2

I have 2 entities A and B that share common fields, I used a trait to setup those common fields based on (Doctrine inheritance for entities common fields) because I don't want to use a MappedSuperClass.

Setting up a restful post route for entity B, I instantiate a FormBType which data_class maps to B::class, that extends FormCType (contains common fields and 'data_class' maps to nothing).

I tried to use the inherit_data approach with https://symfony.com/doc/current/form/inherit_data_option.html but I don't want that extra key/nested layer in my form (I want a flattened one).

My problem is that validation for the common fields which are in the trait using Assert aren't taken into account and form passes validation with empty strings.

class B {
use CTrait;
}


//trait that has the common fields with ORM mapping and Assert
trait CTrait {
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;

/**
* @ORM\Column(type="string")
* @ORM\Assert\Length(min="2")
*/
private $name;
}


//Common fields formType
class CType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name');
    }
}

//Form using the common fields formType
class BType extends CType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => B::class,
            'csrf_protection' => false,
        ]);
    }
}

1 Answer 1

0

After further checking on Length I realized empty strings are considered valid values and it was still passing through validation using name: "" even though I had Assert\Length(min=2), after adding NotBlank the validation worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.