Search code examples
phpzend-frameworkzend-formzend-acl

ZF Zend Form Validator to check if user is allowed to change field?


is it possible to write a validator for a zend form, which checks if the user has the right to change a form field? Means the user sees the field, but if tries even without permission (no acl right), he receives an error message? subsequent this means a field is deactivated if the user is not permitted to change the field.


Solution

  • Your going to want to use Zend_Acl to check permissions. You will want something like this:

    /** 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;
    }