2012-02-15 3 views
2

私はMySQLでLithiumを使用しています。 ユーザーモデルがhasOneになりました。 連絡先モデルbelongsToユーザー。リチウム:関連するデータをフォームに表示して保存するにはどうすればよいですか?

私は以下のコードの非常に基本的なバージョンをリストアップしました。

私の質問:

  1. 私は、ユーザーを編集してフォームを送信すると、どのように私も、連絡先データのセーブユーザー::編集を作るのですか?
  2. また、ユーザーの編集ビューでcontacts.emailを表示するにはどうすればよいですか?

モデル/ Users.php

<?php 
namespace app\models; 

class Users extends \lithium\data\Model { 

    public $hasOne = array('Contacts'); 

    protected $_schema = array(
     'id' => array('type' => 'integer', 
         'key' => 'primary'), 
     'name' => array('type' => 'varchar') 
    ); 
} 
?> 

モデル/ Contacts.php

<?php 
namespace app\models; 

class Contacts extends \lithium\data\Model { 

    public $belongsTo = array('Users'); 

    protected $_meta = array(
     'key' => 'user_id', 
    ); 

    protected $_schema = array(
     'user_id' => array('type' => 'integer', 
          'key' => 'primary'), 
     'email' => array('type' => 'string') 
    ); 
} 
?> 

コントローラ/ UsersController.php

<?php 
namespace app\controllers; 

use app\models\Users; 

class UsersController extends \lithium\action\Controller { 
    public function edit() { 
     $user = Users::find('first', array(
       'conditions' => array('id' => $this->request->id), 
       'with'  => array('Contacts') 
      ) 
     ); 

     if (!empty($this->request->data)) { 
      if ($user->save($this->request->data)) { 
       //flash success message goes here 
       return $this->redirect(array('Users::view', 'args' => array($user->id))); 
      } else { 
       //flash failure message goes here 
      } 
     } 
     return compact('user'); 
    } 
} 
?> 

ビュー/ユーザー/ edit.html。 PHP

答えて

5

これは知っている人はほとんどいませんが、リチウムを使用するとフォームを複数のオブジェクトにバインドできます。

コントローラでは、ユーザーと連絡先オブジェクトの両方を返します。次に、あなたのフォームで:

:ユーザーがフォームを送信すると

<?= $this->form->field('user.name'); ?> 
<?= $this->form->field('contact.email'); ?> 

、両方のオブジェクトのためのデータとして保存されます。

<?= $this->form->create(compact('user', 'contact')); ?> 

あなたは、このような特定のオブジェクトを形成するフィールドをレンダリング

$this->request->data['user']; 
$this->request->data['contact']; 

この情報を使用して、通常どおりデータベースを更新できます。両方のオブジェクトからのデータが有効である場合にのみ情報を保存したい場合は、次のように検証する呼び出すことができます。

$user = Users::create($this->request->data['user']); 
if($user->validates()) { 
    $userValid = true; 
} 

$contact = Contacts::create($this->request->data['contact']); 
if($contact->validates()) { 
    $contactValid = true; 
} 

if($userValid && $userValid){ 
    // save both objects 
} 

希望まあ...ただ、この質問の日付を見て:)

+0

を助けること誰か助けてくれるかもしれない! –

+0

それだけでした! :) – Oerd

+0

ありがとうマックス。そのような偉大な詳細で返信するあなたの非常に種類: – Housni

関連する問題