Skip to content

Commit fce9051

Browse files
committed
Added a new section to explain how to pass options to forms
1 parent 7cb2585 commit fce9051

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

forms.rst

+76
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,82 @@ powerful feature.
540540
Other Common Form Features
541541
--------------------------
542542

543+
Passing Options to Forms
544+
~~~~~~~~~~~~~~~~~~~~~~~~
545+
546+
If you :ref:`create forms in classes <creating-forms-in-classes>`, when building
547+
the form in the controller you can pass custom options to it as the third optional
548+
argument of ``createForm()``::
549+
550+
// src/Controller/TaskController.php
551+
use App\Form\Type\TaskType;
552+
// ...
553+
554+
class TaskController extends AbstractController
555+
{
556+
public function new()
557+
{
558+
$task = new Task();
559+
// use some PHP logic to decide if this form field is required or not
560+
$dueDateIsRequired = ...
561+
562+
$form = $this->createForm(TaskType::class, $task, [
563+
'require_due_date' => $dueDateIsRequired,
564+
]);
565+
566+
// ...
567+
}
568+
}
569+
570+
If you try to use the form now, you'll see an error message: *The option
571+
"require_due_date" does not exist.* That's because forms must declare all the
572+
options they accept using the ``configureOptions()`` method::
573+
574+
// src/Form/Type/TaskType.php
575+
use Symfony\Component\OptionsResolver\OptionsResolver;
576+
// ...
577+
578+
class TaskType extends AbstractType
579+
{
580+
// ...
581+
582+
public function configureOptions(OptionsResolver $resolver)
583+
{
584+
$resolver->setDefaults([
585+
// ...,
586+
'require_due_date' => false,
587+
]);
588+
589+
// you can also define the allowed types, allowed values and
590+
// any other feature supported by the OptionsResolver component
591+
$resolver->setAllowedTypes('require_due_date', 'bool');
592+
}
593+
}
594+
595+
Now you can use this new form option inside the ``buildForm()`` method::
596+
597+
// src/Form/Type/TaskType.php
598+
namespace App\Form\Type;
599+
600+
use Symfony\Component\Form\AbstractType;
601+
use Symfony\Component\Form\Extension\Core\Type\DateType;
602+
use Symfony\Component\Form\FormBuilderInterface;
603+
604+
class TaskType extends AbstractType
605+
{
606+
public function buildForm(FormBuilderInterface $builder, array $options)
607+
{
608+
$builder
609+
// ...
610+
->add('dueDate', DateType::class, [
611+
'required' => $options['require_due_date'],
612+
])
613+
;
614+
}
615+
616+
// ...
617+
}
618+
543619
Form Type Options
544620
~~~~~~~~~~~~~~~~~
545621

0 commit comments

Comments
 (0)