2

ビジネスとユーザーの2つのモデルがあります。それらはHABTM関係によって関連付けられています。

すべてがベイク処理されたコントローラー、モデル、およびビューで機能しています。

現在、2つのモデルを1つのフォームに組み合わせて、ユーザーが会社名を入力できるようにしています。

フォームは次のとおりです。



    Form->create('User'); ?>
    
    
    Form->input('Business.name', array('label' => __('Business name')));
    echo $this->Form->input('User.email');
    echo $this->Form->input('User.firstname');
    echo $this->Form->input('User.lastname');
    echo $this->Form->input('User.password');
    echo $this->Form->input('User.phone_cell', array('type' => 'text'));
    echo $this->Form->input('User.phone_home', array('type' => 'text'));
    echo $this->Form->input('User.phone_work', array('type' => 'text'));
    ?>
    
    Form->end(__('Submit')); ?>
    

私がそれを機能させることができた唯一の方法は、最初にユーザーを保存し、次にユーザーIDを取得し、新しいIDでユーザー配列を追加することによってビジネスを保存することでした。



    if ($this->User->save($this->request->data)) {
        $this->request->data['User'] = array('User' => array(0 => $this->User->id));
    if ($this->User->Business->save($this->request->data)) {
        // User saved
    } else {
        // User not saved
    }
    } else {
        $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
    }

saveAllメソッドを試しましたが成功しませんでした。これをCakePHPの方法で1回の保存に最適化することは可能ですか?

ありがとう

4

1 に答える 1

0

Userとという名前のいくつかのモデルを使用して、自分で動作させることができましたGroup。これが私のコードの一部であり、私がどのようにそれを行ったかを示しています。

ユーザーコントローラー.php

public function edit($id = null) 
{
    $this->User->id = $id;

    if ($this->request->is('get')) {
        //On page load load the user data
        $this->request->data = $this->User->read();
    } else {
       //Saving
       if ($this->User->save($this->data)) {
           //....snipped...
        } else {
           $this->Session->setFlash('Unable to update the user.');
        }
    }

    //Build $groups array for form
    // Only admins can assign admin rights
    if ($this->isMember('Admin')) {
        $this->set('groups',$this->User->Group->find('list'));
    } else {
        $this->set('groups',$this->User->Group->find('list',array(
            'conditions' => array(
                'Group.name !=' => 'Admin'
            )
        )));
    }
    //...more snipping...
}

edit.ctp (表示)

    echo $this->Form->create('User', array('action' => 'edit'));
    echo $this->Form->input('User.username');
    echo $this->Form->input('Group',array(
            'type' => 'select',
            'multiple' => true,
            'label' => "Group (Select multiple entries with CTRL)",
            'size' => count($groups)
        )
    );
    //More snipping

Business.nameその例を元に、入力されたものが有効であり、HABTM 関係に一致することをどのように検証していますか? この場合、鉱山は選択リストを強制します。私のモデルは非常に単純なので、含めませんでした。

debug($this->data);に対するあなたのアウトプットは何debug($this->request->data)ですか?

于 2013-01-04T19:56:06.547 に答える