Skip to content

Creating custom widget instance validation is weird due to controller type mismatch #27397

Closed
@MellenIO

Description

@MellenIO

Summary (*)

See this line of code:

https://github.com/magento/magento2/blob/2.4-develop/app/code/Magento/Widget/Controller/Adminhtml/Widget/Instance/Validate.php#L22

The function \Magento\Widget\Model\Widget\Instance::validate() is type hinted to return either a \Magento\Framework\Phrase or a bool
https://github.com/magento/magento2/blob/2.4-develop/app/code/Magento/Widget/Model/Widget/Instance.php#L294

This means the is_string check is going to fail. This further means that, unless you type cast the phrase to a string, you will not ever get a constructive error message out of the widget validation controller.
This isn't a huge issue for the most part with Magento core because of the frontend validation but for those creating custom widget validation rules it will break.

Examples (*)

$firstResult = __('Test message');
if ($firstResult !== true && is_string($firstResult)) {
    echo 'We have an error!';
}

Does not output anything.

Proposed solution

I think the easiest solution is just to change the validation controller line to the following:

if ($result !== true && (is_string($result) || ($result instanceof \Magento\Framework\Phrase)) {
// ...

On Magento sites with custom validation rules we've gotten around this by adding an afterValidate plugin to \Magento\Widget\Model\Widget\Instance which type casts the result to string (and returns a string for subsequent errors, rather than a phrase).

Metadata

Metadata

Assignees

Labels

Component: WidgetFixed in 2.4.xThe issue has been fixed in 2.4-develop branchIssue: ConfirmedGate 3 Passed. Manual verification of the issue completed. Issue is confirmedIssue: Format is validGate 1 Passed. Automatic verification of issue format passedIssue: Ready for WorkGate 4. Acknowledged. Issue is added to backlog and ready for developmentPriority: P3May be fixed according to the position in the backlog.Progress: doneReported on 2.4.0Indicates original Magento version for the Issue report.Reproduced on 2.4.xThe issue has been reproduced on latest 2.4-develop branchSeverity: S3Affects non-critical data or functionality and does not force users to employ a workaround.Triage: Dev.ExperienceIssue related to Developer Experience and needs help with Triage to Confirm or Reject it

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions