I use Symfony 2.6 (I know, deprecated soon). I want to create a web page that contains the same form 5 or 6 times (to create User) because one User can create limited numbers of others Users. So I can't use FormBuilder because you can't display several times. Then I created normals HTML Forms:
<form class="fcrv" action="{{ path('path') }}" method="POST">
<input type="text" name="Name" placeholder="Name"/>
<textarea rows="4" cols="50" name="comm"></textarea>
<input type="submit" value="Validate">
</form>
I Handle Form by Form with Ajax and I sent the data needed in my Controller. I can get data in Controller with :
$name = $request->request->get('Name');
$comm = $request->request->get('comm');
It's work. After this I want to Simulate the behavior of a normal Form. I need to create my new Form and put the data in, so I did :
//create a new User
$user = new User();
$user->setCreateDate(new Date());
//Create the form
$form = $this->createForm(new UserType(), $user);
$form->setData(array('name'=>$name));
$form->setData(array('comm'=>$comm));
$form->submit($request->request->get($form->getName()));
if ($form->isValid()) {
//Some actions
}
My UserType :
<?php
namespace Test\Bundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UserType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text')
->add('comm', 'text')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Cfau\CleBundle\Entity\FraisVisite',
'csrf_protection' => false
));
}
/**
* @return string
*/
public function getName()
{
return 'test_bundle_user';
}
}
And the conditions in entity User is just : @Assert\NotBlank()
But the form isn't valid !
I disable CSRF token.
I use
echo $form->getErrors(true, false);
to see what wrongs with my form and it say : name: ERROR: This value should not be blank. But I put data with $form->setData(array('name'=>$name)); !
Can you help me. Thanks !