Two form actions in one form

SS 4.2.1

Hi!

I am trying to add another form action to a form. The form has two buttons on the front end but even if I click on the second form action, the first form action function is called instead of the second one.

Can anyone please help?

Example code below

public function HelloForm()
{
    $fields = new FieldList(
        TextField::create('Name', 'Your Name')
    );

    $actions = new FieldList(
        FormAction::create('doSayHello')->setTitle('Say hello'),
        FormAction::create('doSayBye')->setTitle('Say bye')
    );

    $required = new RequiredFields('Name');

    $form = new Form($this, 'HelloForm', $fields, $actions, $required);

    return $form;
}

public function doSayHello($data, Form $form)
{
    $form->sessionMessage('Hello ' . $data['Name'], 'success');

    return $this->redirectBack();
}

public function doSayBye($data, Form $form)
{
    $form->sessionMessage('Bye ' . $data['Name'], 'success');

    return $this->redirectBack();
}

Try something like:

FormAction::create('doSayBye')->setTitle('Say bye')->setAttribute('formaction', $this->Link('doSayBye'))

Maybe I misunderstood what you’re doing here… an HTML form only has one action. You can’t have more than that, else the form won’t know where it is supposed to be submitted. If you want multiple buttons within the form to do different things, then you’ll probably need to do something with javascript.

Actually (I just learnt this now) HTML5 allows inputs to specify a formaction property which trumps the form’s top level action. It’s well supported (as long as you don’t need <=IE9).

1 Like

Thanks! That’s exactly what I needed :slight_smile:

1 Like

Interesting. TIL that :slight_smile:

TIL what TIL means :smile:

1 Like