Elementos Enviados en el Formulario Estandard de Zend Framework Zend Framework viene con clases de elementos concretos cubriendo la mayoría de los elementos de los formularios HTML. La mayoría simplemente especifica una vista de ayuda para usar cuando se decora el elemento, pero varios ofrecen funcionalidad adicional. La siguiente es una lista de todas las clases, así como también una descripción de la funcionalidad que ofrecen. Zend_Form_Element_Button Usada para crear elementos HTML de tipo button, Zend_Form_Element_Button extiende Zend_Form_Element_Submit, derivandi sy funcionalidad personalizada. It specifies the 'formButton' view helper for decoration. Like the submit element, it uses the element's label as the element value for display purposes; in other words, to set the text of the button, set the value of the element. The label will be translated if a translation adapter is present. Because the label is used as part of the element, the button element uses only the ViewHelper and DtDdWrapper decorators. Después de llenar o validar un formulario, se puede verificar si el botón dado fue pulsado usando el método isChecked(). Zend_Form_Element_Captcha Los CAPTCHAs son usados para prevenir el envio automático de formularios por los robots y otros procesos automatizados. The Captcha form element allows you to specify which Zend_Captcha adapter you wish to utilize as a form captcha. It then sets this adapter as a validator to the object, and uses a Captcha decorator for rendering (which proxies to the captcha adapter). Adapters may be any adapters in Zend_Captcha, as well as any custom adapters you may have defined elsewhere. To allow this, you may pass an additional plugin loader type key, 'CAPTCHA' or 'captcha', when specifying a plugin loader prefix path: addPrefixPath('My_Captcha', 'My/Captcha/', 'captcha'); ]]> Los Captcha entonces pueden ser cargados usando el método setCaptcha(), el cual puede tomar una instancia cualquiera de captcha instance, o el nombre corto del adaptador captcha: setCaptcha(new Zend_Captcha_Figlet()); // Usando nombre corto: $element->setCaptcha('Dumb'); ]]> Si desea cargar sus elementos configuración, especifique la clave 'captcha' con un array conteniendo la clave 'captcha', o ambas claves 'captcha' y 'captchaOptions': "Please verify you're a human", 'captcha' => array( 'captcha' => 'Figlet', 'wordLen' => 6, 'timeout' => 300, ), )); // Usindo captcha y captchaOptions: $element = new Zend_Form_Element_Captcha('foo', array( 'label' => "Please verify you're a human" 'captcha' => 'Figlet', 'captchaOptions' => array( 'captcha' => 'Figlet', 'wordLen' => 6, 'timeout' => 300, ), )); ]]> El decorador usado es determinado consultando el adaptador captcha. Por defecto, es usado el Captcha decorator, pero un adaptador puede especificar uno diferente vía su métodogetDecorator(). Como ha notado, el adaptador captcha actúa él mismo como un validador para el elemento. Adicionalmente, el validador NotEmpty no es usado y el elemento es marcado como requerido. En la mayoría de los casos, usted no necesitará hacer nada más para tener un captcha presente en su formulario. Zend_Form_Element_Checkbox Las casillas de verificación (checkboxes) HTML le permiten devolver un valor específico, pero básicamente funcionan como los booleanos: cuando está marcada, el valor es enviado; cuando no está marcada, no se envía nada. Internamente, Zend_Form_Element_Checkbox fuerza este estado. Por defecto, si la casilla (checkbox) está marcada su valor es '1', y si no está marcada su valor es '0'. You can specify the values to use using the setCheckedValue() and setUncheckedValue() accessors, respectively. Internally, any time you set the value, if the provided value matches the checked value, then it is set, but any other value causes the unchecked value to be set. Additionally, setting the value sets the checked property of the checkbox. You can query this using isChecked() or simply accessing the property. Using the setChecked($flag) method will both set the state of the flag as well as set the appropriate checked or unchecked value in the element. Please use this method when setting the checked state of a checkbox element to ensure the value is set properly. Zend_Form_Element_Checkbox uses the 'formCheckbox' view helper. The checked value is always used to populate it. Zend_Form_Element_File The File form element provides a mechanism for supplying file upload fields to your form. It utilizes Zend_File_Transfer internally to provide this functionality, and the FormFile view helper as also the File decorator to display the form element. By default, it uses the Http transfer adapter, which introspects the $_FILES array and allows you to attach validators and filters. Validators and filters attached to the form element will be attached to the transfer adapter. File form element usage The above explanation of using the File form element may seem arcane, but actual usage is relatively trivial: setLabel('Upload an image:') ->setDestination('/var/www/upload'); // ensure only 1 file $element->addValidator('Count', false, 1); // limit to 100K $element->addValidator('Size', false, 102400); // only JPEG, PNG, and GIFs $element->addValidator('Extension', false, 'jpg,png,gif'); $form->addElement($element, 'foo'); ]]> También debe asegurarse de que se ha provisto un tipo de codificación corecto al formulario; se debe utilizar 'multipart/form-data'. Se puede hacer esto estableciendo el atributo 'enctype' en el formulario: setAttrib('enctype', 'multipart/form-data'); ]]> Cuando el atributo ha sido validado exitosamente, usted debe recibir el archivo para almacenarlo en el destino final usando receive(). Adicionalmente, puede determinar la ubicación final usando getFileName(): isValid) { print "Ohoh... validation error"; } if (!$form->foo->receive()) { print "Error receiving the file"; } $location = $form->foo->getFileName(); ]]> Ubicaciones Predeterminadas para la Carga de Archivos Por defecto, los archivos son cargados al directorio temp del sistema. Valores de archivo Dentro de HTTP, un elemento file no tiene valor. Por tanto y a causa de razones de seguridad usted solo obtendrá el nombre del archivo cargado llamando a getValue() y no el destino completo. si usted necesita la información completa llame a getFileName() y le devolverá el destino y nombre de archivo completo. Zend_Form_Element_File soporta también archivos múltiples. Para llamar el método setMultiFile($count) usted puede establecer la cantidad de elementos file que usted desea crear. Esto le previene de establecer la misma configuración varias veces. Configuración de múltiples archivos Crear un elemento multi archivo es lo mismo que querer configurar un elemento único. Sólo tiene que llamar a setMultiFile() adicionalmente después de la creación: setLabel('Upload an image:') ->setDestination('/var/www/upload'); // asegura mínimo 1, maximo 3 archivos $element->addValidator('Count', false, array('min' => 1, 'max' => 3)); // limita a 100K $element->addValidator('Size', false, 102400); // solo JPEG, PNG, y GIFs $element->addValidator('Extension', false, 'jpg,png,gif'); // define 3 elementos file idénticos $element->setMultiFile(3); $form->addElement($element, 'foo'); ]]> En su vista usted ahora obtendrá 3 elementos para carga de archivos idénticos los cuales comparten la misma configuración. Para obtener el conjunto del número de archivos múltiples simplemente llame a getMultiFile(). Elementos File en Subformularioss Cuando usted use elementos file en subformularios debería establecer nombres únicos. Así, cuando usted nombre su elemento file en el subformulario1, debe darle un nombre diferente en el subformulario2. Tan pronto como haya dos elementos file nombrados de forma idéntica, el segundo elemento no se mostrará o enviará. Para limitar el tamaño del archivo, el cual es cargado por el cliente, debe establecer el tamaño máximo de archivo que el formulario acepta . Esto limitará el tamaño del archivo en el lado del cliente configurando la opción MAX_FILE_SIZE en el formulario. Tan pronto como establezca este valor usando el método setMaxFileSize($size), será generado con el elemento file. setLabel('Upload an image:') ->setDestination('/var/www/upload') ->addValidator('Size', false, 102400) // límite en 100K ->setMaxFileSize(102400); // limita el tamaño del archivo en el lado del cliente $form->addElement($element, 'foo'); ]]> MaxFileSize con elementos file múltiples Cuando usted usa elementos file múltiples en los formularios tiene que establecer el MAX_FILE_SIZE una sola vez. Establecerlo otra vez sobreescribirá el valor previamente establecido. Note que usted puede establecer MAX_FILE_SIZE una sola vez, incluso si usa múltiples formularios. Zend_Form_Element_Hidden Los elementos Hidden simplemente inyectan datos que deben ser enviados, pero que el usuario no debe manipular. Zend_Form_Element_Hidden logra esto a través del uso del helper de vista 'formHidden'. Zend_Form_Element_Hash Este elemento provee protección de ataques desde CSRF sobre formularios, asegurando que el dato es enviado por la sesión del usuario que generó el formulario y no por un script malicioso. La protección se logra mediante la adición de un elemento hash a un formulario y verificandolo cuando el formulario es enviado. El nombre del elemento hash debe ser único. Se recomienda usar la opción salt para el elemento, dos hashes con el mismo nombre y diferentes salts no chocan: addElement('hash', 'no_csrf_foo', array('salt' => 'unique')); ]]> Puede establecer el salt más tarde usando el método setSalt($salt). Internamente, el elemento almacena un identificador único usando Zend_Session_Namespace, y lo comprueba en el momento que se envía (comprueba que el TTL no ha espirado). El validador 'Identical' entonces es usado para asegurarse que el hash enviado marcha con el hash alamacenado. El helper de vista 'formHidden' es usado para generar el elemento en el formulario. Zend_Form_Element_Image Las imágenes pueden ser usadas como elementos de formulario, y le permiten especificar elementos gráficos como botones de formulario. Los elementos Image necesitan una imagen fuente. Zend_Form_Element_Image le permite especificar esto usando el método de acceso setImage() (o clave de configuración 'image'). Opcionalmente, también puede especificar un valor para utilizar al momento de enviar la imagen utilizando el método de acceso setImageValue() (o clave de configuración 'imageValue'). Cuando el valor establecido para el elemento sea igual a imageValue, entonces el método de acceso isChecked() devolverá true. Los elementos Image usan el Decorador de Imagen para generar (así como el estandard Errors, HtmlTag, y decorador Label). Opcionalmente, puede especificar una etiqueta para el decorador Image que luego envuelva al elemento imagen. Zend_Form_Element_MultiCheckbox En ocasiones, se tiene un conjunto de checkboxes, y se desea agrupar los resultados. Esto es como un Multiselect, pero en lugar de estar en una lista desplegable, necesita mostrarlos en pares checkbox/value (casilla de verificación/valor). Zend_Form_Element_MultiCheckbox hace esto sencillo. Like all other elements extending the base Multi element, you can specify a list of options, and easily validate against that same list. The 'formMultiCheckbox' view helper ensures that these are returned as an array in the form submission. By default, this element registers an InArray validator which validates against the array keys of registered options. You can disable this behavior by either calling setRegisterInArrayValidator(false), or by passing a false value to the registerInArrayValidator configuration key. You may manipulate the various checkbox options using the following methods: addMultiOption($option, $value) addMultiOptions(array $options) setMultiOptions(array $options) (overwrites existing options) getMultiOption($option) getMultiOptions() removeMultiOption($option) clearMultiOptions() To mark checked items, you need to pass an array of values to setValue(). The following will check the values "bar" and "bat": array( 'foo' => 'Foo Option', 'bar' => 'Bar Option', 'baz' => 'Baz Option', 'bat' => 'Bat Option', ); )); $element->setValue(array('bar', 'bat')); ]]> Note that even when setting a single value, you must pass an array. Zend_Form_Element_Multiselect XHTML select elements allow a 'multiple' attribute, indicating multiple options may be selected for submission, instead of the usual one. Zend_Form_Element_Multiselect extends Zend_Form_Element_Select, and sets the multiple attribute to 'multiple'. Like other classes that inherit from the base Zend_Form_Element_Multi class, you can manipulate the options for the select using: addMultiOption($option, $value) addMultiOptions(array $options) setMultiOptions(array $options) (overwrites existing options) getMultiOption($option) getMultiOptions() removeMultiOption($option) clearMultiOptions() If a translation adapter is registered with the form and/or element, option values will be translated for display purposes. By default, this element registers an InArray validator which validates against the array keys of registered options. You can disable this behavior by either calling setRegisterInArrayValidator(false), or by passing a false value to the registerInArrayValidator configuration key. Zend_Form_Element_Password Password elements are basically normal text elements -- except that you typically do not want the submitted password displayed in error messages or the element itself when the form is re-displayed. Zend_Form_Element_Password achieves this by calling setObscureValue(true) on each validator (ensuring that the password is obscured in validation error messages), and using the 'formPassword' view helper (which does not display the value passed to it). Zend_Form_Element_Radio Radio elements allow you to specify several options, of which you need a single value returned. Zend_Form_Element_Radio extends the base Zend_Form_Element_Multi class, allowing you to specify a number of options, and then uses the formRadio view helper to display these. By default, this element registers an InArray validator which validates against the array keys of registered options. You can disable this behavior by either calling setRegisterInArrayValidator(false), or by passing a false value to the registerInArrayValidator configuration key. Like all elements extending the Multi element base class, the following methods may be used to manipulate the radio options displayed: addMultiOption($option, $value) addMultiOptions(array $options) setMultiOptions(array $options) (overwrites existing options) getMultiOption($option) getMultiOptions() removeMultiOption($option) clearMultiOptions() Zend_Form_Element_Reset Reset buttons are typically used to clear a form, and are not part of submitted data. However, as they serve a purpose in the display, they are included in the standard elements. Zend_Form_Element_Reset extends Zend_Form_Element_Submit. As such, the label is used for the button display, and will be translated if a translation adapter is present. It utilizes only the 'ViewHelper' and 'DtDdWrapper' decorators, as there should never be error messages for such elements, nor will a label be necessary. Zend_Form_Element_Select Select boxes are a common way of limiting to specific choices for a given form datum. Zend_Form_Element_Select allows you to generate these quickly and easily. By default, this element registers an InArray validator which validates against the array keys of registered options. You can disable this behavior by either calling setRegisterInArrayValidator(false), or by passing a false value to the registerInArrayValidator configuration key. As it extends the base Multi element, the following methods may be used to manipulate the select options: addMultiOption($option, $value) addMultiOptions(array $options) setMultiOptions(array $options) (overwrites existing options) getMultiOption($option) getMultiOptions() removeMultiOption($option) clearMultiOptions() Zend_Form_Element_Select uses the 'formSelect' view helper for decoration. Zend_Form_Element_Submit Submit buttons are used to submit a form. You may use multiple submit buttons; you can use the button used to submit the form to decide what action to take with the data submitted. Zend_Form_Element_Submit makes this decisioning easy, by adding a isChecked() method; as only one button element will be submitted by the form, after populating or validating the form, you can call this method on each submit button to determine which one was used. Zend_Form_Element_Submit uses the label as the "value" of the submit button, translating it if a translation adapter is present. isChecked() checks the submitted value against the label in order to determine if the button was used. The ViewHelper and DtDdWrapper decorators to render the element. No label decorator is used, as the button label is used when rendering the element; also, typically, you will not associate errors with a submit element. Zend_Form_Element_Text By far the most prevalent type of form element is the text element, allowing for limited text entry; it's an ideal element for most data entry. Zend_Form_Element_Text simply uses the 'formText' view helper to display the element. Zend_Form_Element_Textarea Textareas are used when large quantities of text are expected, and place no limits on the amount of text submitted (other than maximum size limits as dictated by your server or PHP). Zend_Form_Element_Textarea uses the 'textArea' view helper to display such elements, placing the value as the content of the element.