有没有办法在
<label>
之后加载<input>
。默认情况下,CakePHP 在 <label>
之前加载 <input>
,如下所示:
PHP代码:
<?php echo $this->Form->input('email', ['placeholder' => 'Email']); ?>
生成的代码:
<label for="email">Email</label>
<input name="email" placeholder="Enter your email" id="email" type="email">
但是当我想得到这样的东西时我该怎么办:
<input name="email" placeholder="Enter your email" id="email" type="email">
<label for="email">Email</label>
除了破解一些东西之外,还有什么方法可以做到这一点吗?
您可以使用模板功能,负责此功能的模板是
formGroup
模板,默认情况下是 {{label}}{{input}}
。
echo $this->Form->input('email', [
'placeholder' => 'Email',
'templates' => [
'formGroup' => '{{input}}{{label}}'
]
]);
还可以通过遵循命名约定(即类型名称,后跟
FormGroup
)来定义每个输入类型的表单组模板。因此,对于 email
类型,将是 emailFormGroup
。
echo $this->Form->create(null, [
'templates' => [
'emailFormGroup' => '{{input}}{{label}}',
'textFormGroup' => '{{input}}{{label}}'
// ...
]
]);
这样您就可以轻松地将此选项全局应用到特定类型。
另请参阅 Cookbook > Form Helper > 自定义 FormHelper 使用的模板
当然你也可以使用CSS,有表格
.input.email {
display: table;
width: 100%;
}
.input.email input {
display: table-header-group;
}
.input.email label {
display: table-footer-group;
}
弹性盒订购
.input.email {
display: flex;
flex-flow: column;
}
.input.email input {
order: 1;
}
.input.email label {
order: 2;
}
等等...
您必须使用 FormHelper
的
label()方法,如下所示:
<?php
echo $this->Form->input('email', ['placeholder' => 'Email', 'label' => false]);
echo $this->Form->label('email', 'Email');
?>
另一种方法是创建一个自定义帮助程序并使用 @Choma 建议的方式覆盖现有的帮助程序。
所以你必须添加你的
//View/Helpers/MyCustomFormHelper.php
App::uses('FormHelper', 'View/Helper');
MyCustomFormHelper extends FormHelper{
public function input($fieldName, $options) {
$defaults = array_merge($options, array('label' => false))
echo parent::input($fieldName, $defaults);
echo parent::label(fieldName);
}
}
//AppController.php
class AppController extends Controller {
public $helpers = array(
'Form' => array(
'className' => 'MyCustomFormHelper'
)
);
}
或者您可以使用 after 选项,并在您自己的助手中再次更轻松地完成此操作。
//View/Helpers/MyCustomFormHelper.php
App::uses('FormHelper', 'View/Helper');
MyCustomFormHelper extends FormHelper{
public function input($fieldName, $options) {
$after = parent::label(fieldName);
$defaults = array_merge($options, array(
'label' => false,
'after' => $after,
));
return parent::input($fieldName, $defaults);
}
//or do not overwrite the input function and use a custom one
public function inputLabelAfter($fieldName, $options) {
...
...
}
}
如果代码有错误,我很抱歉我还没有测试过,但我认为您已经了解了情况并给了您更多想法。
编辑:我没有看到这是针对 CakePHP 3.x 的。上面的例子是针对 2.x 的,但我相信它可以。
使用模板是正确的方法 - 我希望这有帮助......
$this->Form->templates([
'nestingLabel' => '{{input}}<label{{attrs}}>{{text}}</label>',
'formGroup' => '{{input}}{{label}}',
]);