PHP code example of lastzero / php-input-validation
1. Go to this page and download the library: Download lastzero/php-input-validation library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
lastzero / php-input-validation example snippets
class UserController
{
protected $user;
protected $form;
public function __construct(UserModel $user, UserForm $form)
{
$this->user = $user;
$this->form = $form;
}
// Update User
public function putAction(int $id, Request $request): array
{
// Find entity (throws exception, if not found)
$this->user->find($id);
// Form initialization with current values
$this->form->setDefinedValues($this->user->getValues());
// Set input values
$this->form->setDefinedWritableValues($request->request->all());
// Validation
$this->form->validate();
if($this->form->hasErrors()) {
throw new FormInvalidException($this->form->getFirstError());
}
// Update values in database
$this->user->update($this->form->getValues());
// Return updated values
return $this->user->getValues();
}
// Return form fields incl current values for User
public function optionsAction(int $id): array
{
// Find entity (throws exception, if not found)
$this->user->find($id);
// Form initialization with current values
$this->form->setDefinedValues($this->user->getValues());
// Returns form as JSON compatible array incl all values
return $this->form->getAsArray();
}
}
use InputValidation\Form;
use InputValidation\Form\Validator;
use InputValidation\Form\Options\YamlOptions;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Loader\YamlFileLoader;
use Symfony\Component\Translation\Loader\ArrayLoader;
$translator = new Translator('en', new MessageSelector);
$translator->addLoader('yaml', new YamlFileLoader);
$translator->addLoader('array', new ArrayLoader);
$validator = new Validator();
$options = new YamlOptions($translator);
$form = new Form($translator, $validator, $options);
$formFactory = new InputValidation\Form\Factory($translator, $validator, $options);
$formFactory->setFactoryNamespace('App\Form');
$formFactory->setFactoryPostfix('Form');
$formFactory->create('User'); // Returns instance of App\Form\UserForm