Stepan Yudin
Stepan Yudin

Reputation: 480

Symfony2: append getter constraint error to the field

Good day everyone!

The problem

I cant find the solution to append getter validation error to specific field in the form.

I have a method Presale::hasPresaleProductsAdded() in my entity. This method returns true or false regarding on amount of products added to collection

After submitting the form, validation error is bubbled to the parent form (because there is no field "presaleProductsAdded" on the form). I want to attach this error to the "presaleProducts" field.

I know about error_mapping property, but i cant get it working

The code

Here is my validation.yml

OQ\PresaleBundle\Entity\Presale:
    properties:
        name:
            - NotBlank: ~
        description:
            - NotBlank: ~
        company:
            - NotBlank: ~
    getters:
        presaleProductsAdded:
            - "True": { message: "Specify at least one product" }

The possible solution

I know that this problem can be solved with custom validation constraint class. But the question is - can i do it only with validation.yml, entity method and getter constraint

Upvotes: 1

Views: 656

Answers (1)

Stepan Yudin
Stepan Yudin

Reputation: 480

So, i,ve got it.

1) I forgot about error_bubbling option. Presale::presaleProducts property has a custom field type assigned in form. That custom field type is compound field and the parent type is set to "form". In that case error_bubbling is true by default.

Switched to false:

class PresaleProductsType extends AbstractType
{
    ... 

    /**
     * @param OptionsResolverInterface $resolver
     */
    public
    function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' => 'OQ\PresaleBundle\Entity\PresaleProducts',
                'error_bubbling' => false, // That's it!
            ]
        );
    }

    /**
     * @return string
     */
    public
    function getName()
    {
        return 'oq_presale_products';
    }

    /**
     * @return string
     */
    public
    function getParent()
    {
        return 'form';
    }

    ...

}

2) The error_mapping option in PresaleType form was configured like that: 'hasPresaleProductsAdded' => 'presaleProducts'

The mistake is in the property path name: symfony did not found the public $hasPresaleProductsAdded; and tried to find public getter (or isser or hasser) like:

  • Presale::getHasPresaleProductsAdded()
  • Presale::hasHasPresaleProductsAdded()
  • Presale::isHasPresaleProductsAdded()

But there is only Presale::hasPresaleProductsAdded() in the entity class definition.

So, i fixed error_mapping option:

'error_mapping' => array(
    'presaleProductsAdded' => 'presaleProducts', 
),

And everything start working like a charm!

Upvotes: 2

Related Questions