Reputation: 1289
So I am trying to generate a dynamic select for Product Table form
instead of writing all the options like this: (code from productType
)
->add('id_cat', ChoiceType::class, [
'choices' => [
'cosmetique' =>'1',
'vetement' => '2',
'parfums' => '3',
],
])
I want the choices to be generated from another table Category(id,cat_name)
.
For example instead of 'cosmetique
' it shows cat_name
and instead of 1
it shows id
(and those are values generated from the database from table Category)
I wrote this function that return all the values from table Category in a table $tab
public function cat (CategoryRepository $categoryRepository)
{
$allcat=$categoryRepository->findAll();
$tab=[];
foreach($allcat as $cat)
{
$tab=$cat->getId();
$tab[$tab]=$cat->getCatname();
}
return $tab;
}
I dont know where exactly I should place it? and how to send that $tab
to ProductType.php
page
Upvotes: 0
Views: 100
Reputation: 209
If you have relation between the two entities (and i guess you have) you can easily use the entity type from Symfony to avoid problem like this which will show all the content inside the category table and submit the chosen object to be saved depending on your association :
$builder->add('category', EntityType::class, [
'class' => Category::class,
'choice_label' => 'cat_name',
]);
Or if you want to keep your way you can pass the array as an option to your form but its not a good practice.
Upvotes: 1
Reputation: 1
Why not just make tab[] something like having a field named 'choices' statically built into it before populating and then add every I'd and category to it and return the table and return results of array wherever?
tab['choices']=$cat->getID();
tab['choices'][tab['choices']]=$cat->getCatname();
And then
for each ($choices as $choice)
For each ($choice as $category)
Print_r( $category)
Upvotes: 0