如何在Zend表单文件元素上使用View脚本?

时间:2010-01-26 23:19:31

标签: zend-framework zend-form decorator zend-view zend-form-element

我将此ViewScript用于标准表单元素:

<div class="field" id="field_<?php echo $this->element->getId(); ?>">
   <?php if (0 < strlen($this->element->getLabel())) : ?>
      <?php echo $this->formLabel($this->element->getName(), $this->element->getLabel());?>
   <?php endif; ?>
   <span class="value"><?php echo $this->{$this->element->helper}(
      $this->element->getName(),
      $this->element->getValue(),
      $this->element->getAttribs()
   ) ?></span>
   <?php if (0 < $this->element->getMessages()->length) : ?>
       <?php echo $this->formErrors($this->element->getMessages()); ?>
   <?php endif; ?>
   <?php if (0 < strlen($this->element->getDescription())) : ?>
      <span class="hint"><?php echo $this->element->getDescription(); ?></span>
   <?php endif; ?>
</div>

尝试单独使用ViewScript会导致错误:

  

表单捕获的异常:没有文件   装饰发现......无法渲染   文件元素

this FAQ揭示了我的部分问题,并更新了我的表单元素装饰器:

'decorators' => array(
   array('File'),
   array('ViewScript', array('viewScript' => 'form/field.phtml'))
)

现在它将文件元素渲染两次,一次在我的视图脚本中,以及在视图脚本之外使用文件元素的额外元素:

<input type="hidden" name="MAX_FILE_SIZE" value="8388608" id="MAX_FILE_SIZE" />
<input type="hidden" name="UPLOAD_IDENTIFIER" value="4b5f7335a55ee" id="progress_key" />
<input type="file" name="upload_file" id="upload_file" />
<div class="field" id="field_upload_file">
    <label for="upload_file">Upload File</label>
    <span class="value"><input type="file" name="upload_file" id="upload_file" /></span>
</div>

有关如何使用ViewScript正确处理此问题的任何想法?


更新:根据Shaun的解决方案,这是我的最终代码:

表格元素:

$this->addElement('file', 'upload_file', array(
    'disableLoadDefaultDecorators' => true,
    'decorators' => array('File', array('ViewScript', array(
        'viewScript' => '_form/file.phtml',
        'placement' => false,
    ))),
    'label' => 'Upload',
    'required' => false,
    'filters' => array(),
    'validators' => array(array('Count', false, 1),),
));

查看脚本:

<?php
$class .= 'field ' . strtolower(end(explode('_',$this->element->getType())));
if ($this->element->isRequired()) {
    $class .= ' required';
}
if ($this->element->hasErrors()) {
    $class .= ' errors';
}
?>
<div class="<?php echo $class; ?>" id="field_<?php echo $this->element->getId(); ?>">
    <?php if (0 < strlen($this->element->getLabel())): ?>
        <?php echo $this->formLabel($this->element->getFullyQualifiedName(), $this->element->getLabel());?>
    <?php endif; ?>
    <span class="value"><?php echo $this->content; ?></span>
    <?php if ($this->element->hasErrors()): ?>
        <?php echo $this->formErrors($this->element->getMessages()); ?>
    <?php endif; ?>
    <?php if (0 < strlen($this->element->getDescription())): ?>
        <p class="hint"><?php echo $this->element->getDescription(); ?></p>
    <?php endif; ?>
</div>

7 个答案:

答案 0 :(得分:19)

答案相对简单。您所需要做的就是首先指定File decorator,为文件输入创建一个特定的视图脚本,并为viewScript装饰器参数中的位置指定false,这将有效地将File装饰器的输出注入viewScript装饰器,例如

$element->setDecorators(array('File', array('ViewScript', array('viewScript' => 'decorators/file.phtml', 'placement' => false))));

然后在新的文件元素视图脚本中,您只需在脚本中回显$ this-&gt;内容,您希望放置文件输入标记。这是最近一个项目的一个例子,如果看起来有点奇怪,请忽略标记,希望它能说明这一点。

<label for="<?php echo $this->element->getName(); ?>" class="element <?php if ($this->element->hasErrors()): ?> error<?php endif; ?>" id="label_<?php echo $this->element->getName(); ?>"> 
<span><?php echo $this->element->getLabel(); ?></span>

<?php echo $this->content; ?>

<?php if ($this->element->hasErrors()): ?>

    <span class="error">
        <?php echo $this->formErrors($this->element->getMessages()); ?>
    </span>

<?php endif; ?>

</label>

渲染时,您将看到元素的

<label for="photo" class="element" id="label_photo"> 
<span>Photo</span>

<input type="hidden" name="MAX_FILE_SIZE" value="6291456" id="MAX_FILE_SIZE">
<input type="file" name="photo" id="photo">

</label>

答案 1 :(得分:4)

这不是一个简单或理想的解决方案,因为它需要File装饰器的扩展......但是他们没有努力将隐藏元素生成逻辑与文件输入生成逻辑分开,这是相当令人沮丧的。我不确定文件视图助手是否处理元素作为数组的问题(这似乎是他们这样做的原因。)

文件装饰器的扩展: (注释掉的部分是导致生成额外输入的原因。)

<?php

class Sys_Form_Decorator_File extends Zend_Form_Decorator_File {

  public function render($content) {

    $element = $this->getElement();
    if (!$element instanceof Zend_Form_Element) {return $content;}

    $view = $element->getView();
    if (!$view instanceof Zend_View_Interface) {return $content;}

    $name = $element->getName();
    $attribs = $this->getAttribs();
    if (!array_key_exists('id', $attribs)) {$attribs['id'] = $name;}

    $separator = $this->getSeparator();
    $placement = $this->getPlacement();
    $markup = array();
    $size = $element->getMaxFileSize();

    if ($size > 0) {

      $element->setMaxFileSize(0);
      $markup[] = $view->formHidden('MAX_FILE_SIZE', $size);

    }

    if (Zend_File_Transfer_Adapter_Http::isApcAvailable()) {

      $apcAttribs = array('id' => 'progress_key');
      $markup[] = $view->formHidden('APC_UPLOAD_PROGRESS', uniqid(), $apcAttribs);

    }

    else if (Zend_File_Transfer_Adapter_Http::isUploadProgressAvailable()) {

      $uploadIdAttribs = array('id' => 'progress_key');
      $markup[] = $view->formHidden('UPLOAD_IDENTIFIER', uniqid(), $uploadIdAttribs);

    }

    /*

    if ($element->isArray()) {

      $name .= "[]";
      $count = $element->getMultiFile();

      for ($i = 0; $i < $count; ++$i) {

        $htmlAttribs = $attribs;
        $htmlAttribs['id'] .= '-' . $i;
        $markup[] = $view->formFile($name, $htmlAttribs);

      }

    }

    else {$markup[] = $view->formFile($name, $attribs);} 

    */

    $markup = implode($separator, $markup);

    switch ($placement) {

      case self::PREPEND: return $markup . $separator . $content;
      case self::APPEND:
      default: return $content . $separator . $markup;

    }

  }

 }

?>

控制器操作中的表单设置:

$form = new Zend_Form();
$form->addElement(new Zend_Form_Element_File('file'));
$form->file->setLabel('File');
$form->file->setDescription('Description goes here.');

$decorators = array();
$decorators[] = array('File' => new Sys_Form_Decorator_File());
$decorators[] = array('ViewScript', array('viewScript' => '_formElementFile.phtml'));
$form->file->setDecorators($decorators);

$this->view->form = $form;

在行动视图中:

<?php echo $this->form; ?>

在元素脚本中:

<div class="field" id="field_<?php echo $this->element->getId(); ?>">

<?php if (0 < strlen($this->element->getLabel())) : ?>
<?php echo $this->formLabel($this->element->getName(), $this->element->getLabel());?>
<?php endif; ?>

<span class="value">
<?php 

echo $this->{$this->element->helper}(

  $this->element->getName(),
  $this->element->getValue(),
  $this->element->getAttribs()

);

?>
</span>

<?php if (0 < $this->element->getMessages()->length) : ?>
<?php echo $this->formErrors($this->element->getMessages()); ?>
<?php endif; ?>

<?php if (0 < strlen($this->element->getDescription())) : ?>
<span class="hint"><?php echo $this->element->getDescription(); ?></span>
<?php endif; ?>

</div>

输出应为:

<form enctype="multipart/form-data" action="" method="post">
<dl class="zend_form">
<input type="hidden" name="MAX_FILE_SIZE" value="134217728" id="MAX_FILE_SIZE" />
<div class="field" id="field_file">
<label for="file">File</label>
<span class="value"><input type="file" name="file" id="file" /></span>
<span class="hint">Description goes here.</span>
</div>
</dl>
</form>

此解决方案的一个问题是隐藏的元素不会在视图中呈现;如果你在客户端脚本中使用div作为选择器,这可能是一个问题......

答案 2 :(得分:2)

我意识到,自定义装饰器类将处理除文件字段之外的大多数字段。 确保您的类实现了如下界面:

class CC_Form_Decorator_Pattern 
extends Zend_Form_Decorator_Abstract 
implements Zend_Form_Decorator_Marker_File_Interface

这对我有用。

答案 3 :(得分:1)

这有助于我解决我的问题。我调整了代码以将文件元素包装在表中。要使其工作,只需从viewdecorator中删除标签,然后按如下方式添加文件元素:

$form->addElement('file', 'upload_file', array(
        'disableLoadDefaultDecorators' => true,
        'decorators' => array(
            'Label',
            array(array('labelTd' => 'HtmlTag'), array('tag' => 'td', 'class' => 'labelElement')),
            array(array('elemTdOpen' => 'HtmlTag'), array('tag' => 'td', 'class' => 'dataElement','openOnly' => true, 'placement' => 'append')),
            'File',
            array('ViewScript', array(
            'viewScript' => 'decorators/file.phtml',
            'placement' => false,
            )),
            array(array('elemTdClose' => 'HtmlTag'), array('tag' => 'td', 'closeOnly' => true, 'placement' => 'append')),
            array(array('row' => 'HtmlTag'), array('tag' => 'tr'))
        ),
        'label' => 'Upload',
        'required' => false,
        'filters' => array(),
        'validators' => array(array('Count', false, 1), ),
    ));

答案 4 :(得分:0)

我找到了一种可以完全避免使用ViewScript的解决方法。

首先,元素定义:

$this->addElement('file', 'upload_file', array(
    'disableLoadDefaultDecorators' => true,
    'decorators' => array(
        'File',
        array(array('Value'=>'HtmlTag'), array('tag'=>'span','class'=>'value')),
        'Errors',
        'Description',
        'Label',
        array(array('Field'=>'HtmlTag'), array('tag'=>'div','class'=>'field file')),
    ),
    'label' => 'Upload File',
    'required' => false,
    'filters' => array('StringTrim'),
    'validators' => array(),
));

其次,在实例化表单类之后,我模仿了我的ViewScript的行为:

$field = $form->getElement('upload_file');
$decorator = $field->getDecorator('Field');
$options = $decorator->getOptions();
$options['id'] = 'field_' . $field->getId();
if ($field->hasErrors()) {
    $options['class'] .= ' errors';
}
$decorator->setOptions($options);

我想我应该研究基于类的装饰器。也许那里有更多的灵活性?

答案 5 :(得分:0)

最简单的方法是在自定义文件修饰器的输出中根本不添加任何标记:

class Custom_Form_Decorator_File extends Zend_Form_Decorator_File {
        public function render($content) {
                return $content;
        }
}

现在,您可以在视图中为此文件元素执行任何操作(输出文件输入字段以及您自己需要的所有隐藏字段)。

答案 6 :(得分:0)

万一你跟随@ Shaun的回答并且你仍然得到错误:确保你已经为相关元素禁用默认装饰器(请看第2行):

$this->addElement('file', 'upload_file', array(
'disableLoadDefaultDecorators' => true,
'decorators' => array('File', array('ViewScript', array(
    'viewScript' => '_form/file.phtml',
    'placement' => false,
))),
'label' => 'Upload',
'required' => false,
'filters' => array(),
'validators' => array(array('Count', false, 1),),
));