FormType:
class BranchFormType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('name');
}
public function getName() {
return 'branch';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'My\MainBundle\Entity\Branch',
));
}
}
In entity definition:
<field name="name" column="name" type="string" length="255"/>
there is no nullable=true and the field has required attribute when rendered.
Validation.yml:
My\MainBundle\Entity\Branch:
properties:
name:
- NotBlank: ~
Does symfony find this file automatically or do I have to included somewhere? The doc just states that the form uses validation service automatically.
Controller:
$branch = new Branch();
$form = $this->createForm(new BranchFormType(), $branch);
if ($request->isMethod('POST')) {
$form->bindRequest($request);
if ($form->isValid()) {
$em->persist($branch);
$em->flush();
return $this->redirect($this->generateUrl('view_branch'));
}
}
return $this->render('MyMainBundle:Branch:create.html.twig', array(
'form' => $form->createView()
));
On submit I get following error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘name’
cannot be null
So isValid returns true despite the fact that name is empty and continues to persist the entity with empty values. How can isValid return true when the name is empty? ORM definition says nullable=false?`Any ideas? I have no extra validator defined. I use sf2.1
It looks like the validation file is in the right folder:
Make sure you are not using validation groups?
Anyway, I would use
Assertto see if there is something wrong with this validation file:Enable annotations:
Set up your entity:
Can you try this?
Also, you can test the validation like this from your controller: