I am creating a form that has multiple sub-forms inside it. Let me elaborate: I am creating a form for a class in the university. That class has multiple stuff in its model like "name","size", etc.. However, I need to attach students to that class. Students have only two fields in their model: "name" and "type"
I need to be able to control all of this from a single form. So normally in PHP the names of the fields would be something like:
'name'
'size'
'student[name][]'
'student[type][]'
'student[name][]'
'student[type][]'
Which would collect all of the students' information in arrays, which can later be accessed. In that form I will also need to dynamically add the number of student fields, but I guess that can be done with javascript.
My questions are: How do I control such a behaviour in Phalcon? Can I use the builder to create fields like that and can I instruct it that those fields are endless, i.e. no specific amount of students? Will I be able to validate all of the students' names using the validator?
Model to form-ready data
1) In your class model, define a relationship to the student model.
class Class extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasMany('id', 'AppName\Models\Student', 'class_id', array(
'alias' => 'students'
));
}
}
2) In your class controller instantiate the class model and reference the alias "students".
$class = new Class::findFirst($classId);
$students = $class->students;
$response = array(
'class' => $class->toArray(),
'students' => $students->toArray()
);
In case you decide not to use Javascript and create the whole form in Phalcon take a look at Phalcon/Forms.
Saving POST data back to model
Take a look at this example.
Validation
This article is helpful.