将 CakePHP FormHelper 与 Bootstrap Forms 一起使用

2022-08-30 14:31:25

CakePHP的FormHelper是您在制作CakePHP应用程序时生成表单的方式。正如人们可能假设的那样,这包括生成输入元素,如下所示:

$this->Form->input('abc');

这将产生如下HTML:

<div class="input text">
  <label for="ModelAbc">Abc</label>
  <input name="data[Model][Abc]" class="" maxlength="250" type="text" id="ModelAbc">
</div>

现在,可悲的是,Bootstrap想要这样的东西:

<div class="control-group">
  <label for="ModelAbc" class="control-label">Abc</label>
  <div class="controls">
    <input name="data[Model][Abc]" class="" maxlength="250" type="text" id="ModelAbc">
  </div>
</div>

如何使 CakePHP 生成此输出?


答案 1

受lericson答案的启发,这是我对CakePHP 2.x的最终解决方案:

<?php echo $this->Form->create('ModelName', array(
    'class' => 'form-horizontal',
    'inputDefaults' => array(
        'format' => array('before', 'label', 'between', 'input', 'error', 'after'),
        'div' => array('class' => 'control-group'),
        'label' => array('class' => 'control-label'),
        'between' => '<div class="controls">',
        'after' => '</div>',
        'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),
    )));?>
<fieldset>
<?php echo $this->Form->input('Fieldname', array(
    'label' => array('class' => 'control-label'), // the preset in Form->create() doesn't work for me
    )); ?>
</fieldset>
<?php echo $this->Form->end();?>

它产生:

<form...>
<fieldset>
<div class="control-group required error">
    <label for="Fieldname" class="control-label">Fieldname</label>
    <div class="controls">
        <input name="data[Fieldname]" class="form-error" maxlength="255" type="text" value="" id="Fieldname"/>
        <span class="help-inline">Error message</span>
    </div>
</div>
</fieldset>
</form>

我基本上添加了“format”和“error”键,并将控件标签类添加到标签元素中。


答案 2

这是 Bootstrap 3 的解决方案

<?php echo $this->Form->create('User', array(
'class' => 'form-horizontal', 
'role' => 'form',
'inputDefaults' => array(
    'format' => array('before', 'label', 'between', 'input', 'error', 'after'),
    'div' => array('class' => 'form-group'),
    'class' => array('form-control'),
    'label' => array('class' => 'col-lg-2 control-label'),
    'between' => '<div class="col-lg-3">',
    'after' => '</div>',
    'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),
))); ?>
<fieldset>
    <legend><?php echo __('Username and password'); ?></legend>
    <?php echo $this->Form->input('username'); ?>
    <?php echo $this->Form->input('password'); ?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>

如果字段需要自己的标签:

<?php echo $this->Form->input('username', array('label' => array('text' => 'Your username', 'class' => 'col-lg-2 control-label'))); ?>

推荐