【发布时间】:2014-06-22 08:10:38
【问题描述】:
我想在我的表单中使用“实体”作为字段类型,并在下拉列表中显示记录的名称,并将所选选项的 id 保存到数据库中。
这是我的表单类型:
namespace Acme\DemoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;
use Acme\DemoBundle\Entity\Person;
class ContactType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('subject')
->add('content')
->add('personid','entity', array(
'class' => 'Acme\DemoBundle\Entity\Person',
'query_builder' => function(EntityRepository $repository) {
return $repository->createQueryBuilder('q');
}))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\Contact'
));
}
/**
* @return string
*/
public function getName()
{
return 'acme_demobundle_contact';
}
}
它从数据库中加载记录列表,并在下拉列表中以正确的选项和值(记录的 ID)在 html 表单的标签中显示它们,但不保存选项的值(记录的 ID)到数据库。
如果我使用 _toString(),Symfony 不会显示任何错误,而是保存“0”而不是 id,如果我不使用 _toString() 并设置“'property' => 'name'”,它会显示这个错误:
ContextErrorException: Catchable Fatal Error: Object of class <Path to Entity> could not be converted to string in /symfony/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php line 855
我在这里关注了 Symfony 的文档:http://symfony.com/doc/current/reference/forms/types/entity.html,但没有找到解决方案。
怎么了?
【问题讨论】:
-
person_id 应该是人。我假设你的关系设置正确。
标签: php symfony symfony-2.1 symfony-2.3 symfony-2.4