我希望在我的控制器中使用一个表单,但每次都会出现以下错误:
Could not load type "locality"
以下是表格类:
class LocationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$factory = $builder->getFormFactory();
$builder->add('province','entity',array(
'class' => 'Acme\DemoBundle\Entity\Province',
'property' => 'name'));
$refreshLocality = function ($form, $province) use ($factory) {
$form->add($factory->createNamed('entity','locality',null, array(
'class' => 'Acme\DemoBundle\Entity\Locality',
'property' => 'name',
'label' => 'Locality',
'query_builder' => function (EntityRepository $repository) use ($province) {
$qb = $repository->createQueryBuilder('locality')
->innerJoin('locality.province', 'province');
if($province instanceof Province) {
$qb = $qb->where('locality.province = :province')
->setParameter('province', $province);
} elseif(is_numeric($province)) {
$qb = $qb->where('province.id = :province_id')
->setParameter('province_id', $province);
} else {
$qb = $qb->where('province.id = 1');
}
return $qb;
}
)));
};
$builder->add('address','text',array(
'required' => false));
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($refreshLocality) {
$form = $event->getForm();
$data = $event->getData();
if($data == null)
$refreshLocality($form, null); //As of beta2, when a form is created setData(null) is called first
if($data instanceof Location) {
$refreshLocality($form, $data->getLocality()->getProvince());
}
});
$builder->addEventListener(FormEvents::PRE_BIND, function (FormEvent $event) use ($refreshLocality) {
$form = $event->getForm();
$data = $event->getData();
if(array_key_exists('province', $data)) {
$refreshLocality($form, $data['province']);
}
});
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\Location'
));
}
public function getName()
{
return 'acme_demobundle_locationtype';
}
}
然后我在我的控制器中调用了这个类:
public function indexAction()
{
$form = $this->get('form.factory')->create(new \Acme\DemoBundle\Form\LocationType());
$request = $this->get('request');
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
}
}
return array('form' => $form->createView());;
}
在这里我的树枝:
<form action="{{ path('_demo') }}" method="POST" id="contact_form">
{{ form_errors(form) }}
{{ form_rest(form) }}
<input type="submit" value="Send" class="symfony-button-grey" />
</form>
当我遇到上述错误时,我尝试在service.xml中的服务部分注册表单:
<service id="form.type.acme_demobundle_locationtype" class="Acme\DemoBundle\Form\LocationType">
<tag name="form.type" alias="acme_demobundle_locationtype" />
</service>
但我得到同样的错误,任何想法?
答案 0 :(得分:0)
您需要将传递的参数交换为createNamed()
:
$form->add($factory->createNamed('entity','locality',null, array(
应该是
$form->add($factory->createNamed('locality', 'entity', null, array(
事实上,您甚至可以将代码简化为
$form->add('locality', 'entity', array(