Symfony2 Embeddable Form: Error Not Displaying

I have an order and product object

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 added the ProductTypes set, with error_bubbling set to false. But when my isSizeValid is false, I have no error message in my form.

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

How can I display an error next to each product in a branch template?

+4
source share
2 answers

You need to set the "error_mapping" option 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',
        ),
    ));
}
+1
source

Assert\Callback, , ... Entity. error_bubbling = false, "".

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();
        } 
    }
}

Assert\Callback http://symfony.com/doc/current/reference/constraints/Callback.html

, , Twig.

+1

Source: https://habr.com/ru/post/1648534/


All Articles