期望的类型"字符串",MyEntity给出的参数

时间:2016-09-13 15:09:44

标签: symfony

我在FormBuilderInterface中创建了一个下拉列表(类别,子类别)而不是输入文本字段时遇到了问题 当我把它改回文本输入时,一切正常。

这是我的FormType

代码
namespace Expatservice\ManagerBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;

class ServiceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('category', EntityType::class, array(
                'class' => 'ExpatserviceCategoryBundle:Category',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('c')
                    ->where('c.parent = 0')
                    ->orderBy('c.title', 'ASC');
                },
                'choice_value' => 'title',
                'choice_label' => 'title'
            ))
            ->add('subcategory', EntityType::class, array(
                'class' => 'ExpatserviceCategoryBundle:Category',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('c')
                    ->where('c.parent = 2')
                    ->orderBy('c.title', 'ASC');
                },
                'choice_value' => 'title',
                'choice_label' => 'title'
            ))
            ->add('description')
            ->add('image', FileType::class, array('data_class' => null, 'required'=>false));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaultOptions(array('data_class' => 'Expatservice\ManagerBundle\Entity\Service'));
    }

    public function getName()
    {
        return 'expantservice_managerbundle_service';
    }
}

我理解这个问题,但无法弄清楚如何解决问题,而且在互联网上一无所获。

1 个答案:

答案 0 :(得分:0)

在处理表单提交时,我应该使用__toString()魔术函数来获取正确的数据类型。

为了确保我们将获得字符串,实体部分应如下所示:

/**
 * Get title
 *
 * @return string
 */
public function getTitle()
{
    return $this->title;
}

public function __toString() {
    return $this->title;
}