I have a Samples Table in my database. Here is my Association in SamplesTable.php
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
In my SamplesControler.php add method i'm getting current User data like this:
$users = $this->Samples->Users->get($this->Auth->user('id'), [
'keyField' => 'id',
'valueField' => 'name'
]);
$this->set(compact('sample', 'users'));
In my add.ctp in Template/Samples/ i'm using this variable to show the user name like this:
echo $this->Form->input('user_id', [
'label' => 'Client',
'type' => 'text',
'disabled' => true,
'value' => $users->name,
'required' => true,
]);
It shows the name correctly, but when i hit submit it doesn't returns the id of the user back to the controller to save it in database. Since i'm very new to this framework i can't figure out if there is anything i'm doing wrong.
I've tried debug response data in my controller add method and there is no user_id in response.
if i change
$users->name to $users
in my template file, it shows all the data about that user in json format in the textfield like this:
{ "id": 4, "name": "firstname lastname", "title": "Engineer", "street": "122", "city": "Lahore", "state": "Punjab", "email_primary": "abc@gmail.com", "created": "2016-03-04T07:45:42+0000", "modified": "2016-03-04T09:56:17+0000"}
If your intention is to show the logged in user's name in the textbox and to save the logged in user's id in the controller, there's no need to fetch the user data.
It's really unnecessary and might cause security issues when you're setting the user id to the template.
When you're trying to access the data of the logged in user, it's the best to keep it this way:
/* For controller: */
$this->Auth->user("field_name");
/* For view: */
$this->request->session()->read("Auth.User.field_name");
Try this:
$name = $this->request->session()->read("Auth.User.first_name")." ". $this->session->read()->("Auth.User.last_name"); // Add this
echo $this->Form->input('user_id', [
'label' => 'Client',
'type' => 'text',
'disabled' => true,
'value' => $name, // Add this
'required' => true,
]);
In the controller:
if ($this->request->is("post")) {
$this->request->data["user_id"] = $this->Auth->user("id"); // Add this
/* Other code */
}
Hope this helps.
Peace! xD