Two form actions in one form

silverstripe-4
Tags: #<Tag:0x00007f10c7d173e0>

#1

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();
}

#4

Try something like:

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

#2

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.


#7

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


#3

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).


#5

Interesting. TIL that :slight_smile:


#6

TIL what TIL means :smile: