我已为SearchField
和SearchForm
及其相应的实体定义了两种表单类型。我的问题是,我无法在POST中handleRequest
并收到此错误:
此表单不应包含额外字段
(如您所见,我设置'allow_extra_fields' => true
)
这有什么问题?
我使用默认表单呈现:
{{ form_start(search_form, {'attr': {'class': 'form-inline' }}) }}
{{ form_widget(search_form) }}
{{ form_end(search_form) }}
这是我的控制器代码:
$searchFormEntity = new SearchForm();
$searchFormWithValues = $this->createForm(new SearchFormType(), $searchFormEntity, array(
'action' => $this->generateUrl('person'),
'method' => 'POST'
));
$searchFormWithValues->add('submit', 'submit', array('label' => 'Buscar'));
$searchFormWithValues->handleRequest($request);
if ($searchFormWithValues->isValid())
{
$entities = $em->getRepository('Person')
->findByCriteria($searchFormWithValues);
}
else
{
foreach ($searchFormWithValues->getErrors() as $key => $error)
{
error_log( $error->getMessage());
}
}
这是我的SearchFormType
:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class SearchFormType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('fields', 'collection', array('type' => new SearchFieldType(),
'allow_add' => false,
'allow_delete' => false,
'by_reference' => false))
->add('submit', 'submit', array('label' => "Buscar"))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\SearchForm',
'allow_extra_fields' => true,
'csrf_protection' => false,
'validation_groups' => false,
));
}
/**
* @return string
*/
public function getName()
{
return 'appbundle_searchform';
}
}
我的SearchFieldType
:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class SearchFieldType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'hidden')
->add('slug', 'hidden')
->add('operators')
->add('value')
->add('choices')
->add('type', 'hidden')
->add('actionFilter')
->add('actionHighlight')
->add('actionShow')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\SearchField'
));
}
/**
* @return string
*/
public function getName()
{
return 'appbundle_searchfield';
}
}
答案 0 :(得分:0)
您正在使用'allow_add' => false
的集合。您必须设置true
。