0

I have in my ListProductsController variable $parentId. I want to get $parentId value and to use it in my SearchProductType:

  public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('price',EntityType::class,[
            'class'=>Product::class,
            'choice_label'=>'price',
            'choice_value'=>'price',
            'placeholder'=>'Default',
            'query_builder' => function (EntityRepository $er){
                return $er->createQueryBuilder('product')
                    ->innerJoin('product.category','c')
                    ->addSelect('c')
                    ->innerJoin('product.manorwomen','m')
                    ->addSelect('m')
                    ->where('c.parent_id=1')

            },
            'expanded'=>false,
            'multiple'=>false
        ])
        ->add('submit',SubmitType::class)
    ;
}

c.parent_id must be equal to $parentId from controller

->where('c.parent_id=$parentId')

How to do that?

2
  • Please, remove “[SOLVED]” from title: accepting an answer is the way to mark it as solved. Commented May 18, 2018 at 18:05
  • Done,thank you for the help!!! Commented May 18, 2018 at 18:51

2 Answers 2

8

Pass it as a required (mandatory) option to your SearchProductType form

/**      
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setRequired([
        'parentId',
    ]);
}

Then pass it when creating the form in ListProductsController

$form = $this->createForm(SearchProductType::class, $objName,
  ['parentId' => $parentId], //or whatever the variable is called
);

Finally use it

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $parentId = $options['parentId'];
    $builder->add('price',EntityType::class,[
        [...]
        'query_builder' => function (EntityRepository $er) use ($parentId) {
                [...]
                ->where('c.parent_id=' . $parentId)

        },
    ]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

HI can you try like this

controller

$data = array("parentId" => $parentId));
$form = $this->createForm(new ExampleFormType($data), $objName);

form

class ExampleFormType extends AbstractType {
    public $data = array();
    public function __construct($data) {
         $this->data = $data;  // Now you can use this value while creating a form field for giving any validation.
    }
}

you can access parentId from $data array

1 Comment

I suppose they could try it but it won't work. At least not since Symfony 2.7. Things have changed in the last 5 years or so.

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.