如何在zf2中进行表单验证后输入计算值

时间:2015-02-03 21:35:42

标签: forms validation doctrine-orm zend-framework2

我正在zf2中开发一个表单,我想根据用户输入计算一个值,并在表单验证后将其设置在一个字段中。在表单中,有一个firstName字段和一个lastName字段;并且我想使用经过验证的输入来计算要填充在fullName字段中的值。

我假设我想设置这样的值,但是没有找到用于设置发送到数据库的“元素”的正确代码:

public function addAction()
{
    $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
    $form = new AddMemberForm($objectManager);
    $member = new Member();
    $form->bind($member);

    $request = $this->getRequest();
    if ($request->isPost()) {
      $form->setData($request->getPost());
      if ($form->isValid()) {

        // develop full name string and populate the field
        $calculatedName = $_POST['firstName'] . " " . $_POST['lastName'];
        $member->setValue('memberFullName', $calculatedName);

        $this->getEntityManager()->persist($member);
        $this->getEntityManager()->flush();
        return $this->redirect()->toRoute('admin-members');
      }
    }

    return array('form' => $form);
}

2 个答案:

答案 0 :(得分:1)

Doctrine的内置Lifecycle Callbacks非常适合处理此类要求,我强烈建议您使用它们。

您只需要正确注释实体。

例如:

<?php
/**
 * Member Entity
 */
namespace YourNamespace\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Event\LifecycleEventArgs;

/**
 * @ORM\Table(name="members")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class Member
{
    // After all of your entity properies, getters and setters... Put the method below

    /**
     * Calculate full name on pre persist.
     *
     * @ORM\PrePersist
     * @return void
     */
    public function onPrePersist(LifecycleEventArgs $args)
    {
        $this->memberFullName = $this->getFirstName().' '.$this->getLastName();
    }
}

通过这种方式,实体的memberFullName属性将在实体级 之前使用名字和名字自动填充。

现在,您可以从动作中删除以下行:

// Remove this lines
$calculatedName = $_POST['firstName'] . " " . $_POST['lastName'];
$member->setValue('memberFullName', $calculatedName);

答案 1 :(得分:0)

Foozy优秀的答案提供了一个适用于添加操作的解决方案,对我的评论的响应将我引导到以下适用于添加和编辑操作的解决方案:

<?php
/**
 * Member Entity
 */
namespace YourNamespace\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Event\PreFlushEventArgs;

/**
 * @ORM\Table(name="members")
 * @ORM\Entity
 */
class Member
{
    // After all of your entity properies, getters and setters... Put the method below

    /**
     * Calculate full name on pre flush.
     *
     * @ORM\PreFlush
     * @return void
     */
    public function onPreFlush(PreFlushEventArgs $args)
    {
        $this->memberFullName = $this->getFirstName().' '.$this->getLastName();
    }
}