4

I'm looking for a way to access the data class entity in a symfony2 form builder class.

The reason I need this is because the text on the submit button should change depending on a value of this entity (a value the user cannot change in the form).

so basically I want to do:

if ($this->entity->getVariable() == xxx) {
// do something
} else {
// do something else
}

inside the form builder class

0

2 Answers 2

3

praxmatig pointed me in the right direction, the solution is even easier:

the underlying entity is automatically available as an option named "data", so you can do:

public function buildForm(FormBuilderInterface $builder, array $options) {
   // whatever

   if (isset($options['data'])) {
      switch ($options['data']->getSomeVariable()) {
      // whatever
      }
   }

   // whatever
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you create the form from controller, you can pass anything you want as the options

// AcmeType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $entity = $options['entity'];
}

// AcmeController.php
$form = $this->createForm(new AcmeType(), $entity, array('entity' => $entity));

Or a better but harder way to do this is using the form event

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.