php - Saving relations in yii2 forms - how to avoid duplication in attributes? -


i have student model (id, name, school_id) , school model (id, name, ...) relation schema is: school has many students, student can have 1 school.

<?php class school extends \yii\db\activerecord { /*.....*/ public function getstudents() {     return $this->hasmany(student::classname(), ['school_id' => 'id']); } /*.....*/ } ?> 

now want render checkboxes each student on school create form:

<?= $form->field($model, 'students')->checkboxlist(arrayhelper::map($allstudents, 'id', 'name')) ?> 

($model school instance. simplicity let's assume there not lot of students - checkboxes control enough)

now, if want add validation rule allow max 5 students (using school::rules() method) - on form submit "trying set read-only attribute students"

okay, means ar relations readonly attributes in models.

but how can use yii2 activeform , validations using rules then, without creation of bogus attribute (student_ids) won't saved db , used solely validation purposes?

is there "right" way here? thanks!

if understand correctly, u need u want 5 student checkboxes shown in school model.

in case, perhaps u dont need validation.

just define relation like:

public function getstudentsforschool() {     return $this->hasmany(student::classname(), ['school_id' => 'id'],'limit'=>5); } 

so every time u student list using function, top 5 records.


Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -