Jose Diaz-Gonzalez a0d6635e44 fix: use ::class 8 years ago
..
Form.php a0d6635e44 fix: use ::class 8 years ago
LICENSE.txt c61ab5ee95 Use HTTPS for the cakefoundation.org URL 8 years ago
README.md fe1d812c89 Update URL in *.md, *.json 9 years ago
Schema.php efef498557 Add "default" key for form schema fields. 8 years ago
composer.json d14ce62984 Use caret operator in composer.json for all sub packages 9 years ago

README.md

Total Downloads License

CakePHP Form Library

Form abstraction used to create forms not tied to ORM backed models, or to other permanent datastores. Ideal for implementing forms on top of API services, or contact forms.

Usage

use Cake\Form\Form;
use Cake\Form\Schema;
use Cake\Validation\Validator;

class ContactForm extends Form
{

    protected function _buildSchema(Schema $schema)
    {
        return $schema->addField('name', 'string')
            ->addField('email', ['type' => 'string'])
            ->addField('body', ['type' => 'text']);
    }

    protected function _buildValidator(Validator $validator)
    {
        return $validator->add('name', 'length', [
                'rule' => ['minLength', 10],
                'message' => 'A name is required'
            ])->add('email', 'format', [
                'rule' => 'email',
                'message' => 'A valid email address is required',
            ]);
    }

    protected function _execute(array $data)
    {
        // Send an email.
        return true;
    }
}

In the above example we see the 3 hook methods that forms provide:

  • _buildSchema() is used to define the schema data. You can define field type, length, and precision.
  • _buildValidator() Gets a Cake\Validation\Validator instance that you can attach validators to.
  • _execute() lets you define the behavior you want to happen when execute() is called and the data is valid.

You can always define additional public methods as you need as well.

$contact = new ContactForm();
$success = $contact->execute($data);
$errors = $contact->errors();

Documentation

Please make sure you check the official documentation