1

I have a form that should allow to add an item (device) to a category (brand). Below is a part of the controller that creates the form (the $brand thing doesn't work but I'll figure that out later). Below that is the code that creates my form.

I want my Select box (which is an entitytype of Brand, and shows all possible brands) to also show a default selected value, based on a variable passed down by the controller.

Two questions:

  1. where can I pass this value down?
  2. how can I set a default option for the EntityType select box? I expected it to be 'data' but even hard-coding a number there won't work.

This is the controller bit:

public function createDevice(Request $request, $brand) {
    $device = new Device();
    $form = $this->createForm(DeviceType::class, $device); // where do I pass the value of the default option?
    $form->handleRequest($request);

and the type:

class DeviceType extends AbstractType {

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

        $builder
            ->add('brand', EntityType::class, array(
                'class' => 'AppBundle:Brand',
                'choice_label' => 'name',
                'choice_value' => 'id',
                'data' => '2' // does not set default value to second item!
3
  • Hi, in your code above you can't pass in $brand as an object via TWIG; but you could via the controller. Just trying to help you. If it was a brand ID, then you could use that in a querybuilder. Commented Jul 13, 2016 at 2:49
  • unsure what you mean? I'm not trying to pass objects to twig, I think. I'm a bit new to all of this :) Commented Jul 13, 2016 at 8:29
  • Hi there bluppfisk. You have the code with function: createDevice(Request $request, $brand), and the variable $brand. Are you attempting to pass a brand object in to the function? If so, it needs to be an object. Commented Jul 13, 2016 at 14:52

1 Answer 1

1

Just set Brand into Device.

$em = $this->getDoctrine()->getManager();
$brand = $em->getRepository('AppBundle:Brand')->find(2);
$device = new Device();
$device->setBrand($brand);
Sign up to request clarification or add additional context in comments.

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.