是否可以为zend表单编写验证器,检查用户是否有权更改表单字段?表示用户看到该字段,但如果未经许可即尝试(没有acl权限),他会收到错误消息?后续这意味着如果不允许用户更改字段,则停用字段。
答案 0 :(得分: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;
}