Symfony 4:如何从Controller传递变量至FormType
Alright, let's get this sorted out. To use your $parentId from the ListProductsController in the SearchProductType's query builder, you'll need to share the variable via Symfony form options and safely inject it into your query (avoiding direct string interpolation to prevent SQL injection). Here's the step-by-step solution:
Step 1: Add the Variable to Your FormType's Options
First, update your SearchProductType to accept parent_id as a configurable option. Add or modify the configureOptions method:
use Symfony\Component\OptionsResolver\OptionsResolver; class SearchProductType extends AbstractType { // ... your existing buildForm method public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ // Define the option with a default value (adjust as needed) 'parent_id' => null, ]); // Optional: Uncomment if parent_id is a required value // $resolver->setRequired(['parent_id']); } }
Step 2: Pass the Variable from the Controller
In your ListProductsController, pass the $parentId as an option when creating the form:
// Inside ListProductsController $parentId = 1; // Replace with your actual variable value $form = $this->createForm(SearchProductType::class, null, [ 'parent_id' => $parentId, ]);
Step 3: Use the Variable in the Query Builder (Safely)
Back in the buildForm method of SearchProductType, access the parent_id from the $options array and use parameter binding in your query builder (never directly insert the variable into the query string—it's a major security risk):
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) use ($options) { return $er->createQueryBuilder('product') ->innerJoin('product.category','c') ->addSelect('c') ->innerJoin('product.manorwomen','m') ->addSelect('m') ->where('c.parent_id = :parentId') ->setParameter('parentId', $options['parent_id']) }, 'expanded' => false, 'multiple' => false ]) ->add('submit', SubmitType::class) ; }
Critical Reminder:
Always use parameter binding (setParameter) instead of directly interpolating variables into your query string—this protects your application from SQL injection attacks, which is non-negotiable for secure code.
内容的提问来源于stack exchange,提问作者Борислав Якимов

