Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "form link"

Using a link to submit a form or button to link

For ergonomic and graphism reasons, I sometimes prefer to use link rather than buttons and/or button rather than links...

To do so, I created this small function :

<?php
# File : JsHelper.php
 
// use of "normal" Javascript Helper
use_helper('Javascript');
 
 
/*!
 * Create a link that submit the closest parent form
 *
 * @param $string    string : text to display
 * @param $options mixed : options to be pass to the tag
 * @return string                : HTML code for the link
 */
function link_to_submit( $string, $options = null )
{
  $func = ";var a=this.ancestors();for(var i in a){if(a[i].tagName=='FORM'){try{a[i].onsubmit();} catch(err){a[i].submit();}break;}}";
  return link_to_function( $string, $func, $options );
}
 
 
 
/*!
 * Create a button that act as a link
 *
 * @param $string    string : text to display in the button
 * @param $url         string : URL of the link
 * @param $options mixed : options to be pass to the tag
 * @return string                : HTML code for the link
 */
function button_to_link( $string, $url, $options = null )
{
  $url = url_for($url);
 
  $func = ";document.location = '$url';return false;";
  if ( is_string($options) ) $options.= " onclick=$func";
  else $options['onclick'] = $func;
 
  return tag('button', $options ).htmlspecialchars($string).'</button>';
}
 

Then, you simply use it as a normal link_to function :

<? use_helper('Js') ?>
 
<?=form_tag('module/action')?>
  <?=input_tag('text')?>
  <?=link_to_submit('Validate')?>
  <?=link_to('Cancel','module/index')?>
</form>
 

Or :

<? use_helper('Js') ?>
 
<?=form_tag('module/action')?>
  <?=input_tag('text')?>
  <?=submit_tag('Validate')?>
  <?=button_to_link('Cancel','module/index')?>
</form>
 

In these two examples, links/buttons of the form are graphicly consistents. For a better user experience ;)

PS : works as well with AJAX forms form_remote_tag()

PPS : Don't forget that thanks to CSS, you can make a button looking like a link (et vice-versa).

PPPS : Don't forget that buttons and links doesn't have the same meaning for search engine bots.

PPPPS : Don't forget that this rely on the fact that user is using javascript!!!

by jugjug on 2008-03-26, tagged form  javascript  link  submit 
(2 comments)