У меня есть php-файл конфигурации, в котором я установил массив с атрибутами для 3 переключателей. В классе Radio у меня есть метод с именем render, который должен выводить переключатели. Переключатели должны быть размещены в теге html fieldset. Проблема, я получаю теги fieldset и legend для каждой кнопки-переключателя. Но я хочу, чтобы переключатели были встроены в 1 набор полей и 1 легенду. Я застрял.
Это конфигурация массива:
<?php
$formConf = [
'kraken' => [
'type' => 'radio',
'id' => 'kraken',
'name' => 'monster',
'label' => 'Kraken',
'radio' => 'checked'
],
'sasquatch' => [
'type' => 'radio',
'id' => 'sasquatch',
'name' => 'monster',
'label' => 'Sasquatch',
'radio' => ''
],
'mothman' => [
'type' => 'radio',
'id' => 'mothman',
'name' => 'monster',
'label' => 'Mothman',
'radio' => ''
]];
Вот класс Radio:
class Radio extends Input {
protected $radio = '';
protected $legend = 'Choose your favorite monster';
public function __construct(array $opts)
{
parent::__construct($opts);
$this->type = 'radio';
if (!isset($opts['radio']) || $opts['radio'] === '' || $opts['radio'] == null) {
$this->radio = '';
}
elseif (isset($opts['radio'])) {
$this->radio = $opts['radio'];
}
}
Этот метод должен генерировать теги html:
public function render() : string
{
$out = '';
$out .= '<fieldset>';
$out .= '<legend>Choose your monster</legend>';
$out .= '<input type="' . $this->type . '"';
$out .= $this->renderRadioChecked();
$out .= '<label for="' . $this->id . '"' . '>';
$out .= $this->label . '</label>';
$out .= '<br/>';
$out .= '</fieldset>';
return $out;
}
protected function renderRadioChecked()
{
$out = '';
if ($this->radio == '') {
$out .= 'id="' . $this->id . '"' . 'name="' . $this->name . '"' . '>';
} else {
$out .= 'id="' . $this->id . '"' . 'name="' . $this->name . '"' . ' checked' . '>';
}
return $out;
}
Ожидаемый результат должен быть:
<fieldset>
<legend>Choose your favorite monster</legend>
<input type="radio" id="kraken" name="monster">
<label for="kraken">Kraken</label><br/>
<input type="radio" id="sasquatch" name="monster" checked>
<label for="sasquatch">Sasquatch</label><br/>
<input type="radio" id="mothman" name="monster">
<label for="mothman">Mothman</label>
</fieldset>
Полная версия с переключателями можно посмотреть здесь: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset
Примечание: у меня уже есть форматег с другими тегами HTML на странице индекса. Вот почему я могу генерировать только набор полей, как указано здесь.