Lars Ebert-Harlaar
Lars Ebert-Harlaar

Reputation: 3537

How to have a RulesChecker add an error to an associated Model?

In my ContentsTable, I add an application rule like this, making sure at least one ImageEntity is added to the ContentEntity when saving:

public function buildRules(RulesChecker $rules) {
    $rules
        ->add(function($entity, $options) {
            return $entity->get('type') !== 'gallery' || count($entity->images) > 0;
        }, 'validDate', [
            'errorField' => 'images.0.image',
            'message' => 'Lade mindestens ein Bild hoch!'
        ]);

    return $rules;
}

The rule is applied, since the save() fails, but I would have expected the defined error message to appear on this form input in Contents/edit.ctp:

<?php echo $this->Form->input('images.0.image', [
    'label' => 'Neues Bild (optional)',
    'type' => 'file',
    'required' => false
]); ?>

It is, however, not added at all.

How can I set the errorField option to add the error to this field?

Upvotes: 0

Views: 133

Answers (1)

ndm
ndm

Reputation: 60463

Specifying paths isn't possible, also in the entity context the errors are expected to be present on an actual entity object, so even if it were possible to specifiy a path, there would be no entity to set the error on.

You could always modify the entity in the rule yourself, however I'm not overly convinced that this is such a good idea. Anyways, what you'd have to do, is to fill the images property with a list that contains one entity with the proper error on the image field, something along the lines of:

->add(function($entity, $options) {
    if ($entity->get('type') !== 'gallery' || count($entity->images) > 0) {
        return true;
    }

    $image = $this->Images->newEntity();
    $image->errors('image', 'Lade mindestens ein Bild hoch!');

    $entity->set('images', [
        $image
    ]);

    return false;
});

Another option, which to me feels a little cleaner, would be to set the error for the images property, and evaluate it manually in the form, ie something like:

->add(
    function($entity, $options) {
        return $entity->get('type') !== 'gallery' || count($entity->images) > 0;
    },
    'imageCount',
    [
        'errorField' => 'images',
        'message' => 'Lade mindestens ein Bild hoch!'
    ]
);
if ($this->Form->isFieldError('images')) {
    echo $this->Form->error('images');
}

See also

Upvotes: 2

Related Questions