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

How to input a calculated value after form validation in zf2

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

我假设我想设置这样的值,但还没有找到设置发送到数据库的 "element" 的正确代码:

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);
}

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);

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();
    }
}