cakephp Model validation error message not displaying in hasOne association

╄→гoц情女王★ 提交于 2019-12-02 02:21:40

validation working for only users table because i have created newEntity for users table only.

That has nothing to do with it. The problem is that you are not following the naming conventions properly.

Filenames must match classnames, so it's UserDetailsTable.php, not UserDetails.php, UsersTable.php, not usersTable.php, etc.

And the correct property name for a hasOne association, is the singular, underscored variant of the association name, so for UserDetails that would be user_detail, consequently the name for the related form control should be user_detail.name.

See also

You're trying to patch your details entity with the wrong data ($this->request->getData()). But really, there is no need to create, patch and save a separate entity in your add function, because the first level of associations will be handled transparently for you. This should work just fine:

public function add() {
    $user = $this->Users->newEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->getData());
        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));
            return $this->redirect($this->referer());
        } else {
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('user'));
}

Or, at least, it should once you correct the field names from the details entity to include "user_detail.", as @ndm said; your HTML above is still showing $this->Form->control('address',...) instead of $this->Form->control('user_detail.address',...), though it also includes fields for city and state, which aren't in your screen shot, so it's unclear what your current version might look like.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!