Zend Framework 2 : création d'un contrôleur simple avec formulaire
Article posté le 23-06-2014 dans la catégorie
PHP
Attention, le contenu cet article est peut-être obsolète !
Comment créer un contrôleur simple comprenant un petit formulaire sous Zend Framework 2Faisant suite à mes précédents petits tutoriels sur le développement PHP avec Zend Framework 2, voici comment mettre en place un contrôleur simple avec un petit formulaire pour insertion et edition d'informations.
Je ne reviendrais pas sur le fonctionnement du système, donc pas de commentaires de ma part ici, juste du code.
Notre objectif ici est de créer une page pour créer un auteur et éditer sa fiche. Le formulaire ne compte qu'un champ (Nom), mais la table compte aussi un champ 'Id' unique.
1- Le model
Auteurs.php
Dans le répertoire Model, créez le fichier Auteurs.php :
namespace LivresModel;
use ZendInputFilterInputFilter;
use ZendInputFilterInputFilterAwareInterface;
use ZendInputFilterInputFilterInterface;
class Auteurs implements InputFilterAwareInterface{
public $Id;
public $Nom;
protected $inputFilter;
public function exchangeArray($data) {
$this->Id = (!empty($data['Id'])) ? $data['Id'] : null;
$this->Nom = (!empty($data['Nom'])) ? $data['Nom'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'Id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'Nom',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
?>
Toujours dans le même dossier, le fichier AuteursTable.php :
namespace LivresModel;
use ZendDbTableGatewayTableGateway;
use ZendDbSqlSelect;
class AuteursTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
public function fetchAll() {
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function listeTousParOrdreAlphabetique() {
$resultSet = $this->tableGateway->select(function (Select $select) {
$select->order('Nom ASC');
});
return $resultSet;
}
public function getAuteurs($Id) {
$Id = (int) $Id;
$rowset = $this->tableGateway->select(array('Id' => $Id));
$row = $rowset->current();
if (!$row) {
throw new Exception("Could not find row $Id");
}
return $row;
}
public function rechercheAuteurs($Chaine) {
$Chaine = (string) $Chaine;
$resultSet = $this->tableGateway->select($where = "Nom LIKE '%$Chaine%'");
return $resultSet;
}
public function getNombreEnregistrements() {
$resultSet = $this->tableGateway->select();
return count($resultSet);
}
public function saveLieux(Auteurs $auteur) {
$data = array(
'Nom' => $auteur->Nom,
);
$Id = (int) $auteur->Id;
if ($Id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getAuteurs($Id)) {
$this->tableGateway->update($data, array('Id' => $Id));
} else {
throw new Exception('Auteur id does not exist');
}
}
}
public function deleteAuteurs($Id) {
$this->tableGateway->delete(array('Id' => (int) $Id));
}
}
?>
2- Le formulaire
Dans votre répertoire form, créez le fichier AuteursForm.php :
namespace LivresForm;
use ZendFormForm;
class AuteursForm extends Form
{
public function __construct($name = null)
{
parent::__construct('lieux');
$this->add(array(
'name' => 'Id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'Nom',
'type' => 'Text',
'options' => array(
'label' => 'Nom',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Add',
'id' => 'submitbutton',
),
));
}
}
?>
3- Le contrôleur
Dans le répertoire Controller, le fichier AuteursController.php :
namespace LivresController;
use ZendMvcControllerAbstractActionController;
use ZendViewModelViewModel;
use LivresModelAuteurs;
use LivresFormAuteursForm;
class AuteursController extends AbstractActionController {
protected $auteursTable;
public function indexAction() {
return new ViewModel(array(
'formulaire' => $this->addAction("getFormulaire"),
'auteurs' => $this->getAuteursTable()->listeTousParOrdreAlphabetique(),
));
}
public function getAuteursTable() {
if (!$this->auteursTable) {
$sm = $this->getServiceLocator();
$this->auteursTable = $sm->get('LivresModelAuteursTable');
}
return $this->auteursTable;
}
public function addAction($typeDemande = "") {
$form = new AuteursForm();
$form->get('submit')->setValue('Ajouter');
$request = $this->getRequest();
if ($request->isPost()) {
$auteur = new Auteurs();
$form->setInputFilter($auteur->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$auteur->exchangeArray($form->getData());
$this->getAuteursTable()->saveAuteurs($auteur);
$form = new AuteursForm();
$form->get('submit')->setValue('Ajouter');
return array('form' => $form);
}
return array('form' => $form);
} else if ($typeDemande == "getFormulaire") {
return array('form' => $form);
} else {
return $this->redirect()->toRoute('auteurs');
}
}
public function editerAction()
{
$id = (int) $this->params()->fromQuery('Id', 0);
if (!$id) {
return $this->redirect()->toRoute('auteurs', array(
'action' => 'index'
));
}
try {
$auteur = $this->getAuteursTable()->getAuteurs($id);
}
catch (Exception $ex) {
return $this->redirect()->toRoute('auteur', array(
'action' => 'index'
));
}
$form = new AuteursForm();
$form->bind($auteur);
$form->get('submit')->setAttribute('value', 'Modifier');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($auteur->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getAuteursTable()->saveAuteurs($auteur);
// Redirect to list of auteurs
return $this->redirect()->toRoute('auteurs');
}
}
return array(
'Id' => $id,
'form' => $form,
);
}
}
?>
4- Les vues
Dans le répertoire view/nomDuModule :
A- Création
indexAuteurs.phtml :
D'abord afficher le formulaire :
$form = $formulaire['form'];
$form->setAttribute('action', $this->url('auteurs', array('action' => 'add')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('Id'));
echo $this->formRow($form->get('Nom'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>
Puis lister les éléments existants avec le lien d'édition :
url('auteurs/editer') . "?Id=" . $this->escapeHtml($auteur->Id); ?>
B- Edition :
editAuteurs.phtml :
escapeHtml($title);
$form = $this->form;
$form->setAttribute('action', $this->url(
'auteurs',
array(
'action' => 'edit',
'Id' => $this->id,
)
));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('Id'));
echo $this->formRow($form->get('Nom'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>
5- La configuration
A- autoload_classmap.php
Comme dans notre projet nous utilisons le système de chargement dans lequel on doit préciser l'emplacement des classes, nous devons mettre à jour ce fichier :
'LivresControllerAuteursController' => __DIR__ . '/src/Livres/Controller/AuteursController.php',
'LivresModelAuteurs' => __DIR__ . '/src/Livres/Model/Auteurs.php',
'LivresModelAuteursTable' => __DIR__ . '/src/Livres/Model/AuteursTable.php',
'LivresFormAuteursForm' => __DIR__ . '/src/Livres/Form/AuteursForm.php',
Module.php
Ajouter dans l'en-tête du fichier :
use LivresModelAuteurs;
use LivresModelAuteursTable;
puis dans l'array de votre méthode getServiceConfig :
'LivresModelAuteursTable' => function($sm) {
$tableGateway = $sm->get('AuteursTableGateway');
$table = new AuteursTable($tableGateway);
return $table;
},
'AuteursTableGateway' => function ($sm) {
$dbAdapter = $sm->get('ZendDbAdapterAdapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Auteurs());
return new TableGateway('auteurs', $dbAdapter, null, $resultSetPrototype);
},
C- module.config.php
La partie la plus longue, mais inévitable.
Tout d'abord, dans la partie controllers invokables, rajoutez :
'LivresControllerAuteursController' => 'LivresControllerAuteursController',
Puis viens le tour des routes :
'auteurs' => array(
'type' => 'Literal',
'options' => array(
'route' => '/auteurs',
'defaults' => array(
'__NAMESPACE__' => 'LivresController',
'controller' => 'AuteursController', (1),
'action' => 'index', (2)
),
),
'verb' => 'get',
'may_terminate' => true,
'child_routes' => array(
'ajout' => array(
'type' => 'Literal',
'options' => array(
'route' => '/ajouter',
'defaults' => array(
'action' => 'add',
),
),
'verb' => 'get,post',
),
'editer' => array(
'type' => 'Segment',
'options' => array(
'route' => '/editer[/:Id]',
'constraints' => array(
'Id' => '[0-9]+',
),
'defaults' => array(
'action' => 'editer',
),
),
'verb' => 'get,post',
),
),
), //Fin route module Auteurs
Et enfin les vues. Dans la partie template_map :
'livres/auteurs/index' => __DIR__ . '/../view/livres/indexAuteurs.phtml',
'livres/auteurs/editer' => __DIR__ . '/../view/livres/editAuteurs.phtml',
Et voilà !
Cet article vous a plu? Découvrez d'autres articles :