开发者

Symfony2 Forms: How to add data to a request object before persisting it?

I'm following Symfony2's form processing:

public function createAction()
 {
    $entity  =开发者_如何学编程 new Node();
    $request = $this->getRequest();
    $form    = $this->createForm(new NodeType(), $entity);

    $form->bindRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($entity);

        $em->flush();

The problem is the the "Node" entity has some other fields that aren't populated by the user, but rather by processes in the controller script. These "system generated" values should also be persisted along with the the "user generated" values from the form.

I'm not sure how to add the system values to the entity.

It is a shortcoming in my OOP knowledge, but I can't find any examples in the docs or online. Thanks!


I think you need to add some getXXX/setXXX methods to Node class (or look inside class'es code for them), so your code will look like

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

$entity->setPropertyOne('some value of mine');
$entity->setCurrentUserId($this->get('security.context')
                          ->getToken()->getUser()->getId());
// another entity setters

$em->persist($entity);

Don't know if it would help you in your case, but i suggest reading about Doctrine 2 events here.

I also strongly recommend you reading this (unofficial) Symfony2 book :)


If you want to manage it in entity rather in controller. And if you are ising YML then just add this on YML file

lifecycleCallbacks: 
prePersist: [ doPrePersist  ]

and in the entity just add this method

function doPrePersist() 
{
    $this->publish = true;
    $this->isDeleted = false;
}

If you are using annotation then in the entity just add the annotation tag

/**
 * @ORM\prePersist
 */
function doPrePersist() 
{
    $this->publish = true;
    $this->isDeleted = false;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜