【问题标题】:How to validate Checkbox in Zend Framework 2?如何验证 Zend Framework 2 中的复选框?
【发布时间】:2014-03-01 11:41:20
【问题描述】:

所以我想要的是在我的表单中验证我的 Checkbox 并检查它是否被选中,所以我应该在我的数据库中将它保存为 1,否则保存为 0,如下所示:

$this->add(array(
            'name' => 'publication',
            'type' => 'Zend\Form\Element\Checkbox',

            'options' => array(
                    'checked_value' => 1,
                    'unchecked_value' => 0,
            ),
    ));

但是当我尝试时,我的数据库中出现了 Null !!,有关更多详细信息,我将编写一些代码,

这是我的看法:

    <label>Publication:</label>
    <?php
         echo $this->formInput($form->get('publication'));
    ?>

这是我的实体:

/**
 * @ORM\Column(name="publication", type="boolean")
 */
protected  $publication;

/**
 * Set publication
 *
 * @param boolean $publication
 * @return Article
 */
public function setPublication($publication)
{
    $this->publication = $publication;

    return $this;
}

/**
 * Get publication
 *
 * @return boolean 
 */
public function getPublication()
{
    return $this->publication;
}

public function exchangeArray($data)
{
   $this->publication  = (isset($data['publication']))  ? $data['publication']  : null;
}

 public function getInputFilter()
  {
    if (!$this->inputFilter) {
        $inputFilter = new InputFilter();

            $inputFilter->add(array(
                'name'     => 'publication',
                'required' => false,
        ));

如果有人有任何解决方案,我将不胜感激:)

【问题讨论】:

  • 向您的复选框元素添加一个布尔过滤器,您就完成了。 $form->getData() 将包含真/假,所有 ORM/TableGateway 将分别将其转换为 1/0。
  • 是的,我试图找到它,但我没有发现任何有用的东西

标签: php zend-framework zend-framework2 zend-form


【解决方案1】:

如果未勾选复选框,则该复选框不包含在帖子中。在您的 exchangeArray 中,在这种情况下您将其设置为 null。

【讨论】:

  • 谢谢@dualmon,你说得对,我没注意:(,我把它改成:$this->publication = (isset($data['publication']))?真:假;
猜你喜欢
  • 2017-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多