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

Multiple fields in forms

Hello

In the following form, phone type and phone number can appear an infinite number of times (the "Add" link is handled by Javascript):

How am I suppose to code this with Phalcon, both when saving a new record (start with one empty phone number) and when editing an existing one (start with x existing phone numbers)?

class MyForm extends Form
{
    public function initialize()
    {
        $field = new Text('name');
        $field->setLabel('Name');
        $this->add($field);

        $field = new Select('phone_type',
            Models\PhoneLineType::find(),
            ['using' => ['id', 'name']]
        );
        $this->add($field);

        $field = new Text('phone_number');
        $this->add($field);
    }
}
// View
foreach (?? as ??) { ?>
    <div>
        <?= $form->render('phone_type') ?>
        <?= $form->render('phone_number') ?>
    </div><?php
}

Thanks in advance!



2.1k
public function initialize($obj = null, $options = null)
{
    if($obj)
    {
        for($i = 0; $i < count($obj->number); $i++)
        {
             $field = new Select('phone_type'.$i,
            Models\PhoneLineType::find(),
            ['using' => ['id', 'name']]
            );
            $this->add($field);

        }
    }
}

something like that =d

Just ideas not sure these work, make the name an array, pretty standard PHP stuff like:

$field = new Text('name[]')

You'll get an array when posted yes? You can then sanitize, validate them separately, something like the first example here: https://docs.phalcon.io/en/latest/reference/validation.html

But instead of $_POST, its the $this->request->getPost['name']. So the form validation is not part of the form itself, but then I'm not sure how to glue this together. Perhaps you can define a custom validator, also found on that link, but within your custom validation, you place something like whats in the first example code block.