How to validate either Zend_Form_Element_File or Z

2019-05-29 23:24发布

问题:

In my form, I want user to pick a file OR enter it's URL. One of two options.

I know how to write a validator for either one of two Zend_Form_Element_Text elements, but since data from Zend_Form_Element_File is not in $_POST but in $_FILES I don't know where to begin - I can't get the data from Zend_Form_Element_File to be in a $context in isValid($value, $context = null) method for my custom validator.

Any ideas?

回答1:

A possible approach I can think of is to pass the information if the file has been uploaded as additional context to the form's validation method:

Form

$file = new Zend_Form_Element_File('file');

$text = new Zend_Form_Element_Text('text');
$text->setAllowEmpty(false);
$text->addValidator(new TextOrFileValidator());

$this->addElement($file);
$this->addElement($text);

Controller

$request = $this->getRequest();

// provide additional context from the form's file upload status
$context = array_merge(
    $this->getRequest()->getPost(),
    array("isUploaded" => $form->file->isUploaded())
);

if ($request->isPost() && $form->isValid($context)) {
}   

Validator

class TextOrFileValidator extends Zend_Validate_Abstract
{

    const ERROR = 'error';

    protected $_messageTemplates = array(
        self::ERROR      => "You either have to upload a file or enter a text",
    );

    function isValid( $value, $context = null ) {

        $hasText = !empty($context['text']);
        $hasFile = $context['isUploaded'];

        if (($hasText && !$hasFile)
            || (!$hasText && $hasFile)
        ) {
            return true;
        }

        $this->_error(self::ERROR);
        return false;

    }
}