Building a form with dynamic widgets
I have 3 classes : Category
, Parameter
and Product
.
Category
has a one-to-many relationship withParameters
.Product
has a one-to-many relationship withCategory
.Parameters
开发者_运维技巧 are attributes for a product (color, weight, size, brand, etc.).
When I select a category and create a new product I want to create a form with these parameters. How can I do this? Is it possible with symfony form framework? I hope for your help.
I trying do this something like:
class ProductRepository extends EntityRepository
{
public function getParameters()
{
$em = $this->getEntityManager();
$parameters = $em->getRepository('ShopProductBundle:CatParameter')->findAll();
$data = array();
foreach ($parameters as $k => $value) {
$name = $value->getId();
$data[$name] = array("label" => $value->getName());
}
return $data;
}
}
Form Class
class ProductType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('name', 'text', array('label' => 'Name'));
$data = $options['data'];
foreach($data as $k => $item){
$builder->add((string)$k, 'text', array('label' => $item['label']));
}
}
public function getName()
{
return 'shop_productbundle_categorytype';
}
public function getDefaultOptions(array $options){
return array('data_class' => 'Shop\ProductBundle\Entity\Product');
}
}
And create form in action:
$parameters = $em->getRepository('ShopProductBundle:Product')->getParameters();
$form = $this->createForm(new ProductType(), $parameters);
End have exception:
Expected argument of type "Shop\ProductBundle\Entity\Product", "array" given
I guess you're getting this exception because in your controller $parameters
is not a product.
You should build a new product, and add the parameters to it.
Also please have a look to this article. It deals with a problem similar to yours.
As soon as you have setup data class in your form the only object you can get is it's type.
'data_class' => 'Shop\ProductBundle\Entity\Product'
The way I'm adding multiple parameters to a product entity is a collection of form items: How to add collection of items
Or maybe you just want to pass parameters like this:
$parameters = $em->getRepository('ShopProductBundle:Product')->getParameters();
$form = $this->createForm(new ProductType(), null, $parameters);
Or if you would like to have an entity:
$form = $this->createForm(new ProductType(), new Product(), $parameters);
精彩评论