Silverstripe Version: 4.7
Question:
I’m trying to build a Contact Form block with Elemental. Everything works great until I submit the form and I get a 404.
I suspect the problem is something to do with the form action not finding the controller
The form action attribute is generated as /ContactForm/#e20 (e20 is the ID of the Contact Block)
The block has been placed on the Home Page of the website
Code as follows:
Model:
<?php
namespace Hydraulink\Blocks;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\TextareaField;
use DNADesign\Elemental\Models\BaseElement;
use Hydraulink\Blocks\ContactBlockController;
class ContactBlock extends BaseElement
{
private static $table_name = 'ElementContact';
private static $singular_name = 'Contact Block';
private static $plural_name = 'Contact Blocks';
private static $description = 'Contact details and form';
private static $controller_class = ContactBlockController::class;
private static $controller_template = "Contact";
private static $icon = 'font-icon-block-phone';
private static $db = [
'DetailsTitle' => 'Varchar(100)',
'DetailsBody' => 'Text',
'FormTitle' => 'Varchar(100)'
];
public function getCMSFields()
{
$fields = parent::getCMSFields();
$fields->removeByName('TopPageID');
$fields->addFieldsToTab('Root.Main', [
TextField::create('DetailsTitle', 'Details title'),
TextareaField::create('DetailsBody', 'Details body'),
TextField::create('FormTitle', 'Form title')
]);
return $fields;
}
public function getType()
{
return 'Contact';
}
}
Controller:
<?php
namespace Hydraulink\Blocks;
use SilverStripe\Forms\Form;
use Hydraulink\Models\Contact;
use Hydraulink\Forms\ContactForm;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\EmailField;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\TextareaField;
use DNADesign\Elemental\Controllers\ElementController;
use SilverStripe\Forms\RequiredFields;
class ContactBlockController extends ElementController
{
private static $allowed_actions = [
'ContactForm'
];
public function ContactForm()
{
$fields = FieldList::create(
TextField::create('Location'),
TextField::create('Name'),
EmailField::create('Email'),
TextareaField::create('Message')
);
$actions = FieldList::create(
FormAction::create('doSend', 'Send')
);
$required = RequiredFields::create('Name', 'Email');
return Form::create($this, 'ContactForm', $fields, $actions, $required);
}
public function doSend(array $data, Form $form)
{
$submission = Contact::create();
$form->saveInto($submission);
$submission->write();
return $this->redirectBack();
}
}
Template:
<section class="block block-contact" id="$Anchor">
<div class="wrapper">
<div class="block-contact__form">
<h2>$FormTitle</h2>
$ContactForm
</div>
</div>
</section>