Skip to content
eliasdorneles edited this page Aug 3, 2012 · 5 revisions

Purpose

The idea is simple (and copied from Rails): it is a helper that creates a post form with a submit button. Optionally, it can have input hiddens as a array in the last parameter.

It has great value in lists of records that have options that are not "elegant" send them as get parameters.

Usage

<!-- Simple button -->
<?php echo button_to('Button value' , 'controller/action' ,
             array('hidden_name' => 'value' )) ?>

<!-- Personalized -->
<?php echo button_to( array('value' => 'Button value', 'class' => 'css Class') ,
             'controller/action', array('hidden_name' => 'value' )) ?>

Helper code:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Creates a post form with a submit button.
 *
* @access   public
* @param    mixed    button's value or array with html configuration
* @param    string    (module/)controller/action to post. 
* @param    string    associative array (hash) with key equals to hidden field's name
                      and value equals to hidden's value.
* @return   string
*/

if ( ! function_exists('button_to')) {
    function button_to( $button_format, $destination , $hiddens = null)
    {
        $CI =& get_instance();    

        $html = "<form action='{$CI->config->site_url($destination)}' method='post'>";

        if (!empty($hiddens))
        {
            foreach ($hiddens as $key => $value)
                $html .= "<input type='hidden' name='$key' value='$value' />";
        }

        if (is_array($button_format))
        {
            $html .= "<input type='submit' "; 

            foreach ($button_format as $key => $value)
                $html .= $key . "='". $value . "' ";
    
            $html .= "/>";
        } else {
            $html .= "<input type='submit' value='{$button_format}' />";
        }
        $html .= "</form>";
        return $html;
    }
}
Clone this wiki locally