【问题标题】:Adding style to CakePHP automatically created input div添加样式到 CakePHP 自动创建的输入 div
【发布时间】:2013-10-24 19:24:59
【问题描述】:

CakePHP 创建一个 div,该 div 自动包装其使用 formhelper 构建的任何输入标签,如下所示:

$this->formhelper->input('something');

输出如下所示:

<div class='input'>
    <input />
</div>

我知道有一种方法可以将类添加到输入标签,即

$this->formhelper->input('text', array('class' => 'some_css'));

但是,您将如何向 CakePHP 自动创建的 div 添加样式。这可能是核心需要被破解的地方,但我想知道是否有更好的方法来做到这一点,以便我得到如下内容:

<div class='input other_class_I_want_here'>
    <input />
</div>

感谢任何可以提供帮助的人。

【问题讨论】:

  • 对于初学者,我建议阅读documentation - 也可以在这里使用$this-&gt;Form-&gt;

标签: css cakephp cakephp-2.0 html-input


【解决方案1】:

只需向 div 添加一个新类。

$this->formhelper->input('text', array('div'=>array('class'=>'divClass'),'class' => 'some_css'));

应该实际输出

<div class='input divClass'>
    <input class='other_class_I_want_here' />
</div>

【讨论】:

    【解决方案2】:

    上面的答案当然是正确的。如果您只需要在一个(或几个)特定位置添加一个类,则效果很好。

    但是,任何到达这里的人都在寻找一种将类添加到应用程序范围内的输入 div 包装器的方法(例如:如果您使用的前端框架通常需要将特定的类名添加到输入包装器以启用auto-styles) 有一个 MUCH 更好的解决方案。也就是说,一个自定义的 FormHelper。

    1. 在 App/View/Helper 目录下创建并保存一个文件“MySuperCoolFormHelper.php”

    2. 将以下代码放入文件中:

        App::uses('FormHelper', 'View/Helper');
        
        class MySuperCoolFormHelper extends FormHelper {
    
            protected function _divOptions($options) {
                if(isset($options['div'])
                    $options['div'] .= ' class1 class2 class3'; //note the prefixing space
                else
                    $options['div'] = 'class1 class2 class3';
    
                return parent::_divOptions($options);
            }
        }
    
    1. 要全局使用这个新的表单助手,请将以下代码添加到您的 AppController:
        public $helpers = array(
            'Form' => array(
                'className' => 'MySuperCoolFormHelper'
            )
            //The rest of your helper inits
        );
    
       
    

    ...和 ​​BLAMMO 你完成了!

    【讨论】:

    • 好问题,抱歉遗漏了!!在您初始化 FormHelper 的 AppController 中,您只需稍微不同地初始化它: public $helpers = array( 'Form' => array( 'className' => 'MySuperCoolFormHelper' ) );
    【解决方案3】:

    CakePHP 3: 用于将 'form-group' 应用于 DIV 并将 'form-control' 应用于输入字段

    <?= 
    $this->Form->control('year', [
        'type' => 'select', 
        'value' => $year, 
        'options' => $years, 
        'label' => false, 
        'class' => 'form-control', 
        'templates' => ['inputContainer' => '<div class="form-group">{{content}}</div>']
        ]); 
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      相关资源
      最近更新 更多