Two-step form – pre-fill from API

5 months ago

zpjet
Member | 3
+
0
-

Hi, I don't know if it's the right use of MVC but how easy is to do two step form filling?

As an example, I have a form with these input fields:

Serial number
Product
Configuration
Manufactured date

There would be two buttons. Next to the SN field, there's Lookup. If the SN is in manufacturer's database (available via API), it will get the details and pre-fill the rest of the form. And then there's Save button which will create the record.

I know that ideally it would be done with i.e. Ajax but how would a JS-free implementation work? I can imagine adding functions to a presenter but it could be done smarter – similarly to error handling?

Thank you!

5 months ago

Milo
Nette Core | 1150
+
+1
-

For example this way. From top of my head, presenter method:

public function actionDefault(string $sn = null): void
{
    $form = ...;
    ...
    $snInput = $form->addText('serial')->setRequired();
    $form->addText('product');
    ...
    $form->addSubmit('load')->setValidationScope([$snInput]);
    $form->addSubmit('save');

    if ($sn) {
        $form->setDefaultValues(...);
    }

    $form->onSuccess[] = function (Form $form) {
        if ($form['load']->isSubmittedBy()) {
            $this->redirect('this', ['sn' => $form->values->serial]);
        } elseif ($form['save']->isSubmittedBy()) {
            $this->model->save(...);
            $this->flashMessage('Saved');
            $this->redirect('...');
        }
    };
}

4 months ago

zpjet
Member | 3
+
0
-

Thank you very much! I'll check it out.