I have two tables
CREATE TABLE `user_roles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=latin1
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`user_role_id` int(11) DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I created the insertion and deletion for user roles . No i have to add the users with user roles. In the user adding form user role is displaying as empty. here is my code: UserTable.php: namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function initialize(array $config)
{
$this->hasMany('UserRoles', [
'foreignKey' => 'id',
'sort' => ['UserRoles.role_name', 'ASC']
]);
$this->displayField('role_name');
} }
UserController.php
public function add()
{
$this->set('title', 'Add Users');
$users = $this->Users->newEntity();
if($this->request->is('post')):
$users = $this->Users->patchEntity($user, $this->request-
>data);
if($this->Users->save($user)):
$this->Flash->success(__('User was created
successfully.'));
return $this->redirect(['action' => 'index']);
endif;
endif;
$this->set('users', $this->users);
$this->set('user_roles', $this->Users->UserRoles->find('list',
['id', 'role_name']));
}
**add.ctp**
<?php
//print_r($user_roles);
echo $this->Form->create($users, ['class' => 'form']);
echo $this->Form->input('username');
echo $this->Form->input('email');
echo $this->Form->input('user_role_id');
echo $this->Form->input('password');
echo $this->Form->button(__("<i class='fa fa-save'></i> Save"));
echo $this->Form->end();
?>
**UserRolesTable.php**
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UserRolesTable extends Table
{
public function initialize(array $config)
{
$this->belongsToMany('Users', [
'foreignKey' => 'user_role_id'
]);
}
public function validationDefault(Validator $validator)
{
$validator->notEmpty('role_name', 'Role name cannot be empty.');
return $validator;
}}
Its showing empty select box for user_role_id. Please help me.