【问题标题】:Cakephp 3 - custom class for radio input labelCakephp 3 - 无线电输入标签的自定义类
【发布时间】:2018-01-15 00:50:25
【问题描述】:

我正在创建一个多无线电传递选项:

$this->Form->radio(
    'edu_tests_items.0.edu_sheets_items_grade_id',
     $eduSheetsGradesItems,
     ['autocomplete' => 'off']
);

每个$eduSheetsGradesItems的内容是这样的:

(int) 0 => [
    'value' => (int) 1,
    'text' => 'Mal',
    'label' => [
        'class' => 'btn btn-danger'
    ],
    'class' => 'btn btn-danger'
],

然后我得到每个单选按钮组的这个 html(这里我只显示第一个标签元素)

<input name="edu_tests_items[0][edu_sheets_items_grade_id]" value="" type="hidden">
<label for="edu-tests-items-0-edu-sheets-items-grade-id-1">
    <input
        name="edu_tests_items[0][edu_sheets_items_grade_id]"
        value="1"
        class="btn btn-danger"
        id="edu-tests-items-0-edu-sheets-items-grade-id-1"
        autocomplete="off"
        type="radio">
    Mal
</label>

我要做的是为标签元素(示例中的btn btn-danger)设置一个特定的类(每个单选按钮标签都不同),但我不知道怎么做。

【问题讨论】:

    标签: css templates cakephp radio-button cakephp-3.x


    【解决方案1】:

    radio小部件不支持单独的radio标签配置,它只支持所有标签的配置(current not properly documented in the Cookbook),可以通过radio()方法的第三个参数传递,比如:

    $this->Form->radio(
        'edu_tests_items.0.edu_sheets_items_grade_id',
        $eduSheetsGradesItems,
        [
            'autocomplete' => 'off',
            'label' => [
                'class' => 'btn btn-danger'
            ]
        ]
    );
    

    您也可以通过模板进行配置,但只能使用 FormHelper::control/input() 方法,但您并非必须这样做。

    所以如果你想对所有标签应用相同的类,那么上面的就可以了。如果您需要应用不同的类做不同的标签,那么您将不得不使用自定义小部件,例如扩展Cake\View\Widget\RadioWidget 并覆盖RadioWidget::_renderLabel() 方法以支持$radio 中可能的label 键参数,映射到您的个人选项集。

    这是一个快速而肮脏的例子:

    protected function _renderLabel($radio, $label, $input, $context, $escape)
    {
        if ($label &&
            isset($radio['label'])
        ) {
            $label = is_array($label) ? $label : [];
    
            if (isset($label['class'])) {
                $radio['label'] = $this->_templates->addClass($radio['label'], $label['class']);
            }
    
            $label = $radio['label'] + $label;
        }
    
        return parent::_renderLabel($radio, $label, $input, $context, $escape);
    }
    

    另见

    【讨论】:

    • 感谢您的帮助。我将采用自定义小部件方式。
    猜你喜欢
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2016-03-30
    • 2023-03-14
    • 1970-01-01
    • 2020-05-10
    相关资源
    最近更新 更多