A simple go back button widget

We all know that widgets are really useful. We can use the almost everywhere we want, and we can use the same code a lot of times ( Almost OOP ).

In this case we are going to create a really useful and simple widget. A GoBack button.

Why a widget ? Simple, we can extend the variables and make it as complex as we want, but will not be this case ;). We are going to pass just 1 variable if we need it.

Under your ext folder or widget folder ( mine under protected/ext/data ) create the following widget:

class EBackButtonWidget extends CWidget {

    public $width = "150px";
    
    public function run() {

        echo CHtml::button('Back', array(
            'name' => 'btnBack',
            'class' => 'uibutton loading confirm',
            'style' => 'width:'.$this->width.';',
            'onclick' => "history.go(-1)",
                )
        );
    }

}

Where:

  1. Back is the text that the button will show.
  2. name will be the name of the button
  3. class just in case that you want to do it pretty :).
  4. styles that you want to use. In my case I will change the width.
  5. onclick will execute our JS. In this case to go back 1 page.

To call this widget we simple:

<?
 $this->widget('application.ext.data.EBackButtonWidget',
   array(
    'width' => "100%",
   ));
?>

Where :

  1. application.ext.data.EBackButtonWidget is the path to our widget.
  2. width will be the width param that we give to the widget.

And that is it !!

Here's a very readable link in spanish to the original [tutorial][original]. [original]: http://www.cristiantala.cl/crear-un-widget-en-yii-boton-volver/