How To Save From Data In Admin Controller Prestashop

We passed together step by step the process to implement a custom tempalate for admin controller and we have create a sub-page (an edit page) for the main template. Now, in this tutorial I will show you how to save data from a custom form in admin controller and changes data structure as you wish. 

First, we will create a custom form in our template file, if you don't know how to create a custom template you can find a step by step tutorial here . So, put the following code in your template:

<form action="{$link->getAdminLink('AdminMymodule')|escape:'htmlall':'utf-8'}" method="post" class="form-horizontal">
<div class="panel edit_page_section">
        <div class="panel-heading">
            <i class="icon-pencil"></i> Edit page: {$page.page_name}
        </div>
 <div class="form-wrapper">
            <div class="form-group">
                <label class="control-label col-lg-3">Field Name</label>
                <div class="col-lg-6">
                    <input type="text" name="my_field" value="">
                </div>
             </div>
</div>
 <div class="panel-footer">
            <a href="{$link->getAdminLink('AdminMymodule')|escape:'htmlall':'utf-8'}" class="btn btn-default" id="cms_form_cancel_btn" onclick="window.history.back();">
                <i class="process-icon-cancel"></i> Cancel
            </a>
            <button type="submit" value="1" id="cms_form_submit_btn" name="saveMymodudleData" class="btn btn-default pull-right">
                <i class="process-icon-save"></i> Save
            </button>
        </div>
</div>
</form>

As you can see the form action point to our admin module so we will add there a postProcess() function from where we will change the data structure as we wish. In the bottom section of the form where is the submit button, its name is saveMymoduleData, we will use this name in the post process function because by this name we know what form was submitted. So, we can have multiple forms and if we change this name we will know where the data will be send.

the postProcess() function should like something like this:

public function postProcess()
    {
        if (Tools::isSubmit('saveMymodudleData'))
        {
            $fields = $_POST;
      $input_name = $this->getValue('input_name');
      
      Db::getInstance()->insert('my_table', array(
          'input_name'      => pSQL($input_name),
      ));
      
      
      
        }
}

As you can see in the above function we are using Tools::isSubmit() function to check when the form is submited, once the form is submited we get the value from $_POST and add it in the database. Let me know if you have any questions in the comments section.

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x