yii2 Изменить тэг метки (label) на спан (span) при выводе поля формы -- ActiveForm, ActiveField
Primary tabs
Если почему-то остро стоит такой вопрос (хотя, логичнее было бы переверстать), можно использовать такое решение:
- Объявляем собственный класс работы с HTML (наследуемся и меняем едниственный метод):
namespace app\helpers\html; class Html extends \yii\helpers\HTML { public static function label($content, $for = null, $options = []) { $options['for'] = $for; return static::tag('span', $content, $options); // вот тут просто поменяли одно слово } }
- Теперь создаём ещё один класс, в которым изменим правило вывода полей формы -- укажем, что нужно использовать новый класс для работы с HTML, который мы создали выше:
<?php namespace app\helpers\es\html; use app\helpers\html\Html as Html; class ActiveField extends \yii\widgets\ActiveField { /** * @var string this property holds a custom input id if it was set using [[inputOptions]] or in one of the * `$options` parameters of the `input*` methods. */ private $_inputId; /** * @var bool if "for" field label attribute should be skipped. */ private $_skipLabelFor = false; /** * Новый лэйбл * * * Generates a label tag for [[attribute]]. * @param null|string|false $label the label to use. If `null`, the label will be generated via [[Model::getAttributeLabel()]]. * If `false`, the generated field will not contain the label part. * Note that this will NOT be [[Html::encode()|encoded]]. * @param null|array $options the tag options in terms of name-value pairs. It will be merged with [[labelOptions]]. * The options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded * using [[Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered. * @return $this the field object itself. */ public function label($label = null, $options = []) { if ($label === false) { $this->parts['{label}'] = ''; return $this; } $options = array_merge($this->labelOptions, $options); if ($label !== null) { $options['label'] = $label; } if ($this->_skipLabelFor) { $options['for'] = null; } $this->parts['{label}'] = Html::activeLabel($this->model, $this->attribute, $options); return $this; } }
-- всё, теперь у нас есть класс, который умеет выводить поля формы нестандартно. С подменой тэга метки.
- Теперь при создании формы (во view), просто укажем ей использовать наш нестандартный класс для вывода полей:
<?php $form = ActiveForm::begin([ 'options' => ['class' => 'form'], 'fieldClass' => 'app\helpers\html\ActiveField',
И всё должно заработать)
- Log in to post comments
- 4832 reads