Zend Image Upload验证问题编辑页面

时间:2012-08-21 08:53:41

标签: image zend-framework file-upload validation

我正在研究Zend Framework 1.11.12版本。在我的添加表单中,我们要放置file upload (for photo upload)字段,并且下面提到的validations as required, file extensions and size specific criteria很少,这是在我的zend形式下声明的:

    // part of my form class (Default_Form_Photo::init)
    $photo = new Zend_Form_Element_File('photo', '', array('required'   => true));
    $photo->setLabel('Photo')
          ->setDestination('/var/www/zendframework/public/uploads/');
    // ensure its mandatory
    #$photo->addValidator('required', true);
    // ensure only one file
    $photo->addValidator('Count', false, array('min' => 1));
    // max 2MB
    $photo->addValidator('Size', false, 2097152)
          ->setMaxFileSize(2097152);
    // only JPEG, PNG, or GIF
    $photo->addValidator('Extension', false, 'jpg,jpeg,png,gif');
    $photo->setValueDisabled(true);
    $this->addElement($photo, 'photo');

现在我已经为hidden field取了edit page,如果没有上传新图片,我会返回当前图片名称:

    // hidden element for edit time photo save
    $this->addElement('hidden', 'photo_uploaded', array( ));

我将hidden element value from controller设置为$form->photo_uploaded->setValue($result['photo'])

现在的问题是:当用户编辑信息时,它不允许保存,因为file upload field is blank没有上传新图像,但在我的情况下必须使用现有的当前图像,我从隐藏元素传递到我的控制员。

因此验证会导致问题,任何想法如何删除我的编辑页面的验证,用户不必每次都上传新图像,他们正在编辑信息。

最感谢的回应将会受到赞赏。

谢谢!

1 个答案:

答案 0 :(得分:2)

答案要求您在表单中添加两个函数:isValid和getValues。首先,删除photo元素中的required,因为我们要在isValid中检查这个:

/**
 * Check if a photo has been submitted. If not, set the form element as required.
 * @param $data Array of values
 * @return Boolean true if all form element requirements are mets
 */
public function isValid($data)
{
 //A photo has not been uploaded this time, nor previously.
 if(!$data['photo'] AND !$data['photo_uploaded'])
 {
  $this->photo->isRequired(TRUE);
 }
 return parent::isValid($data);
}

/**
 * Return an array of form element values
 * @return Array of values
 */
public function getValues()
{
 $values = $this->getValues();

 //if photo has been uploaded, but no previous photos have been uploaded, then set photo_uploaded value.
 if($values['photo'] AND !$values['photo_uploaded'])
 {
  $values['photo_uploaded'] = $values['photo'];
 }

 //if previous photo has been uploaded, but photo has not been uploaded this time, set photo value
 if($values['photo_uploaded'] AND !$values['photo'])
 {
  $values['photo'] = $values['photo_uploaded'];
 }

 return $values;
}