# Saving associated data with hasOne association not working

**URL:** <https://discourse.cakephp.org/t/saving-associated-data-with-hasone-association-not-working/3597>\
**Category:** Need Help\
**Created:** [December 2, 2017, 2:47pm UTC](https://discourse.cakephp.org/t/saving-associated-data-with-hasone-association-not-working/3597 "2017-12-02T14:47:00Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![jaynarayan](https://avatars.discourse-cdn.com/v4/letter/j/82dd89/32.png) [@jaynarayan](https://discourse.cakephp.org/u/jaynarayan)\
**Post date:** [December 2, 2017, 2:47pm UTC](https://discourse.cakephp.org/t/saving-associated-data-with-hasone-association-not-working/3597/1 "2017-12-02T14:47:00Z")

</div>

The problem: I want to create a company and its associated user using single form for company create

I have baked the scaffold and using CakePHP convention.

**my association setup:-**  
_CompaniesTable class_

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

            $this->setTable('companies');
            $this->setDisplayField('name');
            $this->setPrimaryKey('id');

            $this->hasMany('Users', [
                'foreignKey' => 'company_id'
            ]);
        }

```

**UsersTable**

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

```
    $this->setTable('users');
    $this->setDisplayField('id');
    $this->setPrimaryKey('id');

    $this->addBehavior('Timestamp');

    $this->belongsTo('Companies', [
        'foreignKey' => 'company_id',
        'joinType' => 'INNER'
    ]);
    $this->belongsToMany('Roles', [
        'foreignKey' => 'user_id',
        'targetForeignKey' => 'role_id',
        'joinTable' => 'roles_users'
    ]);
}

```

I have used following code in my add.ctp to generate fields for user

 \<?=$this-\>Form-\>control('users.0.user\_name');?\> 

 \<?=$this-\>Form-\>control('users.0.password');?\> \</div

code of add method in the controller

public function add()  
{  
$this-\>viewBuilder()-\>setLayout(false);  
$company = $this-\>Companies-\>newEntity();  
if ($this-\>request-\>is(‘post’)) {  
$company = $this-\>Companies-\>patchEntity($company, $this-\>request-\>getData());

```
        if ($this->Companies->save($company)) {
            $this->Flash->success(__('The company has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The company could not be saved. Please, try again.'));
    }
    $this->set(compact('company'));
    $this->set('_serialize', ['company']);
}

```

my request data

[  
‘name’ =\> ‘x’,  
‘print\_name’ =\> ‘x’,  
‘address\_line1’ =\> ‘x’,  
‘address\_line2’ =\> ‘x’,  
‘city’ =\> ‘x’,  
‘state’ =\> ‘x’,  
‘country’ =\> ‘x’,  
‘pincode’ =\> ‘x’,  
‘current\_financial\_year’ =\> ‘x’,  
‘organization\_start\_date’ =\> [  
‘year’ =\> ‘2021’,  
‘month’ =\> ‘03’,  
‘day’ =\> ‘04’  
],  
‘currency\_name’ =\> ‘x’,  
‘currency\_symbol’ =\> ‘x’,  
‘currency\_subname’ =\> ‘x’,  
‘symbol\_of\_partition’ =\> ‘x’,  
‘symbol\_to\_print’ =\> ‘xx’,  
‘multi\_currency\_management’ =\> ‘0’,  
‘has\_pan’ =\> ‘0’,  
‘has\_gst’ =\> ‘0’,  
‘has\_tds’ =\> ‘0’,  
‘has\_tcs’ =\> ‘0’,  
‘pan\_number’ =\> ‘’,  
‘gst\_number’ =\> ‘’,  
‘tds\_number’ =\> ‘’,  
‘tcs\_number’ =\> ‘’,  
‘pan\_date’ =\> [  
‘year’ =\> ‘2017’,  
‘month’ =\> ‘12’,  
‘day’ =\> ‘02’  
],  
‘gst\_date’ =\> [  
‘year’ =\> ‘2017’,  
‘month’ =\> ‘12’,  
‘day’ =\> ‘02’  
],  
‘tds\_date’ =\> [  
‘year’ =\> ‘2017’,  
‘month’ =\> ‘12’,  
‘day’ =\> ‘02’  
],  
‘tcs\_date’ =\> [  
‘year’ =\> ‘2017’,  
‘month’ =\> ‘12’,  
‘day’ =\> ‘02’  
],  
‘users’ =\> [  
(int) 0 =\> [  
‘user\_name’ =\> ‘james’,  
‘password’ =\> ‘password’  
]  
]  
]

Thanks in advance for your help

---

<div class="post-metadata">

**Author:** ![jarekgol](https://avatars.discourse-cdn.com/v4/letter/j/58956e/32.png) [@jarekgol](https://discourse.cakephp.org/u/jarekgol)\
**Post date:** [December 3, 2017, 10:13am UTC](https://discourse.cakephp.org/t/saving-associated-data-with-hasone-association-not-working/3597/2 "2017-12-03T10:13:58Z")

</div>

And what is the effect? Some error? or only new company without user? nothing?  
Code of your form /template may also help.  
Also debug in controller your entity after patch (and if you don’t guess by your self, paste it here)  
debug($company);  
Check for errors,dirty and isNew flags.  
You can try to add [‘contain’=\>‘Users’] to newEntinty and/or patchEntity and/or save. I remember that it can help if your associations aren’t saved.

> [@jaynarayan](#):
>
> $company = $this-\>Companies-\>newEntity();

---

<div class="post-metadata">

**Author:** ![jaynarayan](https://avatars.discourse-cdn.com/v4/letter/j/82dd89/32.png) [@jaynarayan](https://discourse.cakephp.org/u/jaynarayan)\
**Post date:** [December 3, 2017, 10:21am UTC](https://discourse.cakephp.org/t/saving-associated-data-with-hasone-association-not-working/3597/3 "2017-12-03T10:21:31Z")

</div>

> [@jarekgol](#):
>
> And what is the effect? Some error? or only new company without user? nothing?

Only new company created without user

---

<div class="post-metadata">

**Author:** ![jaynarayan](https://avatars.discourse-cdn.com/v4/letter/j/82dd89/32.png) [@jaynarayan](https://discourse.cakephp.org/u/jaynarayan)\
**Post date:** [December 3, 2017, 10:25am UTC](https://discourse.cakephp.org/t/saving-associated-data-with-hasone-association-not-working/3597/4 "2017-12-03T10:25:41Z")

</div>

I have changed my add method and it is working now. The only problem is that user entity accepts an empty string( i.e. user is not validated).

my code is

```
 public function add()
    {
        $this->viewBuilder()->setLayout(false);
       $company = $this->Companies->newEntity();

        if ($this->request->is('post')) {
            $company = $this->Companies->patchEntity( $company,$this->request->getData());
        
            $user = $this->Companies->users->newEntity();

            $userinfo = $this->request->getData('user');
           
            $user->email = $userinfo['email'];
            $user->user_name = $userinfo['user_name'];
            $user->password = $userinfo['password'];
            $company->users = [$user];
           
            if ($this->Companies->save($company)) {
              
                $this->Flash->success(__('The company has been saved.'));

                return $this->redirect(['controller'=>'Users','action' => 'login']);
            }
            $this->Flash->error(__('The company could not be saved. Please, try again.'));
        }
        $this->set(compact('company'));
        $this->set('_serialize', ['company']);
    }
```

---

<div class="post-metadata">

**Author:** ![jarekgol](https://avatars.discourse-cdn.com/v4/letter/j/58956e/32.png) [@jarekgol](https://discourse.cakephp.org/u/jarekgol)\
**Post date:** [December 3, 2017, 2:05pm UTC](https://discourse.cakephp.org/t/saving-associated-data-with-hasone-association-not-working/3597/5 "2017-12-03T14:05:55Z")

</div>

You can add validation in Table class [https://book.cakephp.org/3.0/en/orm/validation.html#creating-a-default-validation-set](https://book.cakephp.org/3.0/en/orm/validation.html#creating-a-default-validation-set)

also it is possible to add company and user from one form, withoun manual re-write, but you must experiment by your self. I recomend to debug your variables after patchEntity and also after save. In most cases when saving goes ok you got new ID in your entities.

and adding [‘contain’=\> …] is still actual (of course if want to avoid manual re-write)

ps. and check size of first letter and plural ending in users/companies/etc.

---

<div class="post-metadata">

**Author:** ![jaynarayan](https://avatars.discourse-cdn.com/v4/letter/j/82dd89/32.png) [@jaynarayan](https://discourse.cakephp.org/u/jaynarayan)\
**Post date:** [December 3, 2017, 2:10pm UTC](https://discourse.cakephp.org/t/saving-associated-data-with-hasone-association-not-working/3597/6 "2017-12-03T14:10:21Z")

</div>

thanks, I will experiment.

---

<div class="post-metadata">

**Author:** ![Graziel](https://avatars.discourse-cdn.com/v4/letter/g/71c47a/32.png) [@Graziel](https://discourse.cakephp.org/u/Graziel)\
**Post date:** [December 3, 2017, 5:49pm UTC](https://discourse.cakephp.org/t/saving-associated-data-with-hasone-association-not-working/3597/7 "2017-12-03T17:49:02Z")

</div>

your error lies in structure of data you are passing

```auto
<?=$this->Form->control('users.0.user_name');?>
<?=$this->Form->control('users.0.password');?>

```

when you are using `hasOne` it should be singular - [https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-hasone-associations](https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-hasone-associations) so

```auto
<?= $this->Form->control('user.user_name') ?>
<?= $this->Form->control('user.password') ?>

```

if you have trouble remembering how to set your fields in form you can always fill database with fake data and get it to see how its constructed

---

<div class="post-metadata">

**Author:** ![donnidani](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/donnidani/32/744_2.png) [@donnidani](https://discourse.cakephp.org/u/donnidani)\
**Post date:** [December 4, 2017, 12:03pm UTC](https://discourse.cakephp.org/t/saving-associated-data-with-hasone-association-not-working/3597/8 "2017-12-04T12:03:30Z")

</div>

Try to check your allowed/accessible field list at  
Entity/company & Entity user.

Entity/Company  
’users’ =\> true

Entity/Users  
company =\> true
