【发布时间】:2015-11-28 09:22:35
【问题描述】:
我正在使用Phalcon 创建一个带有复选框的表单。我使用此代码在我的 PagesForm.php 文件中创建复选框
$this->add(new Check('usesLayout'));
然后在我看来我有
{{ form.render("usesLayout") }}
但是,如果未选中该复选框,则 Phalcon 会抱怨 usesLayout is required。
视图产生的html代码是
<input type="checkbox" id="usesLayout" name="usesLayout" value="1" checked="checked" />
创建带有复选框的 Phalcon 表单以使其接受选中和未选中的正确方法是什么?
期望的结果
查看使用CakePHP时生成的表单后,html输出是
<input type="hidden" name="usesLayout" id="usesLayout_" value="0" />
<input type="checkbox" name="usesLayout" id="usesLayout" value="1" checked="checked" />
这很好用,所以我正在寻找类似的东西。
当前解决方法
在对this question的最终响应中修改代码后,我目前有这个解决方法(我使用它而不是Phalcon\Forms\Element\Check)
namespace Armaware\InBrowserDev\Forms\Element;
use Phalcon\Forms\Element\Check as PhalconCheck;
class Check extends PhalconCheck
{
/**
* Renders the element widget returning html
*
* @param array|null $attributes Element attributes
*
* @return string
*/
public function render($attributes = null)
{
$attrs = array();
if (!is_null($attributes)) {
foreach ($attributes as $attrName => $attrVal) {
if (is_numeric($attrName) || in_array($attrName, array('id', 'name', 'placeholder'))) {
continue;
}
$attrs[] = $attrName .'="'. $attrVal .'"';
}
}
$attrs = ' '. implode(' ', $attrs);
$id = $this->getAttribute('id', $this->getName());
$name = $this->getName();
$checked = '';
if ($this->getValue()) {
$checked = ' checked';
}
return <<<HTML
<input type="hidden" id="{$id}_" name="{$name}" value="0" />
<input type="checkbox" id="{$id}" name="{$name}" value="1"{$attrs}{$checked} />
HTML;
}
}
【问题讨论】: