OxyScripts.com
Menu spacer Home Tutorials Articles Code Forums irc.freenode.net #oxyscripts
Main (PHP)
Home Forums PHP News PHP Tutorials Articles PHP Code Snippets Contact Us Sysadmin Resources Books Template Shop
3rd Party Streams
SlashDot PHPDeveloper.org PHP.Net
Resources
PHP Manual MySQL Manual Smarty Manual PEAR Manual PHP-GTK Manual Symfony Manual
Code Snippets
Authentication Database Graphics HTTP Miscellaneous Time/Date
Affiliates
Scripts TutorialMan TutorialGuide CodingForums.com PHP Scripts Cheap Web Hosting Affordable Web Hosting Dreamweaver Templates

Search This Site :     PHP Function Reference :
 

Templating in practice : Form helpers

Overview

Symfony provides form helpers to avoid repeating code in templates that contain forms, especially when the default value is linked to the application Model.

Introduction

In templates, HTML tags of form elements are very often mixed with PHP code. Form helpers in symfony aim to simplify this task and to avoid opening <?php echo tags in the middle of an element tag. They also duplicate the name attribute to define the id value.

In addition, if form controls are linked to objects in your data model, symfony can automate the hassle of defining a default value or listing the possible values.

Symfony also provides helpers for form validation. A detailed presentation of this feature can be found in the form validation chapter.

Main form tag

Some helpers are here to facilitate the writing of form tags, especially since they are often mixed with php code.

To create a form, you have to use the symfony form_tag function since it transforms the action given as a parameter into a routed URL:

<?php echo form_tag('test/save') ?>
// will generate in HTML
<form method="post" action="http://www.mysite.com/index.php/test/save">

This will route the form to the save action of the test module. You can learn more about the URL management in the routing chapter.

To change the default method, the default enctype or to specify other attributes, use the second argument:

// options argument with the associative array syntax
<?php echo form_tag('test/save', Array('multipart' => true, 'id' => 'myForm')) ?>
// will generate in HTML
<form method="post" enctype="multipart/form-data" id="myForm" action="http://www.mysite.com/index.php/test/save">
 
// options argument with the string syntax
<?php echo form_tag('test/save', 'method=get class=simpleForm') ?>
// will generate in HTML
<form method="get" class="simpleForm" action="http://www.mysite.com/index.php/test/save">

As there is no need for a closing form helper, you should use the HTML </form> tag, even if it doesn't look good in your source code.

Standard form elements

Each element in a form will have by default an id attribute equal to its name attribute. You can specify custom attributes by adding a last argument, using the associative array syntax or the string syntax.

Here are the standard form element helpers:

  • text field (input):

    <?php echo input_tag('name', 'default value') ?>
    // will generate in HTML
    <input type="text" name="name" id="name" value="default value" />
  • long text field (textarea):

    <?php echo textarea_tag('name', 'default content', 'size=10x20') ?>
    // will generate in HTML
    <textarea name="name" id="name" rows="20" cols="10">default content</textarea>
  • checkbox:

    <?php echo checkbox_tag('married', '1', true) ?>
    <?php echo checkbox_tag('driverslicence', 'B', false) ?>
    // will generate in HTML
    <input type="checkbox" name="married" id="married" value="1" checked="checked" />
    <input type="checkbox" name="driverslicence" id="driverslicence" value="B" />
  • radio button:

    <?php echo radiobutton_tag('status[]', 'value1', true) ?>
    <?php echo radiobutton_tag('status[]', 'value2', false) ?>
    // will generate in HTML
    <input type="radio" name="status[]" id="status_value1" value="value1" checked="checked" />
    <input type="radio" name="status[]" id="status_value2" value="value2" />
  • value selection field (select):

    <?php echo select_tag('name', options_for_select(Array('0' => 'Steve', '1' => 'Bob', '2' => 'Albert', '3' => 'Ian', '4' => 'Buck'), 3)) ?>
    // will generate in HTML
    <select name="name" id="name">
      <option value="0">Steve</option>
      <option value="1">Bob</option>
      <option value="2">Albert</option>
      <option value="3" selected="selected">Ian</option>
      <option value="4">Buck</option>
    </select>

    When the value is the same as the text to display, use an array instead of an associative array

    <?php echo select_tag('payment', options_for_select(Array('Visa', 'Eurocard', 'Mastercard'), 'Visa')) ?>
    // will generate in HTML
    <select name="payment" id="payment">
      <option selected="selected">Visa</option>
      <option>Eurocard</option>
      <option>Mastercard</option>
    </select>

    Multiple selection field uses the same syntax, and the selected values can then be an array

    <?php echo select_tag('payment', options_for_select(Array('Visa', 'Eurocard', 'Mastercard'), Array('Visa', 'Mastecard')), 'multiple=multiple') ?>
    // will generate in HTML
    <select name="payment" id="payment" multiple="multiple">
      <option selected="selected">Visa</option>
      <option>Eurocard</option>
      <option selected="selected">Mastercard</option>
    </select>

    When the data needed to set the value and the text to display can be obtained via methods of an object, you can simply pass an array of the objects, and the names of the methods to use to retrieve the value and display text.

    <?php echo select_tag('articles', objects_for_select($articles, 'getId', 'getTitle', 1) ) ?>

    This will iterate through the $articles array, using the current object by calling the getId() method for the value, and getTitle() for the display text.

  • field to upload a file:

    <?php echo input_file_tag('name') ?>
    // will generate in HTML
    <input type="file" name="name" id="name" value="" />
  • field to enter a password:

    <?php echo input_password_tag('name', 'value') ?>
    // will generate in HTML
    <input type="password" name="name" id="name" value="value" />
  • hidden field:

    <?php echo input_hidden_tag('name', 'value') ?>
    // will generate in HTML
    <input type="hidden" name="name" id="name" value="value" />
  • submit button (as text):

    <?php echo submit_tag('Save') ?>
    // will generate in HTML
    <input type="submit" name="submit" value="Save" />
  • submit button (as image):

    <?php echo submit_image_tag('submit_img') ?>
    // will generate in HTML
    <input type="image" name="submit" src="/images/submit_img.png" />

This last helper uses the same syntax and has the same advantages as the image_tag helper, described in the link helpers chapter.

Rich form elements

Dates

Forms are often used to get dates. Date format is also culture dependent, and wrong dates is the main reason for form validation failures. The input_date_tag can assists the user with a javascript calendar:

<?php echo input_date_tag('dateofbirth', '2005-05-03', 'rich=true') ?>
// will generate in HTML
// a text input tag together with a calendar widget

The last argument specifies that the rich form has to be used. If it was set to false (which is the default value), the normal date entry widget (three text inputs for day, month and year) would be used in place.

The accepted date values are the ones recognized by the strtotime() php function. Beware that, in some limit cases, the results can be surprising:

// Can be used

// work fine
<?php echo input_date_tag('test', '2006-04-01', 'rich=true') ?>
<?php echo input_date_tag('test', 1143884373, 'rich=true') ?>
<?php echo input_date_tag('test', 'now', 'rich=true') ?>
<?php echo input_date_tag('test', '23 October 2005', 'rich=true') ?>
<?php echo input_date_tag('test', 'next tuesday', 'rich=true') ?>
<?php echo input_date_tag('test', '1 week 2 days 4 hours 2 seconds', 'rich=true') ?>
// returns NULL
<?php echo input_date_tag('test', null, 'rich=true') ?>
<?php echo input_date_tag('test', '', 'rich=true') ?>

// Not to be used

// date zero = 01/01/1970
<?php echo input_date_tag('test', 0, 'rich=true') ?>
// non-English date formats don't work
<?php echo input_date_tag('test', '01/04/2006', 'rich=true') ?>

Rich text

Rich text editing in a textarea is also possible, since symfony provides an interface with the TinyMCE widget that inputs html code.

In order to use TinyMCE, you have to download it first from this page and unpack it in a temporary folder. Copy the tinymce/jscripts/tiny_mce directory into your project web/js/ directory, and add to your settings.yml:

all:
  .settings:      
    rich_text_js_dir:  js/tiny_mce

Now you can run the rich version of the textarea input tag:

<?php echo textarea_tag('name', 'default content', 'rich=true size=10x20')) ?>
// will generate in HTML
// a rich text edit zone powered by TinyMCE

If you want to specify custom options for TinyMCE, use the tinymce_options option:

<?php echo textarea_tag('name', 'default content', 'rich=true size=10x20 tinymce_options=language:"fr",theme_advanced_buttons2:"separator"')) ?>

Country

You will probably need to display a country selection field. The select_country_tag helper can do it for you; it uses the default culture to choose in which language the countries will be displayed.

<?php echo select_country_tag('country', 'Albania') ?>
// will generate in HTML
<select name="country" id="country">
  <option>Afghanistan</option>
  <option selected="selected">Albania</option>
  <option>Algeria</option>
  <option>American Samoa</option>
  <option>Andorra</option>
  ...

Form helpers for objects

In many cases form elements are linked to fields in a database table. As you use an object-relational mapping, the form elements are actually linked to attribute accessors and setters. Symfony provides an alternate version to all the previous helpers, where the $value argument - which defines the default value - is replaced by two arguments, $object and $method. The method must be the attribute accessor of the object. The method name is also given to the name and id attributes of the generated HTML tag, so the first argument is suppressed.

The simple text input tag now looks like:

<?php echo object_input_tag($customer, 'getTelephone') ?>
// will generate in HTML
<input type="text" name="getTelephone" id="getTelephone" value="0123456789" />

...provided that $customer->getTelephone() = '0123456789'.

So simply add the object_ prefix in front of the name of the form helpers to get the name of the related object form helper:

object_input_tag($object, $method, $options)
object_textarea_tag($object, $method, $options)
object_checkbox_tag($object, $method, $options)
...

Note: Contrary to the regular for helpers, the object form helpers are only available if you declare explicitly the use of the Object helper in your template:

<?php echo use_helper('Object') ?>

The most useful helper of this type is the object_select_tag, since it can get the list of values from another table. For instance, imagine that you have an Article and an Author table, where one or more articles are written by one author. This means that the Article table has a author_id column:

Article Author
id id
author_id name
title

Now, picture a form built to edit the data of an article. There is an easy way to get the list of the author names when editing the AuthorId column:

object_select_tag($article, 'getAuthorId', 'related_class=Author')

Symfony will use the ->toString() method of the Author class to display the names of the authors in a list. If the method is undefined, the primary key (in the example, the id column) of the Author table is used instead.

By default, the list of authors will be the complete list ordered by creation date, but you can specify another AuthorPeer method to display a custom array of authors, in the order you want, with the peer_method parameter:

object_select_tag($article, 'getAuthorId', 'related_class=Author peer_method=getFamousAuthorsOrderedByBirthDate')

A few other options can define the content of an object select tag. include_title and include_blank allow to add a title or a first empty line to the list:

object_select_tag($article, 'getAuthorId', 'related_class=Author')
object_select_tag($article, 'getAuthorId', 'related_class=Author include_blank=true')
object_select_tag($article, 'getAuthorId', 'related_class=Author include_title=true')
//will display three selects with lists of values looking like:
-------      -------      -------
|Steve |     |      |     |Author|
|John  |     |Steve |     |Steve |
|Mark  |     |John  |     |John  |
-------      |Mark  |     |Mark  |
             -------      -------

Note: the object_select_tag helper uses the Propel layer; it might not work if you use another data abstraction layer.

Easy object update

The object relational mapping given by Propel allows you to easily modify a record in a table from a form if the fields of the forms are properly named.

For instance, if you have an object Author with attributes name, age and address, and that you created a template looking like:

<?php echo form_tag('author/update') ?>
Name : <?php echo object_input_tag($author, 'getName') ?><br />
Age : <?php echo object_input_tag($author, 'getAge') ?><br />
Address:<br />
<?php echo object_textarea_tag($author, 'getAddress') ?>
</form>

Then the update action of the author module can simply use the fromArray modifier:

public function executeUpdate ()
{
  $author = AuthorPeer::retrieveByPk($this->getRequestParameter('id'));
 
  $this->forward404Unless($author instanceof Author);
 
  $author->fromArray($this->getRequest()->getParameterHolder()->getAll(), Author::TYPE_FIELDNAME);
  $author->save();
 
  return $this->redirect('/author/show?id='.$author->getId());
}
 
   Print this page

Top Sponsor
Symantec\'s Norton SystemWorks 2006
Sponsors
CA
Sponsors
AdWords Dominator 125*125
Advertisting

Affiliates
VertexTemplates PHPFreaks CodeWalkers StarGeek DevScripts CGI & PHP Scripts PHP CMS

Shopping Rebates   Sell It 4 You   Flash Page Counters   Get Insured
GPS Tracking Service   Charity Donate Info   Web Site Hosting   VOIP Service

Privacy Policy | Links | Site Map | Advertising

All content on OxyScripts.com is (©)2002-2007

 
Powered by Adrastea - Version 1.0.0. Copyright © Rune Solutions, 2004-2005