From 67b75d015dc0bf8191d1551a9837a944a6fd1b28 Mon Sep 17 00:00:00 2001 From: Lars Heber Date: Wed, 8 Oct 2014 09:53:45 +0200 Subject: [PATCH] Remove ZF1 doc about form decorators - fixes ZF2 #6738 --- .../tutorials/form.decorators.composite.rst | 320 ------------------ .../tutorials/form.decorators.conclusion.rst | 11 - .../tutorials/form.decorators.individual.rst | 232 ------------- .../de/tutorials/form.decorators.intro.rst | 20 -- .../de/tutorials/form.decorators.layering.rst | 259 -------------- .../de/tutorials/form.decorators.simplest.rst | 221 ------------ .../tutorials/form.decorators.composite.rst | 309 ----------------- .../tutorials/form.decorators.conclusion.rst | 10 - .../tutorials/form.decorators.individual.rst | 225 ------------ .../en/tutorials/form.decorators.intro.rst | 18 - .../en/tutorials/form.decorators.layering.rst | 250 -------------- .../en/tutorials/form.decorators.simplest.rst | 217 ------------ .../tutorials/form.decorators.conclusion.rst | 11 - .../tutorials/form.decorators.composite.rst | 313 ----------------- .../tutorials/form.decorators.conclusion.rst | 11 - .../tutorials/form.decorators.individual.rst | 225 ------------ .../fr/tutorials/form.decorators.intro.rst | 19 -- .../fr/tutorials/form.decorators.layering.rst | 253 -------------- .../fr/tutorials/form.decorators.simplest.rst | 220 ------------ 19 files changed, 3144 deletions(-) delete mode 100644 docs/languages/de/tutorials/form.decorators.composite.rst delete mode 100644 docs/languages/de/tutorials/form.decorators.conclusion.rst delete mode 100644 docs/languages/de/tutorials/form.decorators.individual.rst delete mode 100644 docs/languages/de/tutorials/form.decorators.intro.rst delete mode 100644 docs/languages/de/tutorials/form.decorators.layering.rst delete mode 100644 docs/languages/de/tutorials/form.decorators.simplest.rst delete mode 100644 docs/languages/en/tutorials/form.decorators.composite.rst delete mode 100644 docs/languages/en/tutorials/form.decorators.conclusion.rst delete mode 100644 docs/languages/en/tutorials/form.decorators.individual.rst delete mode 100644 docs/languages/en/tutorials/form.decorators.intro.rst delete mode 100644 docs/languages/en/tutorials/form.decorators.layering.rst delete mode 100644 docs/languages/en/tutorials/form.decorators.simplest.rst delete mode 100644 docs/languages/es/tutorials/form.decorators.conclusion.rst delete mode 100644 docs/languages/fr/tutorials/form.decorators.composite.rst delete mode 100644 docs/languages/fr/tutorials/form.decorators.conclusion.rst delete mode 100644 docs/languages/fr/tutorials/form.decorators.individual.rst delete mode 100644 docs/languages/fr/tutorials/form.decorators.intro.rst delete mode 100644 docs/languages/fr/tutorials/form.decorators.layering.rst delete mode 100644 docs/languages/fr/tutorials/form.decorators.simplest.rst diff --git a/docs/languages/de/tutorials/form.decorators.composite.rst b/docs/languages/de/tutorials/form.decorators.composite.rst deleted file mode 100644 index 32cfa625e..000000000 --- a/docs/languages/de/tutorials/form.decorators.composite.rst +++ /dev/null @@ -1,320 +0,0 @@ -.. EN-Revision: none -.. _learning.form.decorators.composite: - -Erstellung und Darstellung von kombinierten Elementen -===================================================== - -Im :ref:`letzten Abschnitt `, hatten wir ein Beispiel welches ein "Element -für das Geburtsdatum" gezeigt hat: - -.. code-block:: php - :linenos: - -
- dateOfBirth->renderLabel() ?> - formText('dateOfBirth[day]', '', array( - 'size' => 2, 'maxlength' => 2)) ?> - / - formText('dateOfBirth[month]', '', array( - 'size' => 2, 'maxlength' => 2)) ?> - / - formText('dateOfBirth[year]', '', array( - 'size' => 4, 'maxlength' => 4)) ?> -
- -Wie könnte man dieses Element als ``Zend\Form\Element`` Element darstellen? Wie kann man einen Decoratpr schreiben -um es darzustellen? - -.. _learning.form.decorators.composite.element: - -Das Element ------------ - -Die Fragen darüber wie das Element arbeiten würde beinhalten: - -- Wir würde man den Wert setzen und empfangen? - -- Wie würde der Wert geprüft werden? - -- Wie würde man trotzdem getrennte Formulareingaben für diese drei Abschnitte erlauben (Tag, Monat, Jahr)? - -Die ersten zwei Fragen drehen sich um das Formularelement selbst: Wie würden ``setValue()`` und ``getValue()`` -arbeiten? Es gibt aktuell eine weitere implizite Frage durch die Frage über den Decorator: Wie würde man -getrennte Datenabschnitte vom Element empfangen und/oder setzen? - -Die Lösung besteht darin die ``setValue()`` Methode des Elements zu überladen um eigene Logik anzubieten. In -diesem speziellen Fall sollte unser Element drei getrennte Verhalten haben: - -- Wenn ein Integer Zeitpunkt angegeben wird, sollte er verwendet werden um Tag, Monat und Jahr zu erkennen und zu - speichern. - -- Wenn ein textueller String angegeben wird sollte er in einen Zeitpunkt gecastet werden, und dieser Wert sollte - verwendet werden um Tag, Monat und Jahr zu erkennen und zu speichern. - -- Wenn ein Array angegeben wird welches die Schlüssel für Tag, Monat und Jahr enthält, dann sollten diese Werte - gespeichert werden. - -Intern werden Tag, Monat und Jahr getrennt gespeichert. Wenn der Wert des Elements empfangen wird, wird das in -einem normalisierten String Format getan. Wir überschreiben ``getValue()`` und ordnen die getrennten -Datenabschnitte dem endgültigen String zu. - -So würde die Klasse aussehen: - -.. code-block:: php - :linenos: - - class My_Form_Element_Date extends Zend\Form\Element\Xhtml - { - protected $_dateFormat = '%year%-%month%-%day%'; - protected $_day; - protected $_month; - protected $_year; - - public function setDay($value) - { - $this->_day = (int) $value; - return $this; - } - - public function getDay() - { - return $this->_day; - } - - public function setMonth($value) - { - $this->_month = (int) $value; - return $this; - } - - public function getMonth() - { - return $this->_month; - } - - public function setYear($value) - { - $this->_year = (int) $value; - return $this; - } - - public function getYear() - { - return $this->_year; - } - - public function setValue($value) - { - if (is_int($value)) { - $this->setDay(date('d', $value)) - ->setMonth(date('m', $value)) - ->setYear(date('Y', $value)); - } elseif (is_string($value)) { - $date = strtotime($value); - $this->setDay(date('d', $date)) - ->setMonth(date('m', $date)) - ->setYear(date('Y', $date)); - } elseif (is_array($value) - && (isset($value['day']) - && isset($value['month']) - && isset($value['year']) - ) - ) { - $this->setDay($value['day']) - ->setMonth($value['month']) - ->setYear($value['year']); - } else { - throw new Exception('Ungültiger Datumswert angegeben'); - } - - return $this; - } - - public function getValue() - { - return str_replace( - array('%year%', '%month%', '%day%'), - array($this->getYear(), $this->getMonth(), $this->getDay()), - $this->_dateFormat - ); - } - } - -Diese Klasse bietet einige nette Flexibilitäten -- wir können Standardwerte von unserer Datenbank setzen, und -sicher sein das der Wert richtig gespeichert und dargestellt wird. Zusätzlich können wir erlauben den Wert von -einem Array zu setzen welches über die Formulareingabe übergebenen wurde. Letztendlich haben wir getrennte -Zugriffe für jeden Datenabschnitt, welche wir jetzt in einem Decorator verwenden können um ein kombiniertes -Element zu erstellen. - -.. _learning.form.decorators.composite.decorator: - -Der Decorator -------------- - -Bei der erneuten Betrachtung des Beispiels im letzten Abschnitt, nehmen wir wir an dass wir wollen das unsere -Benutzer Jahr, Monat und Tag separat eingeben. *PHP* erlaubt es uns glücklicherweise die Array Schreibweise zu -verwenden wenn Elemente erstellt werden, deshalb ist es möglich diese drei Entitäten in einem einzelnen Wert zu -fangen -- und wir erstellen jetzt ein ``Zend_Form`` Element das solch einen Array Wert verarbeiten kann. - -Der Decorator ist relativ einfach: er holt Tag, Monat und Jahr vom Element, und übergibt jedes einem eigenen View -Helfer um die individuellen Formular Eingaben darzustellen; diese werden dann für das endgültige Markup -gesammelt. - -.. code-block:: php - :linenos: - - class My_Form_Decorator_Date extends Zend\Form\Decorator\Abstract - { - public function render($content) - { - $element = $this->getElement(); - if (!$element instanceof My_Form_Element_Date) { - // wir wollen nur das Date Element darstellen - return $content; - } - - $view = $element->getView(); - if (!$view instanceof Zend\View\Interface) { - // verwenden von View Helfers, deshalb ist nichts zu tun - // wenn keine View vorhanden ist - return $content; - } - - $day = $element->getDay(); - $month = $element->getMonth(); - $year = $element->getYear(); - $name = $element->getFullyQualifiedName(); - - $params = array( - 'size' => 2, - 'maxlength' => 2, - ); - $yearParams = array( - 'size' => 4, - 'maxlength' => 4, - ); - - $markup = $view->formText($name . '[day]', $day, $params) - . ' / ' . $view->formText($name . '[month]', $month, $params) - . ' / ' . $view->formText($name . '[year]', $year, $yearParams); - - switch ($this->getPlacement()) { - case self::PREPEND: - return $markup . $this->getSeparator() . $content; - case self::APPEND: - default: - return $content . $this->getSeparator() . $markup; - } - } - } - -Jetzt müssen wir kleinere Änderungen an unserem Formular Element durchführen und Ihm sagen das wir den obigen -Decorator als Standard verwenden wollen. Das benötigt zwei Schritte. Erstens müssen wir das Element über den -Pfad des Decorators informieren. Wir können das im Constructor tun: - -.. code-block:: php - :linenos: - - class My_Form_Element_Date extends Zend\Form\Element\Xhtml - { - // ... - - public function __construct($spec, $options = null) - { - $this->addPrefixPath( - 'My_Form_Decorator', - 'My/Form/Decorator', - 'decorator' - ); - parent::__construct($spec, $options); - } - - // ... - } - -Es ist zu beachten dass das im Constructor getan wird und nicht in ``init()``. Es gibt hierfür zwei Gründe. -Erstens erlaubt dies das Element später zu erweitern um Logik in ``init`` hinzuzufügen ohne das man sich Gedanken -über den Aufruf von ``parent::init()`` machen muss. Zweitens erlaubt es zusätzliche Plugin Pfade über die -Konfiguration zu übergeben oder in einer ``init`` Methode die dann das Überladen des standardmäßigen ``Date`` -Decorators mit einem eigenen Ersatz erlaubt. - -Als nächstes überladen wir die ``loadDefaultDecorators()`` Methode um unseren neuen ``Date`` Decorator zu -verwenden: - -.. code-block:: php - :linenos: - - class My_Form_Element_Date extends Zend\Form\Element\Xhtml - { - // ... - - public function loadDefaultDecorators() - { - if ($this->loadDefaultDecoratorsIsDisabled()) { - return; - } - - $decorators = $this->getDecorators(); - if (empty($decorators)) { - $this->addDecorator('Date') - ->addDecorator('Errors') - ->addDecorator('Description', array( - 'tag' => 'p', - 'class' => 'description' - )) - ->addDecorator('HtmlTag', array( - 'tag' => 'dd', - 'id' => $this->getName() . '-element' - )) - ->addDecorator('Label', array('tag' => 'dt')); - } - } - - // ... - } - -Wie sieht die endgültige Ausgabe aus=? Nehmen wir das folgende Element an: - -.. code-block:: php - :linenos: - - $d = new My_Form_Element_Date('dateOfBirth'); - $d->setLabel('Geburtsdatum: ') - ->setView(new Zend\View\View()); - - // Das sind Äquivalente: - $d->setValue('20 April 2009'); - $d->setValue(array('year' => '2009', 'month' => '04', 'day' => '20')); - -Wenn man dieses Element ausgibt erhält man das folgende Markup (mit einigen wenigen Modifikationen an Leerzeichen -für die Lesbarkeit): - -.. code-block:: html - :linenos: - -
-
- / - / - -
- -.. _learning.form.decorators.composite.conclusion: - -Zusammenfassung ---------------- - -Wir haben jetzt ein Element das mehrere zusammengehörende Formular Eingabefelder darstellen kann, und die -getrennten Felder anschließend als einzelne Entität behandelt -- das Element ``dateOfBirth`` wird als Array an -das Element übergeben, und das Element wird anschließend, wie vorher erwähnt, die passenden Datenabschnitte -erstellen und einen Wert zurückgeben den wir für die meisten Backends verwenden können. - -Am Ende erhält man eine einheitliche *API* für ein Element welche man verwenden kann um ein Element zu -beschreiben welches einen kombinierten Wert repräsentiert. - - diff --git a/docs/languages/de/tutorials/form.decorators.conclusion.rst b/docs/languages/de/tutorials/form.decorators.conclusion.rst deleted file mode 100644 index 26f2b1a08..000000000 --- a/docs/languages/de/tutorials/form.decorators.conclusion.rst +++ /dev/null @@ -1,11 +0,0 @@ -.. EN-Revision: none -.. _learning.form.decorators.conclusion: - -Fazit -===== - -Formular Dekoratore sind ein System welches einige Zeit in Anspruch nimmt um es zu lernen. Zuerst fühlt es sich -mühsam und überaus komplex an. Hoffentlich helfen die verschiedenen Themen die in diesem Kapitel beschrieben sind -wie beide arbeiten, sowie Strategien für deren effektive Verwendung in eigenen Formularen. - - diff --git a/docs/languages/de/tutorials/form.decorators.individual.rst b/docs/languages/de/tutorials/form.decorators.individual.rst deleted file mode 100644 index c3cfbd72a..000000000 --- a/docs/languages/de/tutorials/form.decorators.individual.rst +++ /dev/null @@ -1,232 +0,0 @@ -.. EN-Revision: none -.. _learning.form.decorators.individual: - -Darstellung individueller Decorators -==================================== - -Im :ref:`vorigen Abschnitt ` haben wir uns angesehen wie man Decorators -kombinieren kann um komplexe Ausgaben zu erstellen. Wir haben gesehen dass, obwohl wir eine Tonne an Flexibilität -mit diesem Ansatz haben, fügt er auch einiges an Komplexität und Overhead hinzu. In diesem Abschnitt behandeln -wir wie Decorators individuell dargestellt werden können um eigene Markups für Formulare und/oder individuelle -Elemente zu erstellen. - -Sobald man die Decorators registriert hat, kann man Sie später durch Ihren Namen vom Element erhalten. Sehen wir -uns das vorhergehende Beispiel nochmals an: - -.. code-block:: php - :linenos: - - $element = new Zend\Form\Element('foo', array( - 'label' => 'Foo', - 'belongsTo' => 'bar', - 'value' => 'test', - 'prefixPath' => array('decorator' => array( - 'My_Decorator' => 'path/to/decorators/', - )), - 'decorators' => array( - 'SimpleInput' - array('SimpleLabel', array('placement' => 'append')), - ), - )); - -Wenn wir nur den ``SimpleInput`` holen und darstellen wollen, können wir das tun indem wir die Methode -``getDecorator()`` verwenden: - -.. code-block:: php - :linenos: - - $decorator = $element->getDecorator('SimpleInput'); - echo $decorator->render(''); - -Das ist recht einfach kann aber sogar noch einfacher gemacht werden; machen wir es in einer einzelnen Zeile: - -.. code-block:: php - :linenos: - - echo $element->getDecorator('SimpleInput')->render(''); - -Nicht schlecht, aber trotzdem noch etwas komplex. Um es noch einfacher zu machen wurde mit 1.7 eine -Kurzschreibweise in ``Zend_Form`` eingeführt: man kann jeden registrierten Decorator darstellen indem eine Methode -des Formats ``renderDecoratorName()`` aufgerufen wird. Das wird effektiv ausgeführt wie man oben sieht, macht aber -das ``$content`` Argument optional und vereinfacht die Verwendung: - -.. code-block:: php - :linenos: - - echo $element->renderSimpleInput(); - -Das ist ein netter Trick, aber wie und warum sollte man Ihn verwenden? - -Viele Entwickler und Designer haben sehr präzise Notwendigkeiten für das Markup in Ihren Formularen. Sie würden -eher volle Kontrolle über Ihre Ausgabe haben wollen als auf eine automatisiertere Lösung zu stützen welche mit -Ihrem Design mehr oder weniger konform geht. In anderen Fällen benötigt das Layout des Formulars ein -spezialisierteres Markup -- gruppieren von eigenen Elementen, einige von Ihnen unsichtbar solange bis ein -bestimmter Link ausgewählt wurde, usw. - -Sehen wir uns die Fähigkeit an individuelle Decorators darzustellen und ein spezialisierteres Markup zu erstellen. - -Definieren wir als erstes ein Formular. Unser Formular holt demografische Details des Benutzers. Das Markup wird -sehr stark anpassbar sein, und in einigen Fällen View Helfer direkt verwenden statt den Formular Elementen um -seine Ziele zu erreichen. Hier ist die grundsätzliche Definition des Formulars: - -.. code-block:: php - :linenos: - - class My_Form_UserDemographics extends Zend_Form - { - public function init() - { - // Einen Pfad für eigene Decorators hinzufügen - $this->addElementPrefixPaths(array( - 'decorator' => array('My_Decorator' => 'My/Decorator'), - )); - - $this->addElement('text', 'firstName', array( - 'label' => 'Vorname: ', - )); - $this->addElement('text', 'lastName', array( - 'label' => 'Nachname: ', - )); - $this->addElement('text', 'title', array( - 'label' => 'Titel: ', - )); - $this->addElement('text', 'dateOfBirth', array( - 'label' => 'Geburtsdatum (DD/MM/YYYY): ', - )); - $this->addElement('text', 'email', array( - 'label' => 'Emailadresse: ', - )); - $this->addElement('password', 'password', array( - 'label' => 'Passwort: ', - )); - $this->addElement('password', 'passwordConfirmation', array( - 'label' => 'Passwort wiederholen: ', - )); - } - } - -.. note:: - - Wir definieren jetzt keine Prüfungen oder Filter, da Sie für die Diskussion der Decorators nicht relevant - sind. In einem Real-World Szenario sollte man Sie definieren. - -Da dass auf dem Weg ist, besprechen wir wie dieses Formular angezeigt werden soll. Eine übliche Ausdrucksweise mit -Vor-/Nachnamen ist Sie in einer einzelnen Zeile anzuzeigen; wenn ein Titel angegeben wird, ist er oft auch in der -selben Zeile. Daten werden oft in drei Felder separiert und Seite an Seite angezeigt, wen keine JavaScript -Datumsauswahl verwendet wird. - -Verwenden wir die Fähigkeit die Decorators eines Elements einzeln darzustellen um das zu ermöglichen. Erstens ist -zu beachten das keine expliziten Decorators für die angegebenen Elemente definiert wurden. Als Auffrischung sind -die standardmäßigen Decorators für die (meisten) Elemente: - -- ``ViewHelper``: Verwendet einen View Helfer um eine Formulareingabe darzustellen - -- ``Errors``: Verwendet den View Helfer ``FormErrors`` um Prüfungsfehler darzustellen - -- ``Description``: Verwendet den View Helfer ``FormNote`` um die Beschreibung des Elements darzustellen (wenn - vorhanden) - -- ``HtmlTag``: Umschließt die obigen drei Elemente mit einem **
** Tag - -- ``Label``: Stellt die Überschrift des Elements dar indem es den View Helfer ``FormLabel`` verwendet (und Ihn in - ein **
** Tag umhüllt) - -Auch als Auffrischung, kann man auf jedes Element eines Formulars zugreifen wie wenn es die Eigenschaft einer -Klasse wäre; auf das Element muss einfach mit dem Namen verwiesen werden der Ihm zugeordnet wurde. - -Unser View Skript könnte dann wie folgt aussehen: - -.. code-block:: php - :linenos: - - form; - // Entfernt
von der Erstellung der Überschrift - foreach ($form->getElements() as $element) { - $element->getDecorator('label')->setOption('tag', null); - } - ?> -
-
- title->renderLabel() - . $form->title->renderViewHelper() ?> - firstName->renderLabel() - . $form->firstName->renderViewHelper() ?> - lastName->renderLabel() - . $form->lastName->renderViewHelper() ?> -
-
- dateOfBirth->renderLabel() ?> - formText('dateOfBirth[day]', '', array( - 'size' => 2, 'maxlength' => 2)) ?> - / - formText('dateOfBirth[month]', '', array( - 'size' => 2, 'maxlength' => 2)) ?> - / - formText('dateOfBirth[year]', '', array( - 'size' => 4, 'maxlength' => 4)) ?> -
-
- password->renderLabel() - . $form->password->renderViewHelper() ?> -
-
- passwordConfirmation->renderLabel() - . $form->passwordConfirmation->renderViewHelper() ?> -
- formSubmit('submit', 'Speichern') ?> -
- -Wenn man obiges View Skript verwendet erhält man voraussichtlich das folgende *HTML* (angenähert da das *HTML* -von anbei formatiert ist): - -.. code-block:: html - :linenos: - -
-
- - - - - - - - -
- -
- - - / - - / - -
- -
- - -
- -
-
** Tag). - -- ``Label`` (stellt das Label dar indem es dem oben stehenden vorangestellt wird und umhüllt es mit einem **
** - Tag). - -Man wird feststellen das jeder dieser Decorators nur ein Ding tut, und auf einem speziellen Teil der Metadaten -arbeitet die im Formularelement gespeichert sind: der ``Errors`` Decorator holt Prüffehler und stellt Sie dar; der -``Label`` Decorator holt die Überschrift und stellt Sie dar. Das erlaubt einzelnen Decorators sehr bündig, -wiederholbar, und viel wichtiger, testbar zu sein. - -Hier kommt auch das ``$content`` Argument zum Einsatz: Jede ``render()`` Methode eines Decorators ist designt um -Inhalte zu akzeptieren, und diesen dann entweder zu ersetzen (normalerweise indem er umhüllt wird), hinten -anzuhängen, oder voranzustellen. - -Es ist also am Besten vom Prozess der Dekoration als Erstellung einer Zwiebel zu denken, von Innen nach Außen. - -Um den Prozess zu vereinfachen sehen wir in der Beispiel :ref:`des vorherigen Abschnitts -`. Nochmals: - -.. code-block:: php - :linenos: - - class My_Decorator_SimpleInput extends Zend\Form\Decorator\Abstract - { - protected $_format = '' - . ''; - - public function render($content) - { - $element = $this->getElement(); - $name = htmlentities($element->getFullyQualifiedName()); - $label = htmlentities($element->getLabel()); - $id = htmlentities($element->getId()); - $value = htmlentities($element->getValue()); - - $markup = sprintf($this->_format, $id, $label, $id, $name, $value); - return $markup; - } - } - -Jetzt entfernen wir die Funktionalität des Labels und bauen einen eigenen Decorator dafür. - -.. code-block:: php - :linenos: - - class My_Decorator_SimpleInput extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $name = htmlentities($element->getFullyQualifiedName()); - $id = htmlentities($element->getId()); - $value = htmlentities($element->getValue()); - - $markup = sprintf($this->_format, $id, $name, $value); - return $markup; - } - } - - class My_Decorator_SimpleLabel extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $id = htmlentities($element->getId()); - $label = htmlentities($element->getLabel()); - - $markup = sprintf($this->_format, $id, $label); - return $markup; - } - } - -Das könnte jetzt schön und gut aussehen, aber da ist ein Problem: wie gerade geschrieben gewinnt der letzte -Decorator und überschreibt alles. Man endet nur mit der Eingabe oder nur dem Label, abhängig davon was als -letztes registriert wurde. - -Um das zu verhindern, muss dass in ``$content`` übergebene irgendwie mit dem Markup verbunden werden: - -.. code-block:: php - :linenos: - - return $content . $markup; - -Das Problem mit dem obigen Ansatz kommt dann wenn man programmtechnisch wählen will ob der originale Inhalt das -neue Markup angehängt oder vorangestellt werden soll. Glücklicherweise gibt es hierfür bereits einen -Standardmechanismus; ``Zend\Form\Decorator\Abstract`` hat ein Konzept der Platzierung und definiert einige -Konstanten um es anzusprechen. Zusätzlich erlaubt es die Spezifikation eines Separators der zwischen beide -platziert wird. Verwenden wir Sie: - -.. code-block:: php - :linenos: - - class My_Decorator_SimpleInput extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $name = htmlentities($element->getFullyQualifiedName()); - $id = htmlentities($element->getId()); - $value = htmlentities($element->getValue()); - - $markup = sprintf($this->_format, $id, $name, $value); - - $placement = $this->getPlacement(); - $separator = $this->getSeparator(); - switch ($placement) { - case self::PREPEND: - return $markup . $separator . $content; - case self::APPEND: - default: - return $content . $separator . $markup; - } - } - } - - class My_Decorator_SimpleLabel extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $id = htmlentities($element->getId()); - $label = htmlentities($element->getLabel()); - - $markup = sprint($this->_format, $id, $label); - - $placement = $this->getPlacement(); - $separator = $this->getSeparator(); - switch ($placement) { - case self::APPEND: - return $markup . $separator . $content; - case self::PREPEND: - default: - return $content . $separator . $markup; - } - } - } - -Es sollte beachtet werden das wir das Standardverhalten für jeden verändern; die Annahme besteht darin das die -Überschrift dem Inhalt folgt und die Eingabe vorangestellt wird. - -Erstellen wir jetzt ein Formularelement das Sie verwendet: - -.. code-block:: php - :linenos: - - $element = new Zend\Form\Element('foo', array( - 'label' => 'Foo', - 'belongsTo' => 'bar', - 'value' => 'test', - 'prefixPath' => array('decorator' => array( - 'My_Decorator' => 'path/to/decorators/', - )), - 'decorators' => array( - 'SimpleInput', - 'SimpleLabel', - ), - )); - -Wie arbeitet das? Wenn wir ``render()`` aufrufen, wird das Element durch die verschiedenen angehängten Decorators -iterieren, indem auf jedem ``render()`` aufgerufen wird. Er übergibt einen leeren String zu dem allerersten, und -was auch immer für ein Inhalt erstellt wird, wird dieser an den nächsten übergeben, und so weiter: - -- Der initiale Inhalt ist ein leerer String: ''. - -- '' wird an den ``SimpleInput`` Decorator übergeben welcher dann eine Formulareingabe erstellt und diese an den - leeren String anhängt: ****. - -- Die Eingabe wird dann als Inhalt an den ``SimpleLabel`` Decorator übergeben, welche eine Überschrift erzeugt - und diese dem originalen Inhalt voranstellt; der standardmäßige Separator ist ein ``PHP_EOL`` Zeichen, was uns - folgendes gibt: **
-
- / - / - -
- -.. _learning.form.decorators.composite.conclusion: - -Conclusion ----------- - -We now have an element that can render multiple related form input fields, and then handle the aggregated fields as -a single entity -- the ``dateOfBirth`` element will be passed as an array to the element, and the element will -then, as we noted earlier, create the appropriate date segments and return a value we can use for most backends. - -In the end, you get a uniform element *API* you can use to describe an element representing a composite value. - - diff --git a/docs/languages/en/tutorials/form.decorators.conclusion.rst b/docs/languages/en/tutorials/form.decorators.conclusion.rst deleted file mode 100644 index 3113da09c..000000000 --- a/docs/languages/en/tutorials/form.decorators.conclusion.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. _learning.form.decorators.conclusion: - -Conclusion -========== - -Form decorators are a system that takes some time to learn. At first, they will likely feel cumbersome and overly -complex. Hopefully the various topics covered in this chapter will help you to understand both how they work, as -well as strategies for using them effectively in your forms. - - diff --git a/docs/languages/en/tutorials/form.decorators.individual.rst b/docs/languages/en/tutorials/form.decorators.individual.rst deleted file mode 100644 index 965cf26ee..000000000 --- a/docs/languages/en/tutorials/form.decorators.individual.rst +++ /dev/null @@ -1,225 +0,0 @@ -.. _learning.form.decorators.individual: - -Rendering Individual Decorators -=============================== - -In the :ref:`previous section `, we looked at how you can combine decorators to -create complex output. We noted that while you have a ton of flexibility with this approach, it also adds some -complexity and overhead. In this section, we will examine how to render decorators individually in order to create -custom markup for forms and/or individual elements. - -Once you have registered your decorators, you can later retrieve them by name from the element. Let's review the -previous example: - -.. code-block:: php - :linenos: - - $element = new Zend\Form\Element('foo', array( - 'label' => 'Foo', - 'belongsTo' => 'bar', - 'value' => 'test', - 'prefixPath' => array('decorator' => array( - 'My_Decorator' => 'path/to/decorators/', - )), - 'decorators' => array( - 'SimpleInput', - array('SimpleLabel', array('placement' => 'append')), - ), - )); - -If we wanted to pull and render just the ``SimpleInput`` decorator, we can do so using the ``getDecorator()`` -method: - -.. code-block:: php - :linenos: - - $decorator = $element->getDecorator('SimpleInput'); - echo $decorator->render(''); - -This is pretty easy, but it can be made even easier; let's do it in a single line: - -.. code-block:: php - :linenos: - - echo $element->getDecorator('SimpleInput')->render(''); - -Not too bad, but still a little complex. To make this easier, a shorthand notation was introduced into -``Zend_Form`` in 1.7: you can render any registered decorator by calling a method of the format -``renderDecoratorName()``. This will effectively perform what you see above, but makes the ``$content`` argument -optional and simplifies the usage: - -.. code-block:: php - :linenos: - - echo $element->renderSimpleInput(); - -This is a neat trick, but how and why would you use it? - -Many developers and designers have very precise markup needs for their forms. They would rather have full control -over the output than rely on a more automated solution which may or may not conform to their design. In other -cases, the form layout may require a lot of specialized markup -- grouping arbitrary elements, making some -invisible unless a particular link is selected, etc. - -Let's utilize the ability to render individual decorators to create some specialized markup. - -First, let's define a form. Our form will capture a user's demographic details. The markup will be highly -customized, and in some cases use view helpers directly instead of form elements in order to achieve its goals. -Here is the basic form definition: - -.. code-block:: php - :linenos: - - class My_Form_UserDemographics extends Zend_Form - { - public function init() - { - // Add a path for my own decorators - $this->addElementPrefixPaths(array( - 'decorator' => array('My_Decorator' => 'My/Decorator'), - )); - - $this->addElement('text', 'firstName', array( - 'label' => 'First name: ', - )); - $this->addElement('text', 'lastName', array( - 'label' => 'Last name: ', - )); - $this->addElement('text', 'title', array( - 'label' => 'Title: ', - )); - $this->addElement('text', 'dateOfBirth', array( - 'label' => 'Date of Birth (DD/MM/YYYY): ', - )); - $this->addElement('text', 'email', array( - 'label' => 'Your email address: ', - )); - $this->addElement('password', 'password', array( - 'label' => 'Password: ', - )); - $this->addElement('password', 'passwordConfirmation', array( - 'label' => 'Confirm Password: ', - )); - } - } - -.. note:: - - We're not defining any validators or filters at this time, as they are not relevant to the discussion of - decoration. In a real-world scenario, you should define them. - -With that out of the way, let's consider how we might want to display this form. One common idiom with first/last -names is to display them on a single line; when a title is provided, that is often on the same line as well. Dates, -when not using a JavaScript date chooser, will often be separated into three fields displayed side by side. - -Let's use the ability to render an element's decorators one by one to accomplish this. First, let's note that no -explicit decorators were defined for the given elements. As a refresher, the default decorators for (most) elements -are: - -- ``ViewHelper``: utilize a view helper to render a form input - -- ``Errors``: utilize the ``FormErrors`` view helper to render validation errors - -- ``Description``: utilize the ``FormNote`` view helper to render the element description (if any) - -- ``HtmlTag``: wrap the above three items in a **
** tag - -- ``Label``: render the element label using the ``FormLabel`` view helper (and wrap it in a **
** tag) - -Also, as a refresher, you can access any element of a form as if it were a class property; simply reference the -element by the name you assigned it. - -Our view script might then look like this: - -.. code-block:: php - :linenos: - - form; - // Remove
from label generation - foreach ($form->getElements() as $element) { - $element->getDecorator('label')->setOption('tag', null); - } - ?> -
-
- title->renderLabel() - . $form->title->renderViewHelper() ?> - firstName->renderLabel() - . $form->firstName->renderViewHelper() ?> - lastName->renderLabel() - . $form->lastName->renderViewHelper() ?> -
-
- dateOfBirth->renderLabel() ?> - formText('dateOfBirth[day]', '', array( - 'size' => 2, 'maxlength' => 2)) ?> - / - formText('dateOfBirth[month]', '', array( - 'size' => 2, 'maxlength' => 2)) ?> - / - formText('dateOfBirth[year]', '', array( - 'size' => 4, 'maxlength' => 4)) ?> -
-
- password->renderLabel() - . $form->password->renderViewHelper() ?> -
-
- passwordConfirmation->renderLabel() - . $form->passwordConfirmation->renderViewHelper() ?> -
- formSubmit('submit', 'Save') ?> -
- -If you use the above view script, you'll get approximately the following *HTML* (approximate, as the *HTML* below -is formatted): - -.. code-block:: html - :linenos: - -
-
- - - - - - - - -
- -
- - - / - - / - -
- -
- - -
- -
-
** tag. - -- ``Label`` (render the label preceding the above, wrapped in a **
** tag. - -You'll notice that each of these decorators does just one thing, and operates on one specific piece of metadata -stored in the form element: the ``Errors`` decorator pulls validation errors and renders them; the ``Label`` -decorator pulls just the label and renders it. This allows the individual decorators to be very succinct, -repeatable, and, more importantly, testable. - -It's also where that ``$content`` argument comes into play: each decorator's ``render()`` method is designed to -accept content, and then either replace it (usually by wrapping it), prepend to it, or append to it. - -So, it's best to think of the process of decoration as one of building an onion from the inside out. - -To simplify the process, we'll take a look at the example from :ref:`the previous section -`. Recall: - -.. code-block:: php - :linenos: - - class My_Decorator_SimpleInput extends Zend\Form\Decorator\Abstract - { - protected $_format = '' - . ''; - - public function render($content) - { - $element = $this->getElement(); - $name = htmlentities($element->getFullyQualifiedName()); - $label = htmlentities($element->getLabel()); - $id = htmlentities($element->getId()); - $value = htmlentities($element->getValue()); - - $markup = sprintf($this->_format, $id, $label, $id, $name, $value); - return $markup; - } - } - -Let's now remove the label functionality, and build a separate decorator for that. - -.. code-block:: php - :linenos: - - class My_Decorator_SimpleInput extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $name = htmlentities($element->getFullyQualifiedName()); - $id = htmlentities($element->getId()); - $value = htmlentities($element->getValue()); - - $markup = sprintf($this->_format, $id, $name, $value); - return $markup; - } - } - - class My_Decorator_SimpleLabel extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $id = htmlentities($element->getId()); - $label = htmlentities($element->getLabel()); - - $markup = sprintf($this->_format, $id, $label); - return $markup; - } - } - -Now, this may look all well and good, but here's the problem: as written currently, the last decorator to run wins, -and overwrites everything. You'll end up with just the input, or just the label, depending on which you register -last. - -To overcome this, simply concatenate the passed in ``$content`` with the markup somehow: - -.. code-block:: php - :linenos: - - return $content . $markup; - -The problem with the above approach comes when you want to programmatically choose whether the original content -should precede or append the new markup. Fortunately, there's a standard mechanism for this already; -``Zend\Form\Decorator\Abstract`` has a concept of placement and defines some constants for matching it. -Additionally, it allows specifying a separator to place between the two. Let's make use of those: - -.. code-block:: php - :linenos: - - class My_Decorator_SimpleInput extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $name = htmlentities($element->getFullyQualifiedName()); - $id = htmlentities($element->getId()); - $value = htmlentities($element->getValue()); - - $markup = sprintf($this->_format, $id, $name, $value); - - $placement = $this->getPlacement(); - $separator = $this->getSeparator(); - switch ($placement) { - case self::PREPEND: - return $markup . $separator . $content; - case self::APPEND: - default: - return $content . $separator . $markup; - } - } - } - - class My_Decorator_SimpleLabel extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $id = htmlentities($element->getId()); - $label = htmlentities($element->getLabel()); - - $markup = sprint($this->_format, $id, $label); - - $placement = $this->getPlacement(); - $separator = $this->getSeparator(); - switch ($placement) { - case self::APPEND: - return $markup . $separator . $content; - case self::PREPEND: - default: - return $content . $separator . $markup; - } - } - } - -Notice in the above that I'm switching the default case for each; the assumption will be that labels prepend -content, and input appends. - -Now, let's create a form element that uses these: - -.. code-block:: php - :linenos: - - $element = new Zend\Form\Element('foo', array( - 'label' => 'Foo', - 'belongsTo' => 'bar', - 'value' => 'test', - 'prefixPath' => array('decorator' => array( - 'My_Decorator' => 'path/to/decorators/', - )), - 'decorators' => array( - 'SimpleInput', - 'SimpleLabel', - ), - )); - -How will this work? When we call ``render()``, the element will iterate through the various attached decorators, -calling ``render()`` on each. It will pass an empty string to the very first, and then whatever content is created -will be passed to the next, and so on: - -- Initial content is an empty string: ''. - -- '' is passed to the ``SimpleInput`` decorator, which then generates a form input that it appends to the empty - string: ****. - -- The input is then passed as content to the ``SimpleLabel`` decorator, which generates a label and prepends it to - the original content; the default separator is a ``PHP_EOL`` character, giving us this: **
-
- / - / - -
- -.. _learning.form.decorators.composite.conclusion: - -Conclusion ----------- - -Nous avons maintenant un élément qui peut rendre de multiples champs de formulaire, et les traiter comme une -seule entité -- la valeur ``dateOfBirth`` sera passée comme un tableau à l'élément et celui-ci créra les -segments de date appropriés et retournera une valeur normalisée. - -Enfin, vous avez une API uniforme pour décrire un élement se composant se plusieurs segments distincts. - - diff --git a/docs/languages/fr/tutorials/form.decorators.conclusion.rst b/docs/languages/fr/tutorials/form.decorators.conclusion.rst deleted file mode 100644 index cbfa718d9..000000000 --- a/docs/languages/fr/tutorials/form.decorators.conclusion.rst +++ /dev/null @@ -1,11 +0,0 @@ -.. EN-Revision: none -.. _learning.form.decorators.conclusion: - -Conclusion -========== - -Les décorateur de formulaire sont un système qui peut prendre du temps à maitriser. A première vue, ils -semblent complexes et rudes. Mais les différents sujets traités dans ce chapitre vous aident à comprendre leur -fonctionnement et vous montrent des manières de faire pour les utiliser efficacement dans vos formulaires. - - diff --git a/docs/languages/fr/tutorials/form.decorators.individual.rst b/docs/languages/fr/tutorials/form.decorators.individual.rst deleted file mode 100644 index 66f908a7c..000000000 --- a/docs/languages/fr/tutorials/form.decorators.individual.rst +++ /dev/null @@ -1,225 +0,0 @@ -.. EN-Revision: none -.. _learning.form.decorators.individual: - -Rendu individuel des décorateurs -================================ - -Dans la :ref:`section précédente `, nous avons vu comment combiner les -décorateurs afin de créer un rendu complexe. Ceci est très fléxible mais rajoute tout de même un part de -compléxité à l'ensemble. Dans ce chapitre, nous allons inspecter le rendu individuel des décorateurs afin de -créer du contenu visuel pour des formulaires ou des éléments. - -Une fois des décorateurs enregistrés, vous pouvez les récupérer via leur nom depuis l'élément. Revoyons -l'exemple précédent: - -.. code-block:: php - :linenos: - - $element = new Zend\Form\Element('foo', array( - 'label' => 'Foo', - 'belongsTo' => 'bar', - 'value' => 'test', - 'prefixPath' => array('decorator' => array( - 'My_Decorator' => 'path/to/decorators/', - )), - 'decorators' => array( - 'SimpleInput' - array('SimpleLabel', array('placement' => 'append')), - ), - )); - -Si nous voulons récupérer le décorateur ``SimpleInput``, nous passons par la méthode ``getDecorator()``: - -.. code-block:: php - :linenos: - - $decorator = $element->getDecorator('SimpleInput'); - echo $decorator->render(''); - -C'est simple et ça peut l'être encore plus; ré-écrivons le tout sur une seule ligne: - -.. code-block:: php - :linenos: - - echo $element->getDecorator('SimpleInput')->render(''); - -Pas mauvais, mais toujours un peu compliqué. Pour simplifier, une notation raccourcie a été introduite dans -``Zend_Form`` en 1.7: vous pouvez rendre n'importe quel décorateur enregistré en appelant une méthode de la -forme ``renderDecoratorName()``. Ceci effectue le rendu et fait en sorte que ``$content`` soit optionnel ce qui -simplifie l'utilisation: - -.. code-block:: php - :linenos: - - echo $element->renderSimpleInput(); - -C'est une simplification astucieuse, mais comment et pourquoi l'utiliser? - -Beaucoup de développeurs ont des besoins très précis en affichage des formulaires. Ils préfèrent avoir un -contrôle complet sur tout l'affichage plutôt que d'utiliser une solution automatisée qui peut s'écarter de leur -but initial. Dans d'autres cas, les formulaires peuvent demander un affichage extrêmement spécifique, en groupant -des éléments alors que d'autres doivent pouvoir être invisibles avant que l'on n'effectue telle action sur la -page, etc. - -Utilisons la possibilité de rendre un seul décorateur pour créer un affichage précis. - -D'abord, définissons un formulaire. Celui-ci récupèrera des détails démographiques sur l'utilisateur. Le rendu -sera hautement personnalisé et dans certains cas il utilisera les aides de vue directement plutôt que les -éléments. Voici une définition simple du formulaire: - -.. code-block:: php - :linenos: - - class My_Form_UserDemographics extends Zend_Form - { - public function init() - { - // Ajoute un chemin pour les décorateurs personnalisés - $this->addElementPrefixPaths(array( - 'decorator' => array('My_Decorator' => 'My/Decorator'), - )); - - $this->addElement('text', 'firstName', array( - 'label' => 'First name: ', - )); - $this->addElement('text', 'lastName', array( - 'label' => 'Last name: ', - )); - $this->addElement('text', 'title', array( - 'label' => 'Title: ', - )); - $this->addElement('text', 'dateOfBirth', array( - 'label' => 'Date of Birth (DD/MM/YYYY): ', - )); - $this->addElement('text', 'email', array( - 'label' => 'Your email address: ', - )); - $this->addElement('password', 'password', array( - 'label' => 'Password: ', - )); - $this->addElement('password', 'passwordConfirmation', array( - 'label' => 'Confirm Password: ', - )); - } - } - -.. note:: - - Nous n'utilisons pas de validateurs ou de filtres ici, car ils n'ont rien à voir avec le rendu visuel qui nous - interesse. En réalité, il y en aurait. - -Maintenant réfléchissons au rendu visuel du formulaire. Une communalité concernant les nom et prénom est qu'on -les affiche l'un à coté de l'autre, à coté de leur titre, si présent. Les dates, si elles n'utilisent pas -Javascript, affichent souvent des champs séparés pour chaque segment de la date. - -Utilisons la possibilité de rendre des décorateurs un par un pour accomplir notre tâche. D'abord, notez qu'aucun -décorateur spécifique n'a été renseigné dans les éléments. Rappelons donc les décorateurs par défaut de la -plupart des éléments: - -- ``ViewHelper``: utilise une aide de vue pour rendre l'élément balise de formulaire à proprement parlé. - -- ``Errors``: utilise l'aide de vue ``FormErrors`` pour afficher les erreurs de validation éventuelles. - -- ``Description``: utilise l'aide de vue ``FormNote`` afin de rendre la description éventuelle de l'élément. - -- ``HtmlTag``: encapsule les trois objets ci-dessus dans un tag **
**. - -- ``Label``: rend l'intitulé de l'élément en utilisant l'aide de vue ``FormLabel`` (et en encapsulant le tout - dans un tag **
**). - -Nous vous rappelons aussi que vous pouvez accéder à tout élément individuellement en tant qu'attribut du -formulaire représentant son nom. - -Notre script de vue ressemblerait à cela: - -.. code-block:: php - :linenos: - - form; - // Enlève le
depuis l'intitulé - foreach ($form->getElements() as $element) { - $element->getDecorator('label')->setOption('tag', null); - } - ?> -
-
- title->renderLabel() - . $form->title->renderViewHelper() ?> - firstName->renderLabel() - . $form->firstName->renderViewHelper() ?> - lastName->renderLabel() - . $form->lastName->renderViewHelper() ?> -
-
- dateOfBirth->renderLabel() ?> - formText('dateOfBirth[day]', '', array( - 'size' => 2, 'maxlength' => 2)) ?> - / - formText('dateOfBirth[month]', '', array( - 'size' => 2, 'maxlength' => 2)) ?> - / - formText('dateOfBirth[year]', '', array( - 'size' => 4, 'maxlength' => 4)) ?> -
-
- password->renderLabel() - . $form->password->renderViewHelper() ?> -
-
- passwordConfirmation->renderLabel() - . $form->passwordConfirmation->renderViewHelper() ?> -
- formSubmit('submit', 'Save') ?> -
- -Si vous utilisez le script ci-dessus, vous verrez un code HTML ressemblant à ceci: - -.. code-block:: html - :linenos: - -
-
- - - - - - - - -
- -
- - - / - - / - -
- -
- - -
- -
-
*. - -- ``Label``\  : rend l'intitulé de l'élément en utilisant l'aide de vue ``FormLabel`` (et en encapsulant le - tout dans un tag *
*). - -Notez bien que chaque décorateur n'a qu'une petite tâche particulière et opère sur une partie spécifique des -données de l'élément auquel il est rattaché, le décorateur ``Errors`` récupère les messages de validation de -l'élément et effectue leur rendu, le décorateur ``Label`` rend simplement le libellé. Ceci fait que chaque -décorateur est très petit, réutilisable, et surtout testable. - -Cet argument ``$content`` vient de là aussi : chaque décorateur travaille avec sa méthode ``render()`` sur un -contenu (généralement généré par le décorateur immédiatement précédent dans la pile globale) et embellit -ce contenu en lui rajoutant ou en lui faisant précéder des informations. Il peut aussi remplacer totalement son -contenu. - -Ainsi, pensez au mécanisme des décorateurs comme la conception d'un oignon de l'intérieur vers l'extérieur. - -Voyons voir un exemple, le même que celui :ref:`de la section précédente `\ - : - -.. code-block:: php - :linenos: - - class My_Decorator_SimpleInput extends Zend\Form\Decorator\Abstract - { - protected $_format = '' - . ''; - - public function render($content) - { - $element = $this->getElement(); - $name = htmlentities($element->getFullyQualifiedName()); - $label = htmlentities($element->getLabel()); - $id = htmlentities($element->getId()); - $value = htmlentities($element->getValue()); - - $markup = sprintf($this->_format, $id, $label, $id, $name, $value); - return $markup; - } - } - -Supprimons la fonctionnalité libellé (label) et créons un décorateur spécifique pour lui. - -.. code-block:: php - :linenos: - - class My_Decorator_SimpleInput extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $name = htmlentities($element->getFullyQualifiedName()); - $id = htmlentities($element->getId()); - $value = htmlentities($element->getValue()); - - $markup = sprintf($this->_format, $id, $name, $value); - return $markup; - } - } - - class My_Decorator_SimpleLabel extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $id = htmlentities($element->getId()); - $label = htmlentities($element->getLabel()); - - $markup = sprint($this->_format, $id, $label); - return $markup; - } - } - -Ok, ca semble bon mais il y a un problème : le dernier décorateur va l'emporter. Vous allez vous retrouver avec -comme seul rendu, celui du dernier décorateur. - -Pour faire fonctionner le tout comme il se doit, concaténez simplement le contenu précédent ``$content`` avec le -contenu généré : - -.. code-block:: php - :linenos: - - return $content . $markup; - -Le problème avec cette approche est que vous ne pouvez pas choisir où se place le contenu du décorateur en -question. Heureusement, un mécanisme standard existe ; ``Zend\Form\Decorator\Abstract`` possède le concept de -place et définit des constantes pour le régler. Aussi, il permet de préciser un séparateur à placer entre les -2. Voyons celà : - -.. code-block:: php - :linenos: - - class My_Decorator_SimpleInput extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $name = htmlentities($element->getFullyQualifiedName()); - $id = htmlentities($element->getId()); - $value = htmlentities($element->getValue()); - - $markup = sprintf($this->_format, $id, $name, $value); - - $placement = $this->getPlacement(); - $separator = $this->getSeparator(); - switch ($placement) { - case self::PREPEND: - return $markup . $separator . $content; - case self::APPEND: - default: - return $content . $separator . $markup; - } - } - } - - class My_Decorator_SimpleLabel extends Zend\Form\Decorator\Abstract - { - protected $_format = ''; - - public function render($content) - { - $element = $this->getElement(); - $id = htmlentities($element->getId()); - $label = htmlentities($element->getLabel()); - - $markup = sprintf($this->_format, $id, $label); - - $placement = $this->getPlacement(); - $separator = $this->getSeparator(); - switch ($placement) { - case self::APPEND: - return $markup . $separator . $content; - case self::PREPEND: - default: - return $content . $separator . $markup; - } - } - } - -Notez que dans l'exemple ci-dessus, nous intervertissons les comportements par défaut avec append et prepend. - -Créons dès lors un élément de formulaire qui va utiliser tout celà : - -.. code-block:: php - :linenos: - - $element = new Zend\Form\Element('foo', array( - 'label' => 'Foo', - 'belongsTo' => 'bar', - 'value' => 'test', - 'prefixPath' => array('decorator' => array( - 'My_Decorator' => 'path/to/decorators/', - )), - 'decorators' => array( - 'SimpleInput', - 'SimpleLabel', - ), - )); - -Comment ça fonctionne ? et bien nous appelons ``render()``, l'élément va alors commencer une itération sur -tous ses décorateurs, en appelant ``render()`` sur chacun. Il va passer une chaîne vide comme contenu pour le -premier décorateur, et le rendu de chaque décorateur va servir de contenu pour le suivant, ainsi de suite : - -- Contenu initial : chaîne vide: ''. - -- Chaîne vide ('') est passée au décorateur ``SimpleInput``, qui génère un tag de formulaire de type input - qu'il ajoute à la chaîne vide : ****. - -- Ce contenu généré est alors passé comme contenu original pour le décorateur ``SimpleLabel`` qui génère un - libellé et le place avant le contenu original avec comme séparateur ``PHP_EOL``, ce qui donne : **