1

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 Answer 1

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;

    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking something similar: $this->params = $this->getRequest()->getParams(); $this->params['fromFile'] = $_FILES['fromFile']['name']; ... $form->isValid($this->params); But it seems dirty and not Zend way... That's why I'm asking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.