Reputation: 173
I have an entity ,there is a array type attribute:productKey.I try to add a choice typy to the form to show the productKeys,I wrote codes:
1.my formType:
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('heading','text',array('label'=>'title'))
->add('productKey','choice',array(
'required'=>TRUE,
'label'=>'choose your product',
));
}
2.In my Product entity the productKey is defined:
/**
* @var array $productKey
*
* @ORM\Column(name="productKey", type="array",nullable=true)
*/
private $productKey;
3.In my controller:
$entity = new Product();
$productKey = array("1"=>"one","2"=>"two","3"=>"three");
$entity ->setProductKey($productKey);
$formType = new TicketType($productKey);
$form = $this->createForm($formType,$entity);
return array(
'form'=>$form->createView(),
'entity'=>$entity
);
when I run my project ,the value of productKey can not be listed ! it just appear an empty select chice input. How can i solve it?
Upvotes: 2
Views: 9782
Reputation: 8965
You need to specify the choices using the choices
option in the form type:
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('productKey', 'choice', array(
'choices' => array('1' => 'one', '2' => 'two', '3' => 'three'),
))
;
}
If your choices come from a service, you can create a custom product_key
form type and configure it in the service container.
services:
product_key_form_type:
class: ProductKeyFormType
arguments:
- @product_key_choices_provider
tags:
- { name: form.type, alias: product_key }
This form type would look something like:
class ProductKeyFormType extends AbstractType
{
private $provider;
public function __construct($provider)
{
$this->provider = $provider;
}
public function getDefaultOptions(array $options)
{
return array(
'choices' => $this->provider->getProductKeyChoices(),
);
}
public function getParent(array $options)
{
return 'choice';
}
public function getName()
{
return 'product_key';
}
}
And would be used in your current form type like so:
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('productKey', 'product_key')
;
}
If all of that is too much, you can also add a product_key_choices
option to your form (by adding 'product_key_choices' => array()
to getDefaultOptions
) and just pass the choices in from your controller. This is easier to get up and running, but less portable since you would need to pass this option in every time you use the form.
Upvotes: 8