# Problem while tempting to save related data

**URL:** <https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322>\
**Category:** Need Help\
**Created:** [May 13, 2016, 11:38pm UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322 "2016-05-13T23:38:47Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![aagasi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@aagasi](https://discourse.cakephp.org/u/aagasi)\
**Post date:** [May 13, 2016, 11:38pm UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/1 "2016-05-13T23:38:47Z")

</div>

Hello community! i’m new in cakePHP **3.x** and i’m trying to find some help here 'cause i’m stuck with this.

I have 2 tables with their respective models.

Table 1: **users** Model name: **UsersTable**  
Table 2: **contact\_types** Model name: **ContactTypesTable**

I have also a third table: **users\_contact\_types** with it model **UsersConctactTypesTable**  
This table i used to make the relation between users and their contact types. The fields of that table are: **user\_id** , **contact\_type\_id** and **value**.

**For example:**  
Supose we have a user named **John** with ID = 1 and supose we have 3 different contact types ( **telephone** , **email** and **skype** …with ID 1,2 and 3 respectively)

**Aim to achieve:**  
Store in the relation table ( **users\_contact\_types** ) something like this:

**user\_id**  **contact\_type\_id**  **value**  
1 2 [agasiadolfo@gmail.com](mailto:agasiadolfo@gmail.com)  
1 3 agasi.adolfo

…

and so on.

This relation (according to the documentation [Associations - Linking Tables Together - 3.10](http://book.cakephp.org/3.0/en/orm/associations.html) ) is a **belongs-to-many** relation.

I followed all the steps to create the models, tables, and tempted to save the data in the controller but still having some issues to make this work.

I also read in the documentation([Saving Data - 3.10](http://book.cakephp.org/3.0/en/orm/saving-data.html)) that to save some extra fields we have to use **\_joinData** but i don’t understand how to make it work.

Here i copy my files so you can have a look and tell me what you think.

> INITIALIZE METHOD OF **USERSTABLE** MODEL:

> public function initialize(array $config) {

> ```
> parent::initialize($config);
> 
> ```

> ```
> $this->table('users');
> $this->displayField('id');
> $this->primaryKey('id');
> 
> ```

> ```
> $this->addBehavior('Timestamp');
> $this->addBehavior('Acl.Acl', ['type' => 'requester']);
> 
> ```

> ```
> $this->belongsToMany('ContactTypes', [
> 'through' => 'UsersContactTypes',
> ]);
> 
> ```
> 
> }

INITIALIZE METHOD OF **CONTACTTYPES** MODEL

> public function initialize(array $config) {  
> parent::initialize($config);

> ```
> $this->table('contact_types');
> $this->displayField('name');
> $this->primaryKey('id');
> 
> ```

> ```
> $this->belongsToMany('Users', [
> 'through' => 'UsersContactTypes',
> ]);
> }
> 
> ```

INITIALIZE METHOD OF **USERSCONTACTTYPES** MODEL

> public function initialize(array $config)  
> {  
> parent::initialize($config);

> ```
> $this->table('users_contact_types');
> $this->displayField('user_id');
> $this->primaryKey(['user_id', 'contact_type_id']);
> 
> ```

> ```
> $this->belongsTo('Users', [
> 'foreignKey' => 'user_id',
> 'joinType' => 'INNER',
> 'className' => 'UsersCrudAuth.Users'
> ]);
> $this->belongsTo('ContactTypes', [
> 'foreignKey' => 'contact_type_id',
> 'joinType' => 'INNER',
> 'className' => 'UsersCrudAuth.ContactTypes'
> ]);
> }
> 
> ```

THIS IS MY **Users/add.ctp**

> - \<?= \_\_('Actions') ?\>
> - \<?= $this-\>Html-\>link(\_\_('List Users'), ['action' =\> 'index']) ?\>
> - \<?= $this-\>Html-\>link(\_\_('List Aro'), ['controller' =\> 'Aros', 'action' =\> 'index']) ?\>
> - \<?= $this-\>Html-\>link(\_\_('New Aro'), ['controller' =\> 'Aros', 'action' =\> 'add']) ?\>
> - \<?= $this-\>Html-\>link(\_\_('List Contact Types'), ['controller' =\> 'ContactTypes', 'action' =\> 'index']) ?\>
> - \<?= $this-\>Html-\>link(\_\_('New Contact Type'), ['controller' =\> 'ContactTypes', 'action' =\> 'add']) ?\>
> 
> \<?= $this-\>Form-\>create($user) ?\> \<?= \_\_('Add User') ?\> \<?php echo $this-\>Form-\>input('username'); echo $this-\>Form-\>input('name'); echo $this-\>Form-\>input('surname'); echo $this-\>Form-\>input('gender'); echo $this-\>Form-\>input('password'); echo $this-\>Form-\>input('group\_id', ['options' =\> $groupsList]); echo $this-\>Form-\>input('status');

> ```
> /** For now i render the fields like this, but then i'm going to use a table with a 'add register' button that creates a new node to the table incrementing the id */
> 
> ```

echo $this-\>Form-\>input(‘contact\_types.0.\_id’, [‘options’ =\> $contactTypes]);  
echo $this-\>Form-\>input(“contact\_types.0.\_joinData.value”);  
echo $this-\>Form-\>input(‘contact\_types.1.\_id’, [‘options’ =\> $contactTypes]);  
echo $this-\>Form-\>input(“contact\_types.1.\_joinData.value”);\> ?\>

> ```
> </fieldset>
> <?= $this->Form->button(__('Submit')) ?>
> <?= $this->Form->end() ?>
> 
> ```

And my **UsersController.php** (only the **add** method for now)

> public function add() {  
> $user = $this-\>Users-\>newEntity();  
> if ($this-\>request-\>is(‘post’)) {  
> $user = $this-\>Users-\>patchEntity($user, $this-\>request-\>data);

> ```
> /** This is the posted data from the form */
> debug($this->request->data);
> 
> ```

> ```
> /** Here i tempt to save the user model and the associated model whith it _joinData field */
> debug($this->Users->save($user,
> ['associated' => ['ContactTypes','ContactTypes._joinData']]
> ));
> die();
> 
> ```

> ```
> if ($this->Users->save($user)) {
> $this->Flash->success(__('The user has been saved.'));
> return $this->redirect(['action' => 'index']);
> } else {
> $this->Flash->error(__('The user could not be saved. Please, try again.'));
> }
> }
> 
> ```

> ```
> $groupsTable = TableRegistry::get('Groups');
> $groupsList = $groupsTable->find('list', ['limit' => 200]);
> 
> ```

> ```
> $contactTypes = TableRegistry::get('ContactTypes')->find('list', ['limit' => 200]);
> $this->set(compact('user', 'contactTypes','groupsList'));
> $this->set('_serialize', ['user']);
> }
> 
> ```

Also i add here the **debug** of the request-\>data sended from the form.

```
> /plugins/UsersCrudAuth/src/Controller/UsersController.php (line 105)
> [
> 'username' => 'john',
> 'name' => '',
> 'surname' => '',
> 'gender' => 'm',
> 'password' => 'john',
> 'group_id' => '2',
> 'status' => '',
> 'contact_types' => [
> (int) 0 => [
> '_id' => '5',
> '_joinData' => [
> 'value' => 'john@doe.com'
> ]
> ],
> (int) 1 => [
> '_id' => '4',
> '_joinData' => [
> 'value' => 'john.doe'
> ]
> ]
> ]
> ]
> /plugins/UsersCrudAuth/src/Controller/UsersController.php (line 110)
> false

```

Well, i hope you can help me with this because i can’t figure out whats going on here.

By the way, thanks for cooperating.

---

<div class="post-metadata">

**Author:** ![alysson\_azevedo](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/alysson_azevedo/32/194_2.png) [@alysson\_azevedo](https://discourse.cakephp.org/u/alysson_azevedo)\
**Post date:** [May 14, 2016, 12:57am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/2 "2016-05-14T00:57:30Z")

</div>

It’s just a hunch, but i think the problem is that you didn’t inform the contact\_type\_id.  
insteand `_id` try  
`$this->Form->input('contact_types.1.contact_type_id', ['options' => $contactTypes]);`

---

<div class="post-metadata">

**Author:** ![aagasi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@aagasi](https://discourse.cakephp.org/u/aagasi)\
**Post date:** [May 14, 2016, 1:21am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/3 "2016-05-14T01:21:23Z")

</div>

> [@alysson\_azevedo](#):
>
> $this-\>Form-\>input(‘contact\_types.1.contact\_type\_id’, [‘options’ =\> $contactTypes]);

```
/plugins/UsersCrudAuth/src/Controller/UsersController.php (line 105)
[
	'username' => 'john',
	'name' => '',
	'surname' => '',
	'gender' => 'm',
	'password' => 'john',
	'group_id' => '2',
	'status' => '',
	'contact_types' => [
		(int) 0 => [
			'contact_type_id' => '5',
			'_joinData' => [
				'value' => 'john@doe.com'
			]
		],
		(int) 1 => [
			'contact_type_id' => '4',
			'_joinData' => [
				'value' => 'john.doe'
			]
		]
	]
]
/plugins/UsersCrudAuth/src/Controller/UsersController.php (line 110)
false

```

Thanks Alysson, i’have tried your approach but still not saving. Here is the new request-\>data with that changes.

---

<div class="post-metadata">

**Author:** ![alysson\_azevedo](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/alysson_azevedo/32/194_2.png) [@alysson\_azevedo](https://discourse.cakephp.org/u/alysson_azevedo)\
**Post date:** [May 14, 2016, 1:38am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/4 "2016-05-14T01:38:29Z")

</div>

maybe `contact_types.1._joinData.contact_type_id`

---

<div class="post-metadata">

**Author:** ![aagasi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@aagasi](https://discourse.cakephp.org/u/aagasi)\
**Post date:** [May 14, 2016, 1:40am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/5 "2016-05-14T01:40:57Z")

</div>

I also think like you. I feel that the problem is that the **object** being send is **malformed**. But i don’t know how to solve that problem. Do you know where can i refer to look for some examples?  
The cakePHP documentation doesn’t have clear examples for that.

---

<div class="post-metadata">

**Author:** ![aagasi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@aagasi](https://discourse.cakephp.org/u/aagasi)\
**Post date:** [May 14, 2016, 1:48am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/6 "2016-05-14T01:48:31Z")

</div>

```
/plugins/UsersCrudAuth/src/Controller/UsersController.php (line 105)
[
	'username' => 'john',
	'name' => '',
	'surname' => '',
	'gender' => 'm',
	'password' => 'john',
	'group_id' => '2',
	'status' => '',
	'contact_types' => [
		(int) 0 => [
			'_joinData' => [
				'contact_type_id' => '5',
				'value' => 'john@doe.com'
			]
		],
		(int) 1 => [
			'_joinData' => [
				'contact_type_id' => '4',
				'value' => 'john.doe'
			]
		]
	]
]
/plugins/UsersCrudAuth/src/Controller/UsersController.php (line 110)
false

```

I tried that one, but no success.

---

<div class="post-metadata">

**Author:** ![raul338](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/raul338/32/69_2.png) [@raul338](https://discourse.cakephp.org/u/raul338)\
**Post date:** [May 14, 2016, 1:50am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/7 "2016-05-14T01:50:40Z")

</div>

I had some time ago a problem like this. First i think that you may need to use the [the ‘through’ Option](http://book.cakephp.org/3.0/en/orm/associations.html#using-the-through-option) if you use that you don’t need the \_joinData (i think)

Also to debug, don’t debug the request data, add the associated key in patchEntity and debug the resulting entity. If it all done right the contactTypes should be an array of **entities** instead of an array of arrays.

---

<div class="post-metadata">

**Author:** ![alysson\_azevedo](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/alysson_azevedo/32/194_2.png) [@alysson\_azevedo](https://discourse.cakephp.org/u/alysson_azevedo)\
**Post date:** [May 14, 2016, 1:56am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/8 "2016-05-14T01:56:42Z")

</div>

> [@aagasi](#):
>
> Do you know where can i refer to look for some examples?

Here: [Saving Data - 3.10](http://book.cakephp.org/3.0/en/orm/saving-data.html#converting-belongstomany-data)

I’m not sure how to implement this using the form helper, but this problably works

```php
$data = [
    'contact_types' => [
        '_ids' => [5, 4]
    ]
];
$user = $this->Users->patchEntity($user, $data);

```

maybe `$this->Form->input('contact_types._ids[]', ['options' => $contactTypes]);`

---

<div class="post-metadata">

**Author:** ![aagasi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@aagasi](https://discourse.cakephp.org/u/aagasi)\
**Post date:** [May 14, 2016, 2:12am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/9 "2016-05-14T02:12:36Z")

</div>

Hello Raul, i’m using the through option in the model definition. But that doesn’t meant that you don’t need the **\_joinData** option. The \_joinData is used to add some extra fields to the relation model so ,for example, i can save de ‘value’ (in my case)

Refering to the **debug** , can you write down the code to add the key to the patchEntity? I tried to add it like this:  
$user = $this-\>Users-\>patchEntity($user, $this-\>request-\>data,  
[‘associated’ =\> [‘ContactTypes’,‘ContactTypes.\_joinData’]]  
);

But i don’t know if you were talking about doing that way.

---

<div class="post-metadata">

**Author:** ![aagasi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@aagasi](https://discourse.cakephp.org/u/aagasi)\
**Post date:** [May 14, 2016, 2:20am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/10 "2016-05-14T02:20:36Z")

</div>

Alysson, this approach is almost correct. Now the data of the relation is being saved. But the extra field i added (value) is null in the database. Have you any idea why?

This is the new debug were you can see that now the **save** object is being set.

```
/plugins/UsersCrudAuth/src/Controller/UsersController.php (line 105)
[
	'username' => 'jane',
	'name' => '',
	'surname' => '',
	'gender' => 'f',
	'password' => 'jane',
	'group_id' => '2',
	'status' => '',
	'contact_types' => [
		'_ids' => [
			(int) 0 => '5',
			(int) 1 => '4'
		],
		(int) 0 => [
			'_joinData' => [
				'value' => 'jane@doe.com'
			]
		],
		(int) 1 => [
			'_joinData' => [
				'value' => 'jane.doe'
			]
		]
	]
]
/plugins/UsersCrudAuth/src/Controller/UsersController.php (line 110)
object(UsersCrudAuth\Model\Entity\User) {

	'username' => 'jane',
	'name' => '',
	'surname' => '',
	'gender' => 'f',
	'password' => '$2y$10$EEPZZNIBvhJWYJjsQnQZWuISi2j9BXABQ0PsgKZGDstOzNYq8NILC',
	'group_id' => (int) 2,
	'status' => '',
	'contact_types' => [
		(int) 0 => object(Cake\ORM\Entity) {

			'id' => (int) 5,
			'name' => 'E-mail',
			'_joinData' => object(Cake\ORM\Entity) {

				'user_id' => (int) 57,
				'contact_type_id' => (int) 5,
				'[new]' => false,
				'[accessible]' => [
					'*' => true
				],
				'[dirty]' => [],
				'[original]' => [],
				'[virtual]' => [],
				'[errors]' => [],
				'[invalid]' => [],
				'[repository]' => 'UsersContactTypes'
			
			},
			'[new]' => false,
			'[accessible]' => [
				'*' => true
			],
			'[dirty]' => [],
			'[original]' => [],
			'[virtual]' => [],
			'[errors]' => [],
			'[invalid]' => [],
			'[repository]' => 'ContactTypes'
		
		},
		(int) 1 => object(Cake\ORM\Entity) {

			'id' => (int) 4,
			'name' => 'Facebook',
			'_joinData' => object(Cake\ORM\Entity) {

				'user_id' => (int) 57,
				'contact_type_id' => (int) 4,
				'[new]' => false,
				'[accessible]' => [
					'*' => true
				],
				'[dirty]' => [],
				'[original]' => [],
				'[virtual]' => [],
				'[errors]' => [],
				'[invalid]' => [],
				'[repository]' => 'UsersContactTypes'
			
			},
			'[new]' => false,
			'[accessible]' => [
				'*' => true
			],
			'[dirty]' => [],
			'[original]' => [],
			'[virtual]' => [],
			'[errors]' => [],
			'[invalid]' => [],
			'[repository]' => 'ContactTypes'
		
		}
	],
	'created' => object(Cake\I18n\Time) {

		'time' => '2016-05-14T02:17:18+00:00',
		'timezone' => 'UTC',
		'fixedNowTime' => false
	
	},
	'modified' => object(Cake\I18n\Time) {

		'time' => '2016-05-14T02:17:18+00:00',
		'timezone' => 'UTC',
		'fixedNowTime' => false
	
	},
	'id' => (int) 57,
	'[new]' => false,
	'[accessible]' => [
		'*' => true,
		'contact_types' => true,
		'value' => true
	],
	'[dirty]' => [],
	'[original]' => [
		'contact_types' => [
			(int) 0 => object(Cake\ORM\Entity) {

				'id' => (int) 5,
				'name' => 'E-mail',
				'[new]' => false,
				'[accessible]' => [
					'*' => true
				],
				'[dirty]' => [],
				'[original]' => [],
				'[virtual]' => [],
				'[errors]' => [],
				'[invalid]' => [],
				'[repository]' => 'ContactTypes'
			
			},
			(int) 1 => object(Cake\ORM\Entity) {

				'id' => (int) 4,
				'name' => 'Facebook',
				'[new]' => false,
				'[accessible]' => [
					'*' => true
				],
				'[dirty]' => [],
				'[original]' => [],
				'[virtual]' => [],
				'[errors]' => [],
				'[invalid]' => [],
				'[repository]' => 'ContactTypes'
			
			}
		]
	],
	'[virtual]' => [],
	'[errors]' => [],
	'[invalid]' => [],
	'[repository]' => 'UsersCrudAuth.Users'

}
```

---

<div class="post-metadata">

**Author:** ![alysson\_azevedo](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/alysson_azevedo/32/194_2.png) [@alysson\_azevedo](https://discourse.cakephp.org/u/alysson_azevedo)\
**Post date:** [May 14, 2016, 2:24am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/11 "2016-05-14T02:24:38Z")

</div>

Maybe

```auto
$data = [
    'contact_types' => [
        ['id' => 4, 'value' => 'aaa'],
        ['id' => 5, 'value' => 'bbb']
    ]
];

```

---

<div class="post-metadata">

**Author:** ![aagasi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@aagasi](https://discourse.cakephp.org/u/aagasi)\
**Post date:** [May 14, 2016, 2:36am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/12 "2016-05-14T02:36:17Z")

</div>

That looks good, but i don’t know how to implement it. Can you please give me a hint? I mean using the Form Helper

---

<div class="post-metadata">

**Author:** ![alysson\_azevedo](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/alysson_azevedo/32/194_2.png) [@alysson\_azevedo](https://discourse.cakephp.org/u/alysson_azevedo)\
**Post date:** [May 14, 2016, 2:54am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/13 "2016-05-14T02:54:40Z")

</div>

> [@aagasi](#):
>
> Can you please give me a hint? I mean using the Form Helper

```auto
$this->Form->input('contact_types.0.id', ['options' => $contactTypes]);
$this->Form->input('contact_types.0.value');
$this->Form->input('contact_types.1.id', ['options' => $contactTypes]);
$this->Form->input('contact_types.1.value');

```

---

<div class="post-metadata">

**Author:** ![aagasi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@aagasi](https://discourse.cakephp.org/u/aagasi)\
**Post date:** [May 14, 2016, 3:15am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/14 "2016-05-14T03:15:58Z")

</div>

i just tried this. But now the thing is that the **options** are not being displayed. Now in the form the drawed html is:

`<input type="hidden" name="contact_types[0][id]" options="SELECT ContactTypes.id AS`ContactTypes\_\_id`, ContactTypes.name AS`ContactTypes\_\_name`FROM contact_types ContactTypes LIMIT 200" id="contact-types-0-id">`

This thing It’s kinda tricky.

---

<div class="post-metadata">

**Author:** ![alysson\_azevedo](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/alysson_azevedo/32/194_2.png) [@alysson\_azevedo](https://discourse.cakephp.org/u/alysson_azevedo)\
**Post date:** [May 14, 2016, 3:19am UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/15 "2016-05-14T03:19:15Z")

</div>

`$contactTypes = TableRegistry::get('ContactTypes')->find('list', ['limit' => 200])->all();`

---

<div class="post-metadata">

**Author:** ![aagasi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@aagasi](https://discourse.cakephp.org/u/aagasi)\
**Post date:** [May 14, 2016, 1:36pm UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/16 "2016-05-14T13:36:08Z")

</div>

Now this is the rendered html. Still **not** being able to ‘see’ the dropdown with the values of the contact types.

`<input type="hidden" name="contact_types[0][id]" options="(object)Cake\Datasource\ResultSetDecorator" id="contact-types-0-id">`

What should i do?

---

<div class="post-metadata">

**Author:** ![raul338](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/raul338/32/69_2.png) [@raul338](https://discourse.cakephp.org/u/raul338)\
**Post date:** [May 14, 2016, 3:31pm UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/17 "2016-05-14T15:31:13Z")

</div>

Add ‘type’ =\> ‘select’ with the options

---

<div class="post-metadata">

**Author:** ![aagasi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@aagasi](https://discourse.cakephp.org/u/aagasi)\
**Post date:** [May 14, 2016, 3:37pm UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/18 "2016-05-14T15:37:10Z")

</div>

Well, now the rendered html is ok i think.

`

Celular E-mail Facebook Skype Teléfono fijo `

And this is the **debug**.

```
/plugins/UsersCrudAuth/src/Controller/UsersController.php (line 105)
[
	'username' => 'jany',
	'name' => '',
	'surname' => '',
	'gender' => 'f',
	'password' => 'jany',
	'group_id' => '1',
	'status' => '',
	'contact_types' => [
		(int) 0 => [
			'id' => '5',
			'value' => 'jany@doe.com'
		],
		(int) 1 => [
			'id' => '4',
			'value' => 'jany.doe'
		]
	]
]
/plugins/UsersCrudAuth/src/Controller/UsersController.php (line 110)
object(UsersCrudAuth\Model\Entity\User) {

	'username' => 'jany',
	'name' => '',
	'surname' => '',
	'gender' => 'f',
	'password' => '$2y$10$Ejs6TDlEATIc2dn8i3WoCe.Jyg0blkfUOtaFB1BqcQhiDrHml4w0e',
	'group_id' => (int) 1,
	'status' => '',
	'contact_types' => [
		(int) 0 => object(Cake\ORM\Entity) {

			'id' => (int) 5,
			'name' => 'E-mail',
			'value' => 'jany@doe.com',
			'_joinData' => object(Cake\ORM\Entity) {

				'user_id' => (int) 59,
				'contact_type_id' => (int) 5,
				'[new]' => false,
				'[accessible]' => [
					'*' => true
				],
				'[dirty]' => [],
				'[original]' => [],
				'[virtual]' => [],
				'[errors]' => [],
				'[invalid]' => [],
				'[repository]' => 'UsersContactTypes'
			
			},
			'[new]' => false,
			'[accessible]' => [
				'*' => true
			],
			'[dirty]' => [],
			'[original]' => [],
			'[virtual]' => [],
			'[errors]' => [],
			'[invalid]' => [],
			'[repository]' => 'ContactTypes'
		
		},
		(int) 1 => object(Cake\ORM\Entity) {

			'id' => (int) 4,
			'name' => 'Facebook',
			'value' => 'jany.doe',
			'_joinData' => object(Cake\ORM\Entity) {

				'user_id' => (int) 59,
				'contact_type_id' => (int) 4,
				'[new]' => false,
				'[accessible]' => [
					'*' => true
				],
				'[dirty]' => [],
				'[original]' => [],
				'[virtual]' => [],
				'[errors]' => [],
				'[invalid]' => [],
				'[repository]' => 'UsersContactTypes'
			
			},
			'[new]' => false,
			'[accessible]' => [
				'*' => true
			],
			'[dirty]' => [],
			'[original]' => [],
			'[virtual]' => [],
			'[errors]' => [],
			'[invalid]' => [],
			'[repository]' => 'ContactTypes'
		
		}
	],
	'created' => object(Cake\I18n\Time) {

		'time' => '2016-05-14T15:33:22+00:00',
		'timezone' => 'UTC',
		'fixedNowTime' => false
	
	},
	'modified' => object(Cake\I18n\Time) {

		'time' => '2016-05-14T15:33:22+00:00',
		'timezone' => 'UTC',
		'fixedNowTime' => false
	
	},
	'id' => (int) 59,
	'[new]' => false,
	'[accessible]' => [
		'*' => true,
		'contact_types' => true,
		'value' => true
	],
	'[dirty]' => [],
	'[original]' => [
		'contact_types' => [
			(int) 0 => object(Cake\ORM\Entity) {

				'id' => (int) 5,
				'name' => 'E-mail',
				'value' => 'jany@doe.com',
				'[new]' => false,
				'[accessible]' => [
					'*' => true
				],
				'[dirty]' => [
					'value' => true
				],
				'[original]' => [],
				'[virtual]' => [],
				'[errors]' => [],
				'[invalid]' => [],
				'[repository]' => 'ContactTypes'
			
			},
			(int) 1 => object(Cake\ORM\Entity) {

				'id' => (int) 4,
				'name' => 'Facebook',
				'value' => 'jany.doe',
				'[new]' => false,
				'[accessible]' => [
					'*' => true
				],
				'[dirty]' => [
					'value' => true
				],
				'[original]' => [],
				'[virtual]' => [],
				'[errors]' => [],
				'[invalid]' => [],
				'[repository]' => 'ContactTypes'
			
			}
		]
	],
	'[virtual]' => [],
	'[errors]' => [],
	'[invalid]' => [],
	'[repository]' => 'UsersCrudAuth.Users'

}

```

But still not saving the **value** field. Do you have any clue?

---

<div class="post-metadata">

**Author:** ![pedro](https://avatars.discourse-cdn.com/v4/letter/p/919ad9/32.png) [@pedro](https://discourse.cakephp.org/u/pedro)\
**Post date:** [May 14, 2016, 5:03pm UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/19 "2016-05-14T17:03:22Z")

</div>

Hi Adolfo,

I think what you are mainly facing here is a concept issue. It doesn’t make much sense to a User belongsToMany ContactTypes. It would make more sense for a User hasMany Contacts which in turn belongsTo ContactTypes.

This way you will make the form much easier. For example:

```
$this->Form->input('contacts.0.contact_type_id');
$this->Form->input('contacts.0.value');

```

You would then have:

```
User hasMany Contacts
Contacts belongsTo ContactTypes

```

I’ll not go through more Table definitions as I think you can figure them out by yourself. But feel free to ask anything about this approach.

Best,  
Pedro.

---

<div class="post-metadata">

**Author:** ![aagasi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@aagasi](https://discourse.cakephp.org/u/aagasi)\
**Post date:** [May 14, 2016, 5:37pm UTC](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322/20 "2016-05-14T17:37:36Z")

</div>

Thanks for the reply.

So i updated my models and now i have:

**UsersTable.php**

```
public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('users');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');
        $this->addBehavior('Acl.Acl', ['type' => 'requester']);

        $this->hasMany('ContactTypes');
    }

```

**ContactTypesTable.php**

```
public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('contact_types');
        $this->displayField('name');
        $this->primaryKey('id');

        $this->belongsTo('Users');
    }

```

And the **ContactTypesTable.php** (that still being the same)

```
public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('users_contact_types');
        $this->displayField('user_id');
        $this->primaryKey(['user_id', 'contact_type_id']);

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER',
            'className' => 'UsersCrudAuth.Users'
        ]);
        $this->belongsTo('ContactTypes', [
            'foreignKey' => 'contact_type_id',
            'joinType' => 'INNER',
            'className' => 'UsersCrudAuth.ContactTypes'
        ]);
    }

```

In the **add.ctp**

```
            echo $this->Form->input('contacts.0.contact_type_id');
            echo $this->Form->input('contacts.0.value');

            echo $this->Form->input('contacts.1.contact_type_id');
            echo $this->Form->input('contacts.1.value');

```

And the **UsersController.php**

```
public function add() {
        $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->data);

            /** This is the posted data from the form */
            debug($this->request->data);

            /** Here i tempt to save the user model and the associated model whith it _joinData field */
            debug($this->Users->save($user));
            die();

            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The user could not be saved. Please, try again.'));
            }
        }

        $groupsTable = TableRegistry::get('Groups');
        $groupsList = $groupsTable->find('list', ['limit' => 200]);

        $contactTypes = TableRegistry::get('ContactTypes')->find('list', ['limit' => 200])->all();
        $this->set(compact('user', 'contactTypes','groupsList'));
        $this->set('_serialize', ['user']);
    }

```

But this, is **still failing**. Maybe i misunderstood what you tried to explain me.

The **debug** of the request-\>data sended to the controller is now:

```
/plugins/UsersCrudAuth/src/Controller/UsersController.php (line 124)
[
	'username' => 'John',
	'name' => '',
	'surname' => '',
	'gender' => 'm',
	'password' => 'john',
	'group_id' => '2',
	'status' => '',
	'contacts' => [
		(int) 0 => [
			'contact_type_id' => '5',
			'value' => 'john@doe.com'
		],
		(int) 1 => [
			'contact_type_id' => '4',
			'value' => 'john.doe'
		]
	]
]
/plugins/UsersCrudAuth/src/Controller/UsersController.php (line 129)
false

```

Do i need to add something else to the **models definition**?

Thanks for any reply.

[Next page](https://discourse.cakephp.org/t/problem-while-tempting-to-save-related-data/322.md?page=2)
