问题
Here is my subjects add.ctp view
<?= $this->Form->create($subject) ?>
<fieldset>
<legend><?= __('Add Subject') ?></legend>
<?php
echo $this->Form->input('math');
echo $this->Form->input('english');
echo $this->Form->input('history');
echo $this->Form->input('science');
******this field will display all the users in drop down************* from users table
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
****UsersController.php ****
public function index()
{
$user= $this->set('users', $this->paginate());
$this->set('user', $user);
$this->set('_serialize', ['user']);
}
How to achieve this one please help me...
回答1:
If you want user select box(Dropdown) in the subject add.ctp then you should send all the list of user from add() of SubjectsController.
In subjects add method
public function add()
{
//Your previous logics
$this->loadModel('Users');
$users= $this->Users->find('list');
$this->set('users', $users);
$this->set('_serialize', ['users']);
//Your previous logics
}
In your subject add.ctp
<?= $this->Form->create($subject) ?>
<fieldset>
<legend><?= __('Add Subject') ?></legend>
<?php
echo $this->Form->input('math');
echo $this->Form->input('english');
echo $this->Form->input('history');
echo $this->Form->input('science');
echo $this->Form->input('user_id', ['options' => $users]);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
In your UsersTable(Users Model), add/edit your initialize() as follow
$this->displayField('username');
$this->primaryKey('id');
回答2:
at your Controller
$allUser = $this->Users->find(); // this will be get all user from user table $this->set('allUser', $allUser);
at your View
/**@var array $allUser */// already type of array <?= $this->Form->select('all_user', [ 'multiple' => true, 'value' => $allUser ]); ?>
回答3:
Use $this->Form->select() or $this->Form->input('users', ['options' => array()]);
if you do not want to do foreach loop.
try:
<?= $this->Form->select('users', $users); ?>
来源:https://stackoverflow.com/questions/45830056/how-to-display-all-the-users-in-table-users-to-my-subjects-table-in-add-ctp-view