[PrestaShop] Add a custom RowAction button in AdminController

Control your controllers...

Posted by debuss-a on 27th Jun 2018

Here is a quick to easily add a custom button on the right side of your HelperList in an AdminController class.
In the page, we will demonstrate with a module called LaPosteSuivi which track parcels, we will add a button "Track" (FR: Suivre) that will open a new tab to the tracking page of LaPoste.

First, your controller needs to extend the AdminController, ideally ModuleAdminController, then add some data for your helper.
The purpose here is to define which data will be displayed in your table :


/**
 * Class AdminOrdersLaPosteSuivi
 */
class AdminOrdersLaPosteSuiviController extends ModuleAdminController
{

    /** @var Context */
    protected $context;

    /**
     * AdminOrdersLaPosteSuiviController constructor.
     */
    public function __construct()
    {
        $this->bootstrap = true;
        $this->table = 'lapostesuivi';
        $this->className = __CLASS__;
        $this->context = Context::getContext();
        $this->lang = false;
        $this->allow_export = true;
        $this->deleted = false;
        $this->list_simple_header = false;

        // Here is the new button we want to add.
        $this->addRowAction('tracking');

        // For the sake of shortness, I do not display the rest of the code.
        // You can easily find example online to complete it, or check the
        // AdminOrdersController or AdminCarrierController to see how
        // to do it.
    }
}

We told the controller that we want to add a row action named "tracking".
Now we just need to add a method to handle it.
PrestaShop will look for a public method in the form of : display(name of your row action)Link() .

Let's add it in the controller.
I named the row action "tracking", therefore my method name will be : displayTrackingLink() .
In my method I only create a new Object then use it in the TPL file to create a button and generate the tracking link.

It is best practice not to hard code the HTML inside PHP. To pass the module validation, PrestaShop (Addons) will ask you to move your HTML code from PHP to TPL.


/**
 * Add a tracking  button instead of displaying the full URL.
 *
 * @param string|null $token
 * @param int $id
 * @param string|null $name
 * @return string
 * @throws PrestaShopDatabaseException
 * @throws PrestaShopException
 */
public function displayTrackingLink($token, $id, $name)
{
    // I unset $token and $name so PrestaShop Validator does not
    // complain that these variables are unused.
    unset($token);
    unset($name);

    $this->context->smarty->assign(array(
        'lps' => new LaPosteSuiviWebService($id)
    ));

    return $this->context->smarty->fetch(
        $this->getTemplatePath().'controller/track_button.tpl'
    );
}

Result on the right side of the table :

Track button is displayed as an external link.