Yii2: Config global template for all forms fields

痴心易碎 提交于 2019-12-12 00:12:56

问题


I have this:

<?php

use app\models\Location;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Role;
?>

        <?php $form = ActiveForm::begin(); ?>

        <div class="row">
            <div class="col-sm-6">
                <?= $form->field($model, 'roleId', Yii::$app->formtemplate->fieldTemplate())->dropDownList(ArrayHelper::map(Role::find()->all(), 'id', 'name'), array('prompt' => '-- Select a role --', 'class' => 'form-control select2')); ?>
            </div>
            <div class="col-sm-6">
                <?= $form->field($model, 'published')->checkbox(['label' => ''], true)->label($model->getAttributeLabel('published'), ['class' => 'form-label semibold']); ?>
            </div>
        </div>

I think this is unefficient since I have to add the template to each field (I know I can add it per form, but checkbox has a different one, any ideas how to set it globally, for all forms? not only for one form?

So far what I have done is to create a component called FormTemplate to avoid writing the template directly in the view, which is good, but I want to set it globally.

<?php

namespace app\components;

use Yii;
use yii\base\Component;

class FormTemplate extends Component {


    public function fieldTemplate($option = []) {

        $template = [
            'template' => '',
            'labelOptions' => [ 'class' => 'form-label semibold']
        ];

        $icon = '';
        $position = 'right';

        if(!empty($option['position'])) {
            $position = $option['position'];
        }

        if(!empty($option['icon'])) {
            $icon = $this->_setFieldIcon($option['icon']);
        }

        $template['template'] = '<div class="form-group">{label}<div class="form-control-wrapper form-control-icon-'.$position.'">{input}'.$icon.'<div class="error">{error}{hint}</div></div></div>';

        return $template;

    }

    private function _setFieldIcon($option) {

        switch($option) {
            case 'text':
                $icon = '<i class="fa fa-text-width"></i>';
                break;
            case 'password':
                $icon = '<i class="fa fa-key" aria-hidden="true"></i>';
                break;
            default:
                $icon = '';
                break;
        }

        return $icon;

    }


}

Any ideas?

UPDATE

I have noticed ActiveField is a component, so maybe I could do it on global config? someone has done something like that?

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'components' => [
        'activeField' => [
            'template' => '...'
        ]

回答1:


You can create your ActiveField class as :-

<?php
namespace frontend\widgets;

use yii\helpers\ArrayHelper;
use yii\widgets\ActiveField;

class MyActiveField extends ActiveField
{

public $labelOptions = [ 'class' => 'form-label semibold'];

public function init()
{
    $position = ArrayHelper::remove($this->options, 'right');

    $icon = $this->_setFieldIcon($this->options);

    $this->template ='
                <div class="form-group">{label}
                <div class="form-control-wrapper form-control-icon-'.
                $position.'">
                {input}'.$icon.
                '<div class="error">{error}{hint}
                </div>
                </div>
                </div>';

    parent::init();
}

/**
 * @param $option array
 * @return string HTML
 */
private function _setFieldIcon($option) {
    $icon ='';
    switch(ArrayHelper::getValue($option ,'icon' ,'')) {
        case 'text':
            $icon = '<i class="fa fa-text-width"></i>';
            break;
        case 'password':
            $icon = '<i class="fa fa-key" aria-hidden="true"></i>';
            break;
    }

    return $icon;
}
}

And In ActiveForm use your class as : -

<?php $form = ActiveForm::begin([
    //change this with your active field class
    'fieldClass' => 'frontend\widgets\MyActiveField'
]); ?>

<div class="row">
    <div class="col-sm-6">
        <?= $form->field($model, 'roleId',[
            'options' => ['icon' => '' ,'position' => '']]
        )->dropDownList(ArrayHelper::map(Role::find()->all(), 'id', 'name'), [
            'prompt' => '-- Select a role --', 'class' => 'form-control select2'
        ]); ?>
    </div>

    <div class="col-sm-6">
        <?= $form->field($model, 'published' ,['icon' => '' ,'position' => ''])->checkbox(['label' => ''], true)
            ->label($model->getAttributeLabel('published'), ['class' => 'form-label semibold']); ?>
    </div>
</div>

<?php ActiveForm::end(); ?>



回答2:


If you want to customize ActiveField objects for all your application, you should use Yii2 dependency injection container, e.g. :

\Yii::$container->set('yii\bootstrap\ActiveField', [
    'template' => '...',
]);

Or for ActiveForm :

\Yii::$container->set('yii\bootstrap\ActiveForm', [
    'inputTemplate' => '...',
]);

Read more about practical usage of DI container.



来源:https://stackoverflow.com/questions/38098791/yii2-config-global-template-for-all-forms-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!