dev-master
9999999-dev https://github.com/jimlei/formhandler...
MIT
The Development Requires
by Jim Leirvik
dev-form-builder
dev-form-builder http://jimlei.github.io/formhandler/...
MIT
The Development Requires
by Jim Leirvik
Wallogit.com
2017 © Pedro Peláez
...
Include with composer, (*1)
composer require jimlei/formhandler:dev-master
Create the object/entity that will be modified by the form (request), (*2)
<?php // src/Entity/Article.php
namespace Acme\Entity;
class Article
{
private $id;
private $title;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
public function getTitle()
{
return $this->title;
}
public function setTitle($title)
{
$this->title = $title;
return $this;
}
}
Create the form that will map/validate the data in the request, (*3)
<?php // src/Form/ArticleForm.php
namespace Acme\Form;
use Acme\Entity\Article;
use Jimlei\FormHandler\Form;
class ArticleForm extends Form
{
public function __construct(Article $article)
{
$fields = array(
'title' => array(
'type' => 'string',
'maxLength' => '60',
'required' => true
)
);
parent::__construct($article, $fields);
}
}
It's depending on the Request->getData method so you should implement the RequestInterface in your handling of request data (method, data, query, etc)., (*4)
<?php // src/Net/Request.php
namespace Acme\Net;
use Jimlei\FormHandler\RequestInterface;
/**
* Maps a request to usable data.
*/
class Request implements RequestInterface
{
private $data;
public function __construct()
{
$this->data = json_decode(file_get_contents('php://input')) ?: array();
}
public function getData()
{
return $this->data;
}
}
Bring it together, (*5)
<?php // index.php
use Acme\Entity\Article;
use Acme\Form\ArticleForm;
use Acme\Net\Request;
require 'vendor/autoload.php';
$request = new Request();
$article = new Article();
$form = new ArticleForm($article);
$form->handleRequest($request);
if ($form->isValid())
{
// save article...
}
// do something with the errors
foreach ($form->getErrors() as $error)
{
// log, add to flash message, display otherwise, etc.
}
You can do curl requests to test it out. Play around with passing parameters, change the form field types/require/length, etc and see validation and errors change., (*6)
curl --data '{"title":"foo"}' localhost
$ vendor/bin/phpunit
...
MIT
...
MIT