Skip to content
Syone edited this page May 25, 2024 · 34 revisions

Form

How to create a custom form component

  1. Create a custom class that extends \Sy\Bootstrap\Component\Form, it must implement 2 methods: init() and submitAction()

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
	}

}
  1. 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');
	}
  1. 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', ['foo' => 'hello']); // You can return custom data using the optional second 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');
		}
	}
  1. 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('caffeinated@example.com');
  1. 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.foo); // You can retrieve custom data returned from submitAction()
});

Submit action response

The method submitAction() must return at the end a string in JSON format with informations that can be handle on the client side.

Structure Overview

The response is a single JSON object containing the submit action information.

Field Descriptions

  • ok (boolean): Indicates whether the submit action succeed or not.
  • message (string): The status message.
  • color (string, optional): The alert message color style: 'primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'. Default value is 'success'.
  • timeout (number): The number of milliseconds where the alert message is shown. Default value is 3500.
  • redirection (string, optional): The url where it must be redirected to.
  • Custom fields: Custom fields can be added at the same level as other keys or within nested object, depending on the context. Just ensure they do not conflict with standard field names above.

Example Response

{
  "ok": true,
  "message": "Message sent successfully",
  "foo": "This is a custom field"
}

Clone this wiki locally