2

这可能有点奇怪,但我会尽力解释。基本上我有一个包含用户的表和一个包含客户的表。用户有权查看仅某些客户的数据。所以我想我会为用户权限创建一个单独的表,将用户 ID 和客户 ID 作为外键,每个客户/用户权限有一行。

当管理员使用使用 Zend\Form 的名为 UserForm 的类(以下简称为参考)将新用户添加到数据库时,我还想将表单旁边的所有客户显示为可以选择添加的按钮作为权限。现在,我想我会通过一个 JavaScript 数组来做到这一点,如果客户 ID 被选中/取消选中,它会附加或删除它们,然后将该数组作为隐藏值传递给表单,最后循环遍历数组,将一行插入数组中每个客户 ID 的权限表,并获取已创建的用户 ID。我不确定这是否是最好的方法,但这是我能想到的最好的方法。

希望这至少可以理解。所以,我有一个表格,但我想插入两个不同的表格。我想我的问题是如何将数组作为值传递给表单?以及如何在调用 saveUser() 方法时不仅插入用户表,还插入权限表(我也会在下面发布)。另外,这是一种非常奇怪的做法吗,我对此感到不必要的困难?我很想听听是否有更简单的方法。

我的用户窗体类:

namespace Admin\Form;
use Zend\Form\Form;

class UserForm extends Form
{
public function __construct($name = null)
{
    parent::__construct('user');
    $this->setAttribute('method', 'post');
    $this->add(array(
        'name' => 'userId',
        'attributes' => array(
            'type'  => 'Hidden',
        ),
    ));

    $this->add(array(
        'name' => 'activated',
        'attributes' => array(
            'value' => 1,
            'type'  => 'Hidden',
        ),
    ));
    $this->add(array(
        'name' => 'username',
        'attributes' => array(
            'type'  => 'text',
        ),
        'options' => array(
            'label' => 'Username:',
        ),
    ));
    $this->add(array(
        'name' => 'firstname',
        'attributes' => array(
            'type'  => 'text',
        ),
        'options' => array(
            'label' => 'First name:',
        ),
    ));
    $this->add(array(
        'name' => 'lastname',
        'attributes' => array(
            'type'  => 'text',
        ),
        'options' => array(
            'label' => 'Last name:',
        ),
    ));
    $this->add(array(
        'name' => 'submit',
        'attributes' => array(
            'type'  => 'submit',
            'value' => 'Go',
            'id' => 'submitbutton',
        ),
    ));

}

}

我的 saveUser() 方法

public function saveUser(User $user)
{
    $data = array(
        'firstname'     => $user->firstname,
        'lastname'      => $user->lastname,
        'username'      => $user->username,
        'activated'     => $user->activated,
    );

    $userId = (int)$user->userId;
    if ($userId == 0) {
        $this->tableGateway->insert($data);
    } else {
        if ($this->getUser($userId)) {
            $this->tableGateway->update($data, array('userId' => $userId));
        } else {
            throw new \Exception('User ID does not exist');
        }
    }
}
4

1 回答 1

4

一种方法是使用表单字段集。一个表单可以有多个Fieldset,每个Fieldset可以绑定不同的实体。

当您在实体之间建立一对一关系时,这些很有用

然后,您将创建 teo 实体,例如一个用户实体(正如您已经拥有的)和一个新实体来表示您的权限。

您将为每个对象创建一个 Feildset 并将对象绑定到字段集。(以 UserFieldSet 和 PermissionFieldset 为例)

查看有关表单字段集的部分:

http://zf2.readthedocs.org/en/latest/modules/zend.form.advanced-use-of-forms.html

如果你有一对多的关系,即。一个用户可以拥有许多权限,那么您最好查看表单集合:

http://zf2.readthedocs.org/en/latest/modules/zend.form.collections.html

还有一个为一对多关系动态添加新行的示例。

于 2013-04-25T10:54:45.053 回答