Current Path : /data/web/virtuals/51568/virtual/www/subdom/pomucky/src/form/ |
Current File : /data/web/virtuals/51568/virtual/www/subdom/pomucky/src/form/CheckboxgroupField.php |
<?php namespace app\form; use app\Model; use app\Application; class CheckboxgroupField { public $model; public $attribute; /* [['label' => '...', 'value' => '...'], ... ] */ public $checkboxes = []; public $values = []; public function __construct(Model $model, string $attribute, array $checkboxes, array $values) { $this->model = $model; $this->attribute = $attribute; $this->checkboxes = $checkboxes; $this->values = $values; } public function __toString(): string { $hasError = $this->model->hasError($this->attribute) ? 'is-invalid' : ''; $redColor = $this->model->hasError($this->attribute) ? 'text-danger' : ''; if (Application::$app->request->getMethod() === 'post') { $this->values = $this->model->{$this->attribute}; } $cbgroup = ''; foreach($this->checkboxes as $checkbox) { $checked = in_array($checkbox['value'], $this->values); $cbgroup .= sprintf(' <div id="field-%s" class="form-check"> <input id="%s" class="form-check-input %s" type="checkbox" name="%s[]" value="%s" %s> <label class="form-label %s" for="%s">%s</label> </div> ', $this->attribute . '-' . $checkbox['value'], $this->attribute . '-' . $checkbox['value'], $hasError, $this->attribute, $checkbox['value'], $checked ? 'checked' : '', $redColor, $this->attribute . '-' . $checkbox['value'], $checkbox['label'] ); } $invalidFeedback = sprintf(' <div id="invalid-cbgroup-%s" class="text-danger small">%s</div> ', $this->attribute, $this->model->getFirstError($this->attribute)); return $cbgroup . '<div>' . $invalidFeedback . '</div>'; } }