我正在创建一个select,它接受一个名为category的实体数据。
我想要开发的选择基本上与我开发和使用的选择相同,但是我从类别实体获取的值。
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use BackendBundle\Entity\Categoria;
use BackendBundle\Entity\CategoriaRepository;
class ProductoType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nombre', TextType::class, array(
'label' => 'Nombre',
'required' => 'required',
'attr' => array(
'class' => 'form-name form-control'
)
))
->add('categoria', ChoiceType::class, array(
'choices' => array(
'General' => '1',
'Coffe' => '2'
),
'required' => false,
'empty_data' => null
))
->add('Save', SubmitType::class, array(
"attr" =>array(
"class" => "form-submit btn btn-success"
)
))
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'BackendBundle\Entity\Producto'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'backendbundle_producto';
}
}
我会添加如下所示的部分,但是我收到错误无法加载类型"实体"
->add('categoria', 'entity', array(
'class' => 'BackendBundle:Categoria'
)
)
原始BBDD记录在Object of class \BackendBundle\Entity\Categoria could not be converted to string
中答案 0 :(得分:1)
'entity'应该是EntityType :: class, 您应该使用EntityType的类名而不仅仅是'entity'字符串
请参阅: https://github.com/symfony/symfony/blob/master/UPGRADE-3.0.md#form
答案 1 :(得分:1)
首先,如果您使用的是symfony 3,则必须使用Symfony\Bridge\Doctrine\Form\Type\EntityType
,该类应该是类名而不是实体名
->add('categoria', 'Symfony\Bridge\Doctrine\Form\Type\EntityType', array(
'class' => 'BackendBundle\Entity\Categoria'
)
)
和categoria应该是这样的:
namespace BackendBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table()
* @ORM\Entity()
*/
class Categoria
{
/**
* @var int
*
* @ORM\Id
* @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string")
*/
protected $name;
public function __toString()
{
return $this->name;
}
}