<?php
namespace Extension;
 use TCMS\ControlExtension;
 use TCMS\TException;
 class SelectDefault extends ControlExtension {
 public $option = [ 'name' => 'category', 'data_source' => null, 'value_member' => 'id', 'display_member' => null, 'group_by' => null, 'display_text' => '-- Chọn --', 'error' => false ];
 public function render($value, $option = null) {
 if(empty($option['name']) || empty($option['value_member']) || empty($option['data_source'])) throw new TException('Vui lòng truyền option cho extension select', 501);
 copy_option($this->option, $option);
 $this->addStyle(asset('/style/bootstrap.min.css'));
 if(empty($this->option['display_member'])) {
 $this->option['display_member'] = $this->option['value_member'];
 }
 if(is_string($this->option['data_source'])) {
 $model = \Model::load($this->option['data_source']);
 if(!$model) {
 throw new TException("Không tìm thấy model " . $this->option['data_source']);
 }
 if(empty($this->option['group_by'])) $selectData = $model->select($this->option['value_member'], $this->option['display_member'])->toArray();
 else $selectData = $model->select($this->option['value_member'], $this->option['display_member'], $this->option['group_by'])->toArray();
 }
 else if(is_array($this->option['data_source'])) {
 $selectData = $this->option['data_source'];
 }
 echo '<select name="'.$this->option['name'].'" class="form-control'. ($this->option['error'] ? ' error' : '') .'" id="'.$this->option['name'].'">';
 if($this->option['display_text'] == null) echo "<option selected value=''>-- Chọn --</option>\n";
 else echo "<option selected value=''>" . $this->option['display_text'] . "</option>\n";
 if(empty($this->option['group_by'])) {
 foreach($selectData as $k => $v) {
 if($value != null && $v[$this->option['value_member']] == $value) echo "<option selected value='". $v[$this->option['value_member']] ."'>".$v[$this->option['display_member']]."</option>\n";
 else echo "<option value='". $v[$this->option['value_member']] ."'>".$v[$this->option['display_member']]."</option>\n";
 }
 }
 else {
 $this->groupDataProc($selectData, $value);
 }
 echo '</select>';
 }
 private function groupDataProc($data, $value, $parent_id = 0, $char = '') {
 foreach ($data as $key => $item) {
 if ($item[$this->option['group_by']] == $parent_id) {
 if($value != null && $item[$this->option['value_member']] == $value) echo "<option selected value='". $item[$this->option['value_member']] ."'>".$char . ' ' . $item[$this->option['display_member']]."</option>\n";
 else echo "<option value='". $item[$this->option['value_member']] ."'>".$char . ' ' . $item[$this->option['display_member']]."</option>\n";
 unset($data[$key]);
 $this->groupDataProc($data, $value, $item[$this->option['value_member']], $char . '---');
 }
 }
 }
 }
 ?>