0

我正在开发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 fieldedit 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没有上传新图像,但在我的情况下必须使用现有的当前图像,我从隐藏元素传递到我的控制器。

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

尽早回复将不胜感激。

谢谢 !

4

1 回答 1

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;
}
于 2012-08-21T09:50:43.440 回答