Agnes D
Agnes D

Reputation: 461

Symfony2 embed form: error not displayed

I have an order and a product entity

class Order {

    /**
     * @ORM\OneToMany(targetEntity="Product", mappedBy="order", cascade={"persist", "remove"}))
     * @Assert\Valid()
     * @Assert\Count(
     *      min = "1"
     * )
     */
     protected $products;
}

and

class Product
{
    /**
     * @ORM\ManyToOne(targetEntity="Order", inversedBy="products")
     * @ORM\JoinColumn(name="id_order", referencedColumnName="id", onDelete="CASCADE", nullable=false)
     */
    protected $order;

    /**
     * @ORM\ManyToOne(targetEntity="Category")
     * @ORM\JoinColumn(name="id_category", referencedColumnName="id", nullable=false)
     */
    protected $category;

    /**
     * @ORM\ManyToOne(targetEntity="Size")
     * @ORM\JoinColumn(name="id_size", referencedColumnName="id", nullable=true)
     */
    protected $size;


    /**
     * @Assert\IsTrue(message = "Please enter a size")
     */
    public function isSizeValid()
    {
        if($this->category->getCode() == 1 && is_null($this->size)) {
            return false;
        }
        return true;
    }

}

in my orderType form, I have added a collection of ProductTypes, with error_bubbling set to false. But when my isSizeValid is false, I do not have any error message on my form.

But when I set error_bubbling to true, the error is displayed on top of my form.

How can I display the error next to each product in my twig template?

Upvotes: 4

Views: 358

Answers (2)

galeaspablo
galeaspablo

Reputation: 885

Use an Assert\Callback function, such that you put your domain logic where it belongs... in your Entity. And then use error_bubbling=false, such that the error is displayed on top of "size".

use Symfony\Component\Validator\Context\ExecutionContextInterface;
//...

class product
{
    //...

    /**
     * @param ExecutionContextInterface $context
     *
     * @Assert\Callback
     */
    public function validate(ExecutionContextInterface $context)
    {
        //someLogic to define $thereIsAnError as true or false
        if($this->category->getCode() == 1 && is_null($this->size)) {
            $context->buildViolation('Please enter a size.')
                ->atPath('size')
                ->addViolation();
        } 
    }
}

Read more about using Assert\Callback at http://symfony.com/doc/current/reference/constraints/Callback.html

If you still have issues, then please also post your Twig template.

Upvotes: 1

Alsatian
Alsatian

Reputation: 3135

You have to set the option 'error_mapping' in your form.

http://symfony.com/doc/current/reference/forms/types/form.html#error-mapping

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'error_mapping' => array(
            'isSizeValid' => 'product',
        ),
    ));
}

Upvotes: 1

Related Questions