-
Notifications
You must be signed in to change notification settings - Fork 1
Home
- Create a custom class that extends
\Sy\Bootstrap\Component\Form
, it must implement 2 methods:init()
andsubmitAction()
Example:
<?php
namespace Project\Component;
class MyContactForm extends \Sy\Bootstrap\Component\Form {
/**
* Send to email address
*
* @var string
*/
private $email;
/**
* @param string $email
*/
public function __construct($email) {
parent::__construct();
$this->email = $email;
}
/**
* Form inputs must be added in this method
*/
public function init() {
// TO DO
}
/**
* Form submit action must be implemented in this method
*
* @return string
*/
public function submitAction() {
// TO DO
}
}
- Add form inputs in the
init()
method
/**
* Form inputs must be added in this method
*/
public function init() {
// Set form attributes
$this->setAttribute('id', 'my-contact-form');
// Add email input
$this->addEmail([
'name' => 'email',
'required' => 'required',
'placeholder' => 'Your e-mail',
], [
'label' => 'E-mail',
]);
// Add anti spam field
$this->addAntiSpamField();
// Add message textarea
$this->textarea = $this->addTextarea([
'name' => 'message',
'required' => 'required',
'placeholder' => 'Your message',
], [
'label' => 'Message',
]);
// Add submit button
$this->addButton('Send');
}
- When the form is submitted, the method
submitAction()
is called and must return a json response at the end
/**
* Form submit action must be implemented in this method
*
* @return string
*/
public function submitAction() {
try {
// Validate & retrieve submitted data
$this->validatePost();
$from = $this->post('email');
$message = $this->post('message');
// Perform some actions with the data
mail($this->email, "Message from $from", $message);
// Return a success message in json format
return $this->jsonSuccess(
'Message sent successfully',
custom: ['foo' => 'This is a custom field'] // You can return custom data using the optional `custom` parameter
);
} catch (\Sy\Component\Html\Form\Exception $e) {
// If submitted data is not valid, return an error message
return $this->jsonError('Please fill the form correctly');
}
}
- Your custom form component is now ready to use, you can add it on your page or another component
$this->setVar('CONTACT_FORM', new MyContactForm('[email protected]');
- Customize the client side actions after the form submit
The form submission is handled in javascript.
By default the success/error message returned by the submitAction()
method will be shown in a bootstrap alert component.
You can customize actions on the client side after the form submission by adding a javascript listener on a custom event submitted.syform
document.getElementById('my-contact-form').addEventListener('submitted.syform', e => {
// You can replace entirely the default behavior by calling preventDefault()
e.preventDefault(); // Omit this if you want to keep the default behavior and just add other behavior
// Retrieve response data
const data = e.detail;
// Do nothing if it is an error
if (!data.ok) return;
// Do something if it is a success
console.log(data.message, data.custom.foo); // You can retrieve custom data returned from submitAction()
});
Here is another example where we add an event listener at the document body level. You have to do that when the form is added dynamically in the DOM.
document.body.addEventListener('submitted.syform', e => {
// We have to ensure that it is the right form submission first
const form = e.target;
if (!form.matches('#my-contact-form')) return;
// Then we can do stuff here...
});
The method submitAction()
must return at the end a string in JSON format with informations that can be handle on the client side.
The response is a single JSON containing the submit action information.
-
ok
(boolean): Indicates whether the submit action succeed or not. -
message
(string|object, optional): The status message. If message not provided, no alert will be shown.- If it's a string, it represents the message you want to display.
- If it's a JSON object, it should have the following structure:
{ "title": "Your title here", "body": "Your message body here" }
- The
title
andbody
are both strings that represent the header and the content of the message, respectively.
-
color
(string, optional): The alert message color style: 'primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'. Default value is 'success'. -
autohide
(boolean, optional): Default value is true, the message will automatically disappear after a certain period of time depending on the message length. Set false if you want that the user have to manually dismiss the message. -
reset
(boolean, optional): Reset the form if submit is successfull. Default is true. -
redirection
(string, optional): The url where it must be redirected to. -
custom
(object, optional): Custom fields can be added within this object.
{
"ok": true,
"message": "Message sent successfully",
"custom": {
"foo": "This is a custom field"
}
}
jsonSuccess(string|array $data = [], array $options = [], array $custom = []): string
-
data
parameter can be:- string: The status message.
- array: Associative array containing the JSON response fields.
-
options
Associative array for optional fields: 'redirection', 'color' etc. -
custom
Associative array for custom fields.
Example:
// No alert message
return $this->jsonSuccess();
// With an alert message
return $this->jsonSuccess('My message');
// With options and custom data
return $this->jsonSuccess('My message', ['color' => 'secondary'], ['foo' => 'Hello world']);
// In PHP 8, we can use named arguments
return $this->jsonSuccess('My message', custom: ['foo' => 'Hello world']);
// Set all data directly in the first parameter
return $this->jsonSuccess([
'message' => 'My message',
'color' => 'secondary',
'custom' => ['foo' => 'Hello world'],
]);
// Message title & body
return $this->jsonSuccess([
'message' => [
'title' => 'Success!',
'body' => 'Please check your mailbox'
],
'color' => 'secondary',
'custom' => ['foo' => 'Hello world'],
]);
jsonError(string|array $data = [], array $options = [], array $custom = []): string
-
data
parameter can be:- string: The status message.
- array: Associative array containing the JSON response fields.
-
options
Associative array for optional fields: 'redirection', 'color' etc. -
custom
Association array for custom fields.
The component Sy\Bootstrap\Component\Form\Crud\Delete
helps you to create a delete button that will use a CRUD service to delete an entry in the database.
Example:
$delete = new \Sy\Bootstrap\Component\Form\Crud\Delete(
service: 'user',
id: ['id' => $id],
options: [
'button-label' => 'Delete',
'button-attributes' => ['class' => 'btn-foo'],
'button-options' => ['color' => 'primary', 'icon' => 'paper-plane'],
'confirm' => 'Do you want to delete it?',
'selector' => '#item-' . $id,
'redirection' => Url::build('page', 'foo'),
],
attributes: [
'class' => 'form-foo',
'data-attr' => 'some value',
]
);
-
service
(string): The CRUD service name. -
id
(array): The row id on the database. -
options
(array, optional): Customization parameters. See details below. -
attributes
(array, optional): The form attributes.
-
button-label
(string): The submit button label. Default is empty string. -
button-attributes
(array): The submit button attributes. -
button-options
(array): The submit button options. -
confirm
(string): The confirm message shown before the submit action. -
flash-message
(string|array): The success flash message shown if the item is deleted successfully. Default value is 'Deleted successfully'. -
selector
(string): The element matching this selector will be remove from the DOM if the submit succeed. -
redirection
(string): Redirection URL if the submit succeed.
You can extends the class Sy\Bootstrap\Component\Form\Crud\Create
to helps you to create a database item creation form.
You have to customize fields on init()
method and the submit action on submitAction()
method.
You can extends the class Sy\Bootstrap\Component\Form\Crud
to helps you to create a database item update form.
You have to customize fields on init()
method and the submit action on submitAction()
method.