2012-02-28 70 views
0

檢索數據我有表 「car_types」,控制器users_controller,模型Car_type和動作URL驗證未在蛋糕的PHP工作,如果從其他模型

localhost/carsdirectory/users/dashboard 

dashboard.ctp(視圖)

<?php echo $this->Form->create('Users', array('type' => 'file', 'action' => 'dashboard')); ?> 
<select> 
<?php foreach($car_type as $key => $val) { ?> 
<option value="" selected="selected">select</option> 
<option value="<?php echo $val['Car_type']['id']; ?>"> 
<?php echo $val['Car_type']['car_type']; ?> 
</option> 
<?php } ?> 
</select> 
<?php echo $this->Form->end(array('label' => 'Submit', 'name' => 'Submit', 'div' => array('class' => 'ls-submit')));?> 

Car_type.php(模型)

class Car_type extends AppModel 
    { 
    var $name = 'Car_type'; 

    var $validate = array(

    'car_type' => array(

     'rule' =>'notEmpty', 
     'message' => 'Plz select type.' 
     ) 
    ); 
    } 

users_controller.php中(控制器)

public function dashboard(){ 

     $this->loadModel('Car_type'); // your Model name => Car_type 

     $this->set('car_type', $this->Car_type->find('all')); 

    } 

但是當我點擊提交按鈕,我想告訴MSG(PLZ選擇型),現在它不工作,我知道我必須在我的代碼問題而無法即時通訊無法理清這麼plz幫助我

在此先感謝,vikas tyagi

回答

1

這驗證規則是,當你添加一些汽車類型,而不是用戶驗證。

對於這一點,你需要把驗證的用戶模型從car_type_id領域:

class User extends AppModel { 
    var $name = 'User'; 

    var $validate = array(
     'car_type_id' => array(
      'rule' => 'notEmpty', 
      'message' => 'Please, select car type.' 
     ) 
    ); 
} 

而且你的形式:

$this->Form->input('car_type_id', array('options' => $car_type, 'empty' => '- select -')); 

控制器可以簡單:

$this->set('car_type', $this->User->Car_type->find('all')); 

然而,不知道這是否是你的整個代碼,以確認這兩個模型之間的關係是c orrect。

+0

但我創建了其他模型類Car_type – 2012-02-28 11:46:00

+0

當您需要添加汽車類型的用戶時,您的驗證必須是模型用戶,而不是Car_type。你能在[pastebin](http://pastebin.com/)上爲我們展示更多代碼嗎?像你的整個用戶和Car_type模型和數據庫中這些表的結構? – 2012-02-28 11:52:45

+0

這是動作url本地主機/ carsdirectory /用戶/儀表板,並在此頁面我有選擇字段,在此選擇字段im從car_types表中獲取數據(我有兩個字段表1. id 2.Car_type),這就是爲什麼我已經使其他型號Car_type – 2012-02-28 12:10:07

0

考慮到它是數據,您應該在模型中存儲有效選擇列表。

var $carType= array('a' => 'Honda', 'b' => 'Toyota', 'c' => 'Ford'); 

你可以得到該變量在控制器只是這樣的:

$this->set('fieldAbcs', $this->MyModel->carType); 

不幸的是,你不能簡單地使用在規則中聲明的INLIST規則變量,因爲規則被聲明爲實例變量和那些只能靜態初始化(不允許變量)。周圍的最好的辦法是設置變量的構造:

var $validate = array(
    'carType' => array(
     'allowedChoice' => array(
      'rule' => array('inList', array()), 
      'message' => 'Pls select type.' 
     ) 
    ) 
); 

function __construct($id = false, $table = null, $ds = null) { 
    parent::__construct($id, $table, $ds); 

    $this->validate['carType']['allowedChoice']['rule'][1] = 
    array_keys($this->fieldAbcChoices); 
} 
+0

感謝您的回覆,我嘗試過 – 2012-02-28 11:37:34