我在symfony2项目中有一个表单,我在其中向构建器添加了一个新的表单元素:
$builder->add('section', 'entity', array(
'class' => 'SciForumVersion2Bundle:Section',
'label' => 'Section',
'property' => 'name',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('s')
->where('s.conference = conference')
->setParameter('conference', $conference);
},
));
$ conference变量来自控制器,我在FormType中设置了这个变量:
private $conference;
public function __construct($conference)
{
$this->conferenceObject = $conference;
}
但后来我收到错误消息:
ContextErrorException: Notice: Undefined variable: conference in ....
行号指向该行:
->setParameter('conference', $conference);
使用时
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('s')
->where('s.conference = :conference')
->setParameter('conference', $this->conference);
},
我收到此错误消息:
FatalErrorException: Error: Using $this when not in object context in..
有什么想法吗?谢谢。
答案 0 :(得分:2)
在FormType __construct()中,您要设置类变量名称时出错:
public function __construct($conference)
{
$this->conference = $conference;
}
在query_builder
参数中,使用类变量作为值,并在DQL部分使用前缀参数名称和':':
$conference = $this->conference;
$builder->add('section', 'entity', array(
'class' => 'SciForumVersion2Bundle:Section',
'label' => 'Section',
'property' => 'name',
'query_builder' => function(EntityRepository $er) use ($conference) {
return $er->createQueryBuilder('s')
->where('s.conference = :conference')
->setParameter('conference', $conference);
},
));
答案 1 :(得分:0)
我将这条线变薄产生错误
->where('s.conference = $conference')
我会是那样的
->where('s.conference = conference')