Reputation: 190
I have created a form type like below
/**
* Class CreatePosFormType.
*/
class CreatePosFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', TextType::class, [
'required' => true,
'constraints' => [new NotBlank()],
]);
$builder->add('identifier', TextType::class, [
'required' => true,
'constraints' => [new NotBlank()],
]);
$builder->add('description', TextType::class, [
'required' => false,
]);
$location = $builder->create('location', LocationFormType::class, [
'constraints' => [new NotBlank(), new Valid()],
]);
$location->addModelTransformer(new LocationDataTransformer());
$builder->add($location);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Pos::class,
]);
}
}
In my controller I have get the form and send the request to the form as below:
$form = $this->get('form.factory')->createNamed('pos', CreatePosFormType::class);
$form->handleRequest($request);
But I need instead of sending the request to the form get the data from the request and set the values for individually I have tried like below:
$form->get('name')->setData('john');
But It's not setting the form field value.
If I set the values to form by above the below error occures
{ "form": { "children": { "name": {}, "identifier": {}, "description": {}, "location": {}, } }, "errors": [] }
Upvotes: 1
Views: 698
Reputation: 2629
You can send the mapped class to the form itself. Like this:
public function createPost(Request $request)
{
$pos = new Pos();
$pos->setName('John');
$form = $this->get('form.factory')->createNamed('pos', CreatePosFormType::class, $pos);
}
You can also send in data through the options. Like this:
public function createPost(Request $request)
{
$form = $this->get('form.factory')->createNamed('pos', CreatePosFormType::class, null, ['yourVariable' => $yourVariable]);
}
And in the form class you would catch that in your options.
class CreatePosFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$yourVariable = $options['yourVariable'];
//do stuff with your variable
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Pos::class,
'yourVariable' => null,
]);
}
Upvotes: 1