您可以使用我的代码 Fdola.com。利用
<?php
$list_module = new \App\Vendor\Fdola\Forms\CheckBoxList('list_module', ['a' => 'A', 'b' => 'B'], ['a'], ['class' => 'checkBoxList']);
$list_module->setLabel('Module hiển thị banner:');
$list_module->addValidators([
new \Phalcon\Validation\Validator\PresenceOf([
'message' => '<b>:field</b> không được phép rỗng'
])
]);
$this->add($list_module);
<?php
/**
* Created by PhpStorm.
* User: thanhansoft
* Date: 4/29/2016
* Time: 4:21 PM
*/
namespace App\Vendor\Fdola\Forms;
use Phalcon\Http\Request;
use Phalcon\Tag;
class CheckBoxList extends \Phalcon\Forms\Element {
private $_data;
private $_dataOld;
public function __construct($name, $data, $dataOld = null, $attribute = null) {
$this->_data = $data;
$this->_dataOld = $dataOld;
parent::__construct($name, $attribute);
}
public function render($attribute = null) {
$get_value = $this->getValue();
if ($get_value) {
$data = $get_value;
} else {
$data = $this->_dataOld;
}
$tag = new Tag();
$string = '';
if ($this->_data) {
foreach ($this->_data as $key => $value) {
$arr = ['id' => $this->_name . '-' . $key, 'name' => $this->_name . '[]', 'value' => $key];
if ($data && in_array($key, $data)) {
$arr['checked'] = 'checked';
}
$string .= '<label>' . $tag::checkField($arr) . ' ' . $value . '</label>';
}
}
if (isset($this->_attributes['class'])) return '<div class="' . $this->_attributes['class'] . '">' . $string . '</div>';
return $string;
}
}