我遇到Symfony 2.5的一些问题我需要根据我从控制器传递的一些参数来修改表单,但我无法将$ options数组初始化为任务。
我的档案:
// ordersContrroller.php
$orders=new OrdersM();
$form = $this->createForm(new ListOrdersType(), $orders, array('id'=>1));
// ListOrdersType.php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Event\DataEvent;
use Symfony\Component\Form\FormEvents;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ListOrdersType extends AbstractType
{
public function getDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\MyBundle\Form\Model\OrdersM',
'id'=>1,
));
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
var_dump(array_keys($options));
$builder->add('orders', 'entity', array(
'class' => 'AcmeMyBundle:Orders',
'property' => 'name',
'query_builder' => function($repository) use ($options) {
return $repository->createQueryBuilder('o')
->where('o.id='.$options['id'])
->orderBy('o.id', 'ASC' )
;
}
));
}
public function getName()
{
return 'orders';
}
}
我有两个截然不同的问题。当我把选项数组放在che控制器中时 阵列(' ID' =→1)
我发现以下错误:
选项" id"不存在。已知选项包括:"动作"," attr", " auto_initialize"," block_name"," by_reference"," cascade_validation", "复合","约束"," csrf_field_name"," csrf_message", " csrf_protection"," csrf_provider"," csrf_token_id", " csrf_token_manager","数据"," data_class","禁用"," empty_data", " error_bubbling"," error_mapping"," extra_fields_message", " inherit_data","意图"," invalid_message", " invalid_message_parameters","标签"," label_attr","映射", " max_length","方法","模式"," post_max_size_message", " property_path"," read_only"," required"," translation_domain", " trim"," validation_groups"," virtual"
类似于在声明解析器的默认选项时声明选项。
当我尝试在query_builder函数上的密钥$选项[' id']上使用$ options数组时,我得到以下错误:
注意:未定义的索引:id in **** /表/类型/ ListOrdersType.php 第56行
那个是这个:
->where('o.id='.$options['id'])
id $选项是ony one,但我真的需要在EntityType.php文件中使用不同的参数进行查询,我真的需要以某种方式将它们传递给选项。
我失踪了什么? Tx适合您的时间。
答案 0 :(得分:0)
尝试这样做(getDefaultOptions
更改为setDefaultOptions
):
class ListOrdersType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\MyBundle\Form\Model\OrdersM',
'id'=> null,
));
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('orders', 'entity', array(
...
'query_builder' => function($repository) use ($options) {
return $repository->createQueryBuilder('o')
->where('o.id= :id')
->orderBy('o.id', 'ASC' )
->setParameter('id', $options['id'])
;
}
));
}
...
}
$orders=new OrdersM();
$form = $this->createForm(new ListOrdersType(), $orders, array('id'=>1));