2

是否可以为 zend 表单编写验证器,用于检查用户是否有权更改表单字段?意味着用户看到了该字段,但如果即使在没有许可的情况下尝试(没有 acl 权限),他会收到错误消息?随后,这意味着如果不允许用户更改字段,则禁用该字段。

4

1 回答 1

1

您将要用于Zend_Acl检查权限。你会想要这样的东西:

/** Application_Validate_HasEditRights::isValid()**/
public function isValid($value, $context = array())
{
    // Set in form or element using $this->setResource()
    $resource  = $this->_resource;
    // Set in form or element using $this->setPrivilege()
    $privilege = $this->_privilege;

    if ( empty($resource) || empty($privilege) ) {
        throw new Zend_Exception("Validator requires a resource and privilege");
    }

    // Set in form or element $this->setOriginalValue()
    $original  = $this->_originalValue;
    $isEdit = false;
    // Check if original matches new value
    if ($original != $value) {
        $isEdit = true;
    }
    /** Get ACL **/
    $acl  = new Zend_Acl();
    $acl->addRole('guest');
    $acl->addRole('administrator', 'guest');

    $acl->addResource('form');
    // $acl->allow('role', 'resource', array('privilege'));
    $acl->allow('guest','form', array('limited')); // arbitrary resource and privilege names
    $acl->allow('administrator','form', array('full-access'));

    // Get the role of the logged in user; this may be different from how you store it
    $role = Zend_Auth::getInstance()->getIdentity()->role;

    // Check if the role has access to this form
    if ( $isEdit && !$acl->isAllowed($role, $resource, $privilege) ) {
        // Set Error message
        $this->_error(self::INVALID_PRIVILEGES);
        return false;
    }

    return true;
}
于 2011-07-15T17:10:23.033 回答