【发布时间】:2014-12-30 22:32:37
【问题描述】:
我正在尝试为我在 Symfony 2.6.1 中的表单类型传递一个额外的选项,如下所示 (FabricanteForm.php):
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nombre', 'text')
->add('direccion', 'textarea')
->add('telefono', 'text', array(
'required' => TRUE,
'trim' => TRUE,
))
->add('fax', 'text', array(
'required' => FALSE,
))
->add('correo', 'email', array(
'required' => FALSE,
));
if ($options['isFabricante'] !== null)
{
$builder->add('pais', 'text');
}
else
{
$builder->add('pais', 'entity', array(
'class' => 'AppBundle:Pais',
'property' => 'nombre',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('qb')
->where('qb.activo = :activoValue')
->setParameter('activoValue', true);
},
'mapped' => FALSE,
'expanded' => FALSE,
'multiple' => TRUE,
));
}
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setOptional(array(
'isFabricante',
));
$resolver->setDefaults(array(
'data_class' => 'Sencamer\AppBundle\Entity\FabricanteDistribuidor',
'intention' => 'fabricante',
'isFabricante' => null
));
}
然后我在控制器上创建表单如下:
$entityPais = new Entity\Pais();
$formPaisesDistribuidor = $this->createForm(new Form\PaisesForm(), $entityPais, array('isFabricante' => null));
$formPaisesFabricante = $this->createForm(new Form\PaisesForm(), $entityPais, array('isFabricante' => true));
但是我收到了这个错误:
The option "isFabricante" does not exist. Known options are: "action", "allow_extra_fields", "attr", "auto_initialize", "block_name", "by_reference", "cascade_validation", "compound", "constraints", "csrf_field_name", "csrf_message", "csrf_protection", "csrf_provider", "csrf_token_id", "csrf_token_manager", "data", "data_class", "disabled", "empty_data", "error_bubbling", "error_mapping", "extra_fields_message", "inherit_data", "intention", "invalid_message", "invalid_message_parameters", "label", "label_attr", "label_format", "mapped", "max_length", "method", "pattern", "post_max_size_message", "property_path", "read_only", "required", "translation_domain", "trim", "validation_groups", "virtual".
这是在表单类型上设置额外参数的正确方法吗?这是重用表单的最佳方式吗? (您可能注意到$formPaisesDistribuidor 和$formPaisesFabricante 之间的唯一区别是pais 字段类型,第一个是实体,第二个是文本)
有什么帮助吗?建议?
【问题讨论】:
-
如您所见,每种表单类型都有一个特定的选项列表。将参数作为构造函数参数传递是最简单的。
-
@Cerad 奇怪的部分,除非在 2.6.x 上有所改变,否则我在 2.5.x 项目中使用相同的方法。无论如何,我只是尝试一下您的建议,谢谢
-
有趣的是 2.5。我在 2.0 或 2.1 的时候遇到过这个问题。
-
您的方法在 2.6 中应该仍然有效,我只是使用您的方法在我的一个表单上对其进行了测试。
-
@ReynierPM 你应该把这个条件移到symfony.com/doc/current/cookbook/form/…
标签: php symfony symfony-forms