2013-05-15 49 views
0

您好,我有以下型號:CakePHP的顯示標籤元素旁邊驗證錯誤的觀點

class Mymodel extends AppModel { 
    public $validate = array(
     'username' => array(
      'required' => array(
       'rule' => array('notEmpty'), 
       'message' => 'A username is required' 
      ), 
      'regexp' => array(
       'rule' => '/^[a-z0-9]{3,10}$/i', 
       'message' => 'Only letters and integers, min 3, max. 10 characters' 
      ) 
     ) 
    ) 
} 

及以下觀點:signup.ctp

<?php 
echo $this->Form->create("Mymodel "); 
echo $this->Form->input('username' ,array('label'=>"Username :")); 
echo $this->Form->input('password' ,array('label'=>"Password :",'type' => 'password')); 
echo $this->Form->end('signup'); 
?> 

我的控制器:

class MymodelController extends AppController 
{ 
    public function signup() 
    {} 
} 

cakePHP的默認驗證行爲是顯示輸入下面的錯誤消息,所以我的問題是:我該如何笑W的標籤字段錯誤,我的意思是這樣的:

用戶名:(我要在這裏展示的錯誤消息)

回答

1

您可以使用$this->Form->error('fieldname')輸出,無論你想的錯誤消息(給輸入參數'error'=>false以防止它在默認位置輸出錯誤消息。

例如: -

$error = $this->Form->isFieldError('username') ? $this->Form->error('username') : ''; 
echo $this->Form->label('username', "Username : $error"); 
echo $this->Form->input('username' ,array('label' => false, 'error' => false)); 
0

表單模板裏面蛋糕核心庫,我不會建議改變任何這些。

如果你想使用

echo $this->Form->input('username' ,array('label'=>"Username :")); 

一如既往,而不是手動錯誤添加標籤保留,你必須用JavaScript來做到這一點。
下面是jQuery的一些代碼,可以達到你想要

$(function() { 
    $('.error-message').each(function(index) { 
     var errorText = $(this).text(); 
     var label = $(this).siblings('label'); 
     label.text(label.text() + errorText); 
     $(this).remove(); 
    }); 
}); 

一定要測試它的情況下,我錯過了什麼東西。將其修改爲您的需要,添加一些樣式等。
如果您想要這樣做無處不在,請將該腳本插入到佈局中,否則將其添加到所需的視圖中。

1

通過「格式」選項

更改元素的順序,如果是好有錯誤消息的標籤和輸入之間放,通過format改變輸入的「元素」的順序選項;

// Create the form. By setting options via the 
// 'inputDefaults' option, the options are 
// automatically applied to all inputs. 
// of course, you can also set this option 
// for each input individually 
echo $this->Form->create("Mymodel", array(
    'inputDefaults' => array(
     // set the order of the 'elements' inside the input-div 
     'format' => array('before', 'label', 'error', 'between', 'input', 'after'), 
     // puts ':' between the label and the input 
     'between' => ':', 
    ) 
)); 
echo $this->Form->input('username'); 
echo $this->Form->input('password'); 
echo $this->Form->end('signup'); 

我還添加了一些額外的修改;

  • 的「之間」選項可用於額外的內容添加到您的輸入,例如(見代碼)把一個:標籤和輸入之間。這樣做,您不必設置自定義標籤
  • 如果輸入用於名爲'password'的字段,CakePHP將自動創建密碼字段。您不必自行設置類型(除非您想將類型覆蓋爲「密碼」輸入以外的其他類型)
相關問題