0

how I can get the object attributes that i use to build this form : controller code

$assistance1 = new Assistance();
$assistance1->setEtudiant($etudiant1);
$form = $this->get('form.factory')->create(new AssistanceType(), $assistance1);

buildform function on the Form class

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('present', 'checkbox',array(
            'required'  => false,
        ))
    ;
}
2
  • Can you be more specific?
    – Jacob
    May 30, 2015 at 20:37
  • i want use $assistance1 attributes on the buildForm function to define a label for checkbox something like : $myobject=$builder->get???(); $value= $myobject->getAttribute();
    – hamza
    May 30, 2015 at 20:42

2 Answers 2

0

You could add $this->assistance1; to AssistenceType and do new AssistenceType($assistence1); But this is not good design imo.

class AssistenceType extends AbstractType
{
    private $assistence1;

    public function __construct($assistence1)
    {
        $this->assistence1 = $assistence1;
    }

    public function buidlForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('present', 'checkbox', array(
            'required' => false,
            'label' => $this->assistence1->getEtudiant()
        ));
    }
}

and use it like this

$form = $this->get('form.factory')->create(new AssistanceType($assistence1), $assistance1);
2
  • i can't use this solution in this case (Collection of Forms): public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('contenu', 'textarea') ->add('date_seance' ,'datetime') ->add('assistances', 'collection', array( 'type' => new AssistanceType(), )) ; } this is an other form that use this form
    – hamza
    May 30, 2015 at 21:16
  • You could use $assistence = $options->getData() inside the buildForm method I guess. And then label => $assistence->getEtudiant().
    – Jacob
    May 30, 2015 at 21:27
0

You should keep in mind that building the form is decoupled from it's data. If you need the form to change based on it's properties, you will need to implement different kinds of event listeners or subscribers. Think of it like this: you only need one builder for many forms.

To implement a listener or subscriber on the form, you will most probably be off easiest to first declare your form type as a service, then register the service you will need to alter the form's behaviour, and tag it as an event listener for the form. This is all in the docs :)

However, the Form component of Symfony tends to be one of the most complex, so don't hesitate to clarify your problem a bit more so I can assist you more effectively.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.