Uniform: multiple forms per controller

Hello all,

I am struggeling getting two uniform forms on one page.
Does someone already managed to have solution with two forms and is able to share them.

This is how my controller looks currently (but currently no action gets exececuted)

    return function ($site, $pages, $page)
{
    $gb_form = new Form([
        'email' => [
            'rules' => ['required', 'email'],
            'message' => 'Email ist eventuell fehlerhaft oder nicht vorhanden.',
        ],
        'message' => [
            'rules' => ['required'],
            'message' => 'Nachricht wird benötigt',
        ],
        'name' => [
            'rules' => ['required'],
            'message' => 'Name wird benötigt',
        ],        
    ]);

    $contact_form = new Form([
        'email' => [
            'rules' => ['required', 'email'],
            'message' => 'Email ist eventuell fehlerhaft oder nicht vorhanden.',
        ],
        'message' => [
            'rules' => ['required'],
            'message' => 'Nachricht wird benötigt',
        ],
        'name' => [
            'rules' => ['required'],
            'message' => 'Name wird benötigt',
        ],        
    ]);    

    if (r::is('POST')) {

        if ($gb_form->successful()) {
           $gb_form->logAction([
               'guestbook-dir' => kirby()->roots()->content().'/guestbook',
           ]);
        } elseif ($contact_form->successful()) {
           $contact_form->emailAction([
               'to' => 'me@example.com',
               'from' => 'info@example.com',
            ]); 
        }
    }

    return compact('gb_form', 'contact_form');
};

I don’t think there is a isSuccessful() method, and the actions are only performed if the form is successful anyway, so try this:

if (r::is('POST')) {

           $gb_form->logAction([
               'guestbook-dir' => kirby()->roots()->content().'/guestbook',
           ]);
           $contact_form->emailAction([
               'to' => 'me@example.com',
               'from' => 'info@example.com',
            ]); 
    }

Be sure to check out this answer in the docs (especially the part with the second constructor parameter). You can use a hidden form field to identify the form that has been sent:

<input type="hidden" name="form" value="gb">
if (r::is('POST')) {
    if (get('form') === 'gb') {
        $gb_form->logAction([
            'guestbook-dir' => kirby()->roots()->content().'/guestbook',
        ]);
    } elseif (get('form') === 'contact') {
        $contact_form->emailAction([
            'to' => 'me@example.com',
            'from' => 'info@example.com',
        ]);
    }
}
3 Likes