[英]How to override default HTML Helper of Cakephp?
我被設計師給了主題,我被指派將其與產品集成。 由於源代碼方面的產品規模很大,我必須修改幾乎所有的視圖和布局。 此外,該產品的開發將在未來2年進行,這是計划。
我正在嘗試覆蓋Cakephp的HTML Helper類,以便它將更改css的所有默認類。 由於這種策略,開發人員不必為觀點付出更多努力,它將簡化未來的開發。 馬上
echo $this->Form->input('username');
生成
<div class="input text required">
<label for="username">Username</label>
<input id="username" type="text" required="required" maxlength="30" name="data[User][username]">
</div>
我希望通過重寫HTML Helper來實現這一點。
<div class="form-group has-error">
<label for="inputError" class="control-label">Input with error</label>
<input type="text" id="username" class="form-control" name=" data[User][username]" required="required">
</div>
這是文本框的一個示例。 請提前幫助,謝謝。
我想你無法覆蓋它。 但是你可以構建另一個擴展 FormHelper的幫助器。
我這樣做曾經使我的表單創建過程更簡單地使用Bootstrap css內置類。
class BFormHelper extends FormHelper {
public function label($fieldName = null, $text = null, $options = array()){
$myOptions = array('class' => 'control-label');
return parent::label($fieldName, $text, array_merge($options, $myOptions));
}
}
這樣我們封裝了CSS類control-label
,如果需要更改它,我們只需要在一個地方完成它。
然后,在視圖上你只需:
<?= $this->BForm->label('somefield', 'Some bootstrap field') ?>
我做的CakePHP版本是1.3。
看起來你正在使用bootstrap css框架。 我建議你使用這個插件:
為了生成上面的代碼,您可以始終使用核心FormHelper
:
<?php
echo "<div class=\"form-group has-error\">."
. $this->Form->label('username', '<your-text-goes-here>', array('class' => 'control-label'))
. $this->Form->input('username', array('class' => 'form-control', 'label' => false, 'div' => false))
. "</div>\n";
?>
FormHelper
核心可以完全定制,以滿足您的需求。 但這種方式意味着你的意志必須付出額外的努力。 閱讀cakebook中有關如何自定義核心FormHelper
的相應部分。
如果要最小化視圖中的代碼,可以創建自定義表單助手,如下面給出的示例。
<?php
class CustomformHelper extends AppHelper {
public $helpers = array('Form');
public function customInput(<your-options-goes-here>) {
/* Write your custom code for the specific type of input
* you want to create. */
}
};
?>
在您的自定義助手中,您可以通過定義$helpers
數組來引入任何其他核心助手,就像您在控制器中所做的那樣。
您在$helpers
數組中定義的所有核心助手都可以使用$this
。 例如,如果要從自定義方法中調用FormHelper::input()
方法,可以使用以下代碼: $this->Form->input(...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.