我在尝试在组合框(html 选择标签)usign Symfony2 FormBuilder 中选择默认值时遇到问题。这是我的代码:
MyController.php我发送到Form th 默认省份被选中
$n = new Foo();
$em = $this->getDoctrine()->getEntityManager();
$province = $em->getRepository('MyEntityBundle:SYS_TProvince')->find('ES-M');
$form = $this->createForm(new NewsletterType($province), $n);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
// some action
}
}
NewsletterType.php我在省字段中使用默认省份
class NewsletterType extends AbstractType
{
private $province;
function __construct($province)
{
$this->province = $province;
}
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('idnewsletter', 'hidden');
$builder->add('email', 'email');
$builder->add('type', 'entity',
array('label' => 'type',
'class' => 'MeediamSplashBundle:USR_TType',
'property' => 'description',
'preferred_choices' => array(3,5,7)
));
$builder->add('province', 'entity',
array('label' => 'province',
'class' => 'MeediamSplashBundle:SYS_TProvince',
'property' => 'name',
'data' => $this->province
));
$builder->add('postalcode');
$builder->add('status', 'hidden');
$builder->add('created', 'hidden');
}
public function getName()
{
return 'newsletter';
}
}
SYS_TProvince.php实体
<?php
namespace SciOf\Meediam\SplashBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
* @ORM\Table(name="SYS_TProvince")
*/
class SYS_TProvince
{
/**
* @ORM\Id
* @ORM\Column(type="string", length=5, nullable=false)
*/
protected $idprovince;
/**
* @ORM\Column(type="string", length=3, nullable=false)
* @Assert\NotBlank()
*/
protected $idcountry;
/**
* @ORM\Column(type="string", length=60, nullable=false)
* @Assert\NotBlank()
*/
protected $name;
public function getIdprovince() { return $this->idprovince; }
public function getIdcountry() { return $this->idcountry; }
public function getName() { return $this->name; }
public function setIdprovince($idprovince) { $this->idprovince = $idprovince; }
public function setIdcountry($idcountry) { $this->idcountry = $idcountry; }
public function setName($name) { $this->name = $name; }
public function __toString() { return $this->idprovince; }
}
显然,一切都很好,但它不起作用。如果我使用“preferred_choices”,它可以工作,但我无法通过“数据”选择默认值。
该对象在类中很好,如果我使用 ->getIdProvice() 我会得到对象的 PK,并且因为是字符串而出现错误。
我阅读了一些信息,但我不知道该怎么做:
如何在 Symfony2 中设置表单字段的默认值? http://symfony.com/doc/current/reference/forms/types/field.html
有人看到任何错误吗?