Can someone help me with multiple select in CakePHP 3? I have a project in CakePHP 3.6. In one of the view, I need to add student's presences, and I wanna do it with a multiple select (Select2).
In one lesson I can choose many students. The students are saved in DB, and in the select input, I wanna get the students from there (DB). I try to use select2.org script, but it does not work as I want. The input doesn't show the student's name.
This is my input:
echo $this->Form->input('students_id', [
'type' => 'select',
'multiple' => true,
'options' => $students,
'hiddenField' => false,
'id' => 'students_id',
]);
This my script:
$('#students_id').select2({
tag: true,
multiple: 'multiple'
});
And in the controller I get students list in this way:
$students = $this->Students->find('list', ['limit' => 200]);
EDIT:
StudentsTable:
class StudentsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('students');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->belongsTo('Courses', [
'foreignKey' => 'course_id',
'joinType' => 'INNER'
]);
$this->hasMany('LessonPresences', [
'foreignKey' => 'student_id'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->scalar('name')
->maxLength('name', 45)
->requirePresence('name', 'create')
->notEmpty('name');
$validator
->scalar('lastname')
->maxLength('lastname', 45)
->requirePresence('lastname', 'create')
->notEmpty('lastname');
$validator
->email('email')
->allowEmpty('email');
$validator
->scalar('phone')
->maxLength('phone', 18)
->allowEmpty('phone');
$validator
->integer('grander')
->allowEmpty('grander');
$validator
->scalar('address')
->maxLength('address', 100)
->allowEmpty('address');
$validator
->dateTime('add_date')
->requirePresence('add_date', 'create')
->notEmpty('add_date');
$validator
->date('sign_date')
->requirePresence('sign_date', 'create')
->notEmpty('sign_date');
$validator
->integer('status')
->allowEmpty('status');
$validator
->date('course_end')
->allowEmpty('course_end');
return $validator;
}
}