如何在使用Symfony2保存之前设置或更改实体值

sta*_*wek 2 php entity symfony doctrine-orm

如果它是例如NULL,我想更改实体值.不幸的是我的代码导致异常 - 虽然在数据库中创建了'translation'记录并且getId方法正确返回了id,但似乎没有设置id.

这是非常简单的代码,为什么它不起作用?

public function createAction(Request $request)
{
    $entity  = new Word();
    $form = $this->createForm(new WordType(), $entity);
    $form->bind($request);


    if ($form->isValid()) {

        $em = $this->getDoctrine()->getManager();

        //works fine - database record is created
        if($entity->getIdTranslation() == NULL){
            $translation = new Translation();
            $em->persist($translation);
            $em->flush();
            $entity->setIdTranslation($translation->getId());
        }


        $em->persist($entity);
        //throws exception - Integrity constraint violation: 1048 Column 'id_translation' cannot be null  
        $em->flush();

        return $this->redirect($this->generateUrl('admin_word_show', array('id' => $entity->getId())));
    }

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}
Run Code Online (Sandbox Code Playgroud)

编辑:添加了我的模型和映射信息的一部分:

过度模型的一部分

Revelant Words mappings:

 /**
 * @var integer $id_language
 *
 * @ORM\Column(name="id_language", type="integer")
 */
private $id_language;
/**
 *@ORM\ManyToOne(targetEntity="Language", inversedBy="words")
 *@ORM\JoinColumn (name="id_language", referencedColumnName="id")
 */
protected $language;

/**
 *
 * @ORM\ManyToOne(targetEntity="Translation", inversedBy="words")
 * @ORM\JoinColumn(name="id_translation", referencedColumnName="id")
 */
protected $translation;
Run Code Online (Sandbox Code Playgroud)

和翻译:

class Translation
 {

public function __construct() {
    $this->words = new ArrayCollection();
}
/**
 * @ORM\PrePersist()
 */
public function prePersist() {
    $this->created_date = new \DateTime();
}
 /**
 *
 * @ORM\OneToMany(targetEntity="Word" ,mappedBy="translation")
 */
protected $words;
Run Code Online (Sandbox Code Playgroud)

另外注意:我使用数据库建模软件(工作台)而不是Symfony控制台工具创建了我的数据库模型,现在我正在尝试设置实体以反映数据库模型.我不确定它的正确方法 - 也许我的模型太复杂而无法与Doctrine一起使用?

Tur*_*tan 9

生命周期回调

有时,您需要在插入,更新或删除实体之前或之后执行操作.这些类型的操作称为" 生命周期 "回调,因为它们是您需要在实体生命周期的不同阶段执行的回调方法(例如,插入,更新,删除实体等).

生命周期回调应该是与内部转换实体中的数据有关的简单方法(例如,设置创建/更新的字段,生成段塞值)

如果你需要做一些更重的提升 - 比如执行记录或发送电子邮件 - 你应该将外部注册为事件监听器或订阅者,并让它访问你需要的任何资源.有关更多信息,请参阅如何注册事件监听器和订户.