Sunday, May 18, 2014

3.0 - Saving data using Form with HasOne relationship

Dear All,

I am new & trying from 3.0.

I have made "User" hasOne "Profile" Association with DB

users [ id, username, password, created, modified ]
&
profiles [id, name, address, email, mobile, user_id, created, modified]

In UsersTable.php

"class UsersTable extends Table{    
    public function initialize(array $config) {
        $this->hasOne('Profiles',[
            'className' => 'Profiles',
            'foreignKey' => 'user_id',
            'dependent' => true
        ]);
        $this->displayField('username');
    }
} "

In ProfilesTable.php

"class ProfilesTable extends Table{    
    public function initialize(array $config) {
        $this->belongsTo('Users',[
            'className' => 'Users',
            'foreignKey' => 'user_id',
            'joinType' => 'INNER'
        ]);        
    }
} "

In Entity, User.php & Profile.php

class User extends Entity{
    protected $_accessible = ['*' => true];
}

class Profile extends Entity{
    protected $_accessible = ['*' => true];
}

In ProfilesController.php's add function,

public function add(){
        
        $profiles = TableRegistry::get('Profiles');
        
        $profile = $profiles->newEntity($this->request->data);
        
        $pUser = $this->Profiles->Users->find('list',['fields' => ['id', 'username']]);
        
        $this->set(compact('pUser'));
        
        if($this->request->is('post')){
            if($profiles->save($profile)){
                $this->Session->setFlash(__('Profile has been saved.'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Session->setFlash(__('Unable to save profile, please try again.'));
        }
        $this->set(compact('profile'));
    }


In Profiles Template, add.ctp

<?php

echo $this->Form->create($profile);
echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('address');
echo $this->Form->input('mobile');
echo $this->Form->input('username', ['options' => $pUser]);
echo $this->Form->button('Save Profile');
echo $this->Form->end();

?>

The question is when i fill up the form and hit the save button i can not save the "user_id" of Profiles in Database and also can not save the "created" field as current time.

I am sure i am missing something, Could you please help me & guide me on this regard?

Thanks in advance.

Bayezid
Enthusiast Lover of CakePHP

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: