We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Repeating field collection multiple times and saving to multiple models

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?



43.9k

Hi,

you will use javascript for dynamically adding new student objects forms. So, naturally I would collect the POST request as a json object.



2.1k

this is how i use it

$component_name = new Element\Text("component_name");
$component_name->setAttribute("name", "component_name[]");
$component_name->addValidator(new Validator\PresenceOf(
array('message' => $this->translate->_("require_name"))
));

Wil this validate al of the elements inside the component_name[] aray? And then what happens when you try to edit it? Can you please share more sample code?

Thanks in advance

this is how i use it

$component_name = new Element\Text("component_name");
$component_name->setAttribute("name", "component_name[]");
$component_name->addValidator(new Validator\PresenceOf(
array('message' => $this->translate->_("require_name"))
));


2.1k
edited Feb '15

unfortunately it will not. however it is possible to create your own validators to handle it.

https://github.com/7thcubic/cphalcon/commit/e095f263d198a82d15c7be573e09acd5fbd646f3

if you wish you can simply override all the current validators to make it check if the type is array.

one bad thing abt this is it expects every single entry of the array type to be a certain type.

if you have an array of objects that has different types i believe you can override the element and create a multiple flag, after which alter that validations and adding of validators to be access an array of objects. i will try to work on it later =d