Php 使用formbuilder在组合框中选择默认值
我在尝试使用Sign Symfony2 FormBuilder在组合框(html选择标记)中选择默认值时遇到问题。这是我的密码: MyController.php我发送到要选择的默认省的表单Php 使用formbuilder在组合框中选择默认值,php,symfony,formbuilder,Php,Symfony,Formbuilder,我在尝试使用Sign Symfony2 FormBuilder在组合框(html选择标记)中选择默认值时遇到问题。这是我的密码: MyController.php我发送到要选择的默认省的表单 $n = new Foo(); $em = $this->getDoctrine()->getEntityManager(); $province = $em->getRepository('MyEntityBundle:SYS_TProvince')->find('ES-M');
$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\u tprovice.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; }
}
如果需要默认值,则需要在创建表单之前在实体中设置默认值
比如$yourEntity->setProvince(“我的默认值”)代码>
但在您的情况下,我不确定setter,您可以添加您的实体吗?我已经发布了实体。我必须在哪里添加此代码?控制器?FormBuilder?对不起,迟到了,您必须在$form=$this->createForm(新时事通讯类型($province),$n)之前添加此内容代码>在你的例子中,$entity应该是$n,你只需要设置你的省(或者如果你在两个实体之间有关系的话设置倍数),希望我很清楚。这是有效的。谢谢……但是,出于好奇,如果我使用的是没有实体类的表单,这是个好问题。我不知道,永远不要尝试,但我认为即使没有实体,你也必须创建一个假的对象来创建你的表单。所以,也许你可以用实体做同样的事情……我已经做了,创建了一个假的“表单实体”,用于FormBuilder。