在我的 Symfony2 应用程序中,有两个实体:地址和城镇。Address 实体有一个 4 位数的邮政编码属性(“pcNum”),它指的是 Town 实体的 id。一个地址只能有一个邮政编码,因此只能指一个城镇(但是反过来也是可能的:一个城镇可以有更多的邮政编码)。
对于这两个实体,我创建了一个名为 TownType 和 AddressType 的表单。用户可以输入并保存城镇(这很好用)。Address 实体的表单允许用户填写地址,包括邮政编码。邮政编码链接到 Town 实体的 ID。
但是,当我尝试保留从 AddressType 表单中检索到的新地址实体时,我收到了 MySql 错误,即 pc_num 字段(实体中的 pcNum)为空:
SQLSTATE [23000]:违反完整性约束:1048 列 'pc_num' 不能为空
(这是 Address 实体的字段,应该包含一个 Town 的 ref 键。)在持久化 Address 实体之前,它的值不知何故丢失了。如果我在控制器中手动填写该字段,无论用户在表单中输入什么,我都可以保留新地址而不会出现错误。如果我删除到 Town 实体的链接并使用不知道的表单字段,只要邮政编码恰好存在,我也可以安全而不会出错。但是以它应该的方式,使用两种形式和实体关联,我无法让它工作。在过去的几周里,我尝试了很多不同的事情,但我没有想法。下面是我的代码。随意评论任何事情,也许我的整个方法都是错误的。
这是我的城镇实体:
namespace Xx\xBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Check;
/**
*
* Xx\xBundle\Entity\Town
*
* @ORM\Table(name="lib_towns")
* @ORM\Entity
*/
class Town
{
#id
/**
* @ORM\Id
* @ORM\Column(type="integer", length="4", nullable=false)
* @ORM\GeneratedValue(strategy="AUTO")
* @Check\NotBlank()
* @Check\MaxLength(4)
*/
protected $id;
#name
/**
* @ORM\Column(name="name", type="string", length="100", nullable=true)
* @Check\NotBlank()
* @Check\MaxLength(100)
*/
protected $name;
//some more properties
#getters and setters
/**
* Set id
*
* @param integer $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Get id
*
* @return integer $id
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* @return string $name
*/
public function getName()
{
return $this->name;
}
//some more getters ans setters
}
这是我的地址实体:
namespace Xx\xBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Check;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Xx\xBundle\Entity\Town;
/**
*
* Xx\xBundle\Entity\Address
*
* @ORM\Entity
* @ORM\Table(name="addresses")
*/
class Address
{
#id
/**
* @ORM\Id
* @ORM\Column(type="integer", length="6", nullable=false)
* @ORM\GeneratedValue(strategy="AUTO")
* @Check\NotBlank()
* @Check\MaxLength(6)
*/
protected $id;
#town
/**
* @orm\OneToOne(targetEntity="town")
* @ORM\JoinColumn(name="pc_num", referencedColumnName="id", nullable=false)
*/
protected $town;
//some other properties...
#getters and setters
/**
* Set id
*
* @param integer $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Get id
*
* @return integer $id
*/
public function getId()
{
return $this->id;
}
/**
* Set town entity linked to this address
*
*/
public function setTown(town $town = null)
{
$this->town = $town;
}
/**
* Get town entity linked to this address
*
*/
public function getTown()
{
return $this->town;
}
//some other functions...
}
接下来,这是我为地址创建的表单:
namespace Xx\xBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityRepository;
class AddressType extends AbstractType
{
public function buildForm(Formbuilder $builder, array $options)
{
$builder->add('id', 'hidden'); //necessary for updates
$builder->add('town', 'entity', array
(
'label' => 'Postal code (4 digits):*',
'class' => 'XxxBundle:Town',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('t')
->orderBy('t.id', 'ASC'); },
//'empty_value' => '----',
'property'=> 'Id',
'property_path'=> false,
'expanded' => false,
'multiple' => false,
'required' => true
));
$builder->add('street', 'text', array
(
'label' => 'Street:*',
'required' => true
));
//some more fields...
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Xx\xBundle\Entity\Address'
);
}
public function getName()
{
return 'address';
}
}
这是我的地址控制器中的相关操作功能:
public function editAddressAction($id = null)
{
$em = $this->getDoctrine()->getEntityManager();
$address = new Address();
$isNew = is_null($id);
//this also tests positve after a form has been sent
if($isNew)
{
#fill address object with some defaults
$address->setCreated(new \DateTime("now"));
} else
{
#fill address object with existing db data
$address = $em->getRepository('XxxBundle:Address')->find($id);
}
#create form and fill it with address object data
$form = $this->createForm(new AddressType(), $address);
#if form sent: check input
$request = $this->get('request');
if ($request->getMethod() == 'POST')
{
$form->bindRequest($request); //calls setters
if ($form->isValid())
{
//if I leave the following lines in: no error (but also no sense)
//because the pcNum should be retrieved from the form
$pcNum = 2222;
$town = $em->getRepository('XxxBundle:Town')->find($pcNum);
$address->setTown($town);
//end
#persist and flush
$id_unknown = is_null($address->getId());
if($id_unknown)
{
#insert address
$em->persist($address);
} else
{
#update address
$address->setModified(new \DateTime("now"));
$em->merge($address);
}
#commit
$em->flush();
#get id of update or insert and redirect user
$address_id = $address->getId();
return $this->redirect($this->generateUrl('displayAddress', array('id'=>$address_id)));
}
}
return $this->render('XxxBundle:Forms:address.html.twig', array('form'=>$form->createView(), 'new' => $isNew, 'id' => $id));
}
总而言之,这是相关的 Twig 片段:
<form action="{{ path('addAddress') }}" method="post" {{ form_enctype(form) }}>
{{ form_errors(form) }}
<div class="form_row">
{{ form_errors(form.town) }}
{{ form_label(form.town, 'Postal code:*') }}
{{ form_widget(form.town, {'attr': { 'class': 'form_pcNum', 'maxlength': '4', 'size': '4' } } ) }}
</div>
<div class="form_row">
<!-- some more fields here -->
</div>
<div class="form_row">
<button name="btn_add" id="do_add" type="submit" class="" value="btn_add" title="Ok!">Ok</button>
</div>
{{ form_rest(form) }}
</form>
任何帮助表示赞赏......如果您知道相关(工作)示例,那也很棒。干杯!