How to create a custom admin page in opencart?
Asked Answered
A

2

33

I want to know how to make a custom admin panel page in opencart.

Requires login with the controller - the admin panel does not seem to use the same controller as the normal site. I know how to make custom pages with opencart (but this is not for the admin)

A simple Hello World example would be great

Atomicity answered 22/5, 2012 at 11:4 Comment(0)
A
64

OpenCart 2.x

The path names have changed in OpenCart 2 - you will want to create

admin/controller/extension/module/hello.php admin/language/en-gb/extension/module/hello.php admin/view/template/extension/module/hello.tpl Then the route becomes

admin/index.php?route=extension/module/hello

OpenCart 1.x

  • Include full MVC flow.

I found out how to do this. OpenCart uses the MVC pattern. I recommend reading about How to be an OpenCart Guru? post about learning how the system works - this Admin workflow should also suffice for customer end.

1) Create a new file in admin/controller/custom/helloworld.php

Your filename and controller name should be the same in desc order:

helloworld.php

<?

class ControllerCustomHelloWorld extends Controller{ 
    public function index(){
                // VARS
                $template="custom/hello.tpl"; // .tpl location and file
        $this->load->model('custom/hello');
        $this->template = ''.$template.'';
        $this->children = array(
            'common/header',
            'common/footer'
        );      
        $this->response->setOutput($this->render());
    }
}
?>

2) Create a new file in admin/view/template/custom/hello.tpl

Hello.tpl

<?php echo $header; ?>
<div id="content">
<h1>HelloWorld</h1>
<?php
echo 'I can also run PHP too!'; 
?>
</div> 
<?php echo $footer; ?>

3) Create a new file in admin/model/custom/hello.php

<?php
class ModelCustomHello extends Model {
    public function HellWorld() {
        $sql = "SELECT x FROM `" . DB_PREFIX . "y`)"; 
        $implode = array();
        $query = $this->db->query($sql);
        return $query->row['total'];    
    }       
}
?>

4) You then need to enable the plugin to avoid permission denied errors:

Opencart > Admin > Users > User Groups > Admin > Edit

Select and Enable the Access Permission.

To visit your page go to

www.yoursite.com/opencart/admin/index.php?route=custom/helloworld

Atomicity answered 22/5, 2012 at 11:47 Comment(19)
Good, repped - Great tut. I think this is not needed though $this->load->model('catalog/information'); might slow down your code loading un-needed libraries especially on busy sites with multiple admin users.Bordeaux
@Bordeaux Thanks. For comments and likes.Atomicity
admin/view/custom/hello.tpl should by admin/view/template/custom/hello.tplLeticialetisha
The loading of one model is going to make little difference even with 100 admins viewing the same page unless it's a really crappy serverSemiology
hi @TheBlackBenzKid....I need to create model file, how to create model files for custom form ?please advise me........Appomattox
getting below error, please suggest Fatal error: Class 'Controllercustomhelloworld' not found in C:\xampp\htdocs\bustersextra\system\engine\front.php on line 44Intelsat
Is the hello.php uploaded in the custom folder?Atomicity
SCREAM: Error suppression ignored for ( ! ) Fatal error: Class 'Controllercustomhelloworld' not found in C:\wamp\www\Opencart\system\engine\front.php on line 39 , i got this error ,when accessing the new page from the admin panel what to do ??Showpiece
Check your permissions in the User Groups and also check the tpl file existsAtomicity
Great tutorial. Thank you. On the last step: It seems right now the path to add access permission is: OpenCart Admin -> Users -> Users Groups -> Top Administrator - > Edit -> Tick only access permission or both access and modify permission and save.Mccarron
But you need to give the token param to access this directly in admin area, right?Bergamo
Just enable <?=$_GET['token']?> when visit the page. Just place the token in the URL. Yes we link to it, example admin/index.php?route=mods/helloworld&token=324834 etcAtomicity
Well .. actually, @TheBlackBenzKid, OpenCart does not use MVC pattern. They a bastardized version of Rails-like architecture. It doesn't have views (only dumb templates), it doesn't have model layer (only table gateways) and all of the logic is dumped in something they call "controllers".Inundate
Have your wrote any blog for this? I couldn't find any tutorial on "How to create a complete (admin/catalog) module in Opencart". or if you know any, please do tell me. thanksSalaidh
How to add that page in menu?Octangular
I have recently started building an OC website after last doing so a year two two back, so need to refresh. Alas I downloaded OC version 2, and cannot get this code working. Been at it for hours trying my luck. Error I am getting is "Fatal error: Call to undefined method ControllerCustomHelloWorld::render() in C:\websites\weddingshoponline\shop\admin\controller\custom\helloworld.php on line 14". Any suggestions? Or does this warrant a new question?Ludovick
You have a missing PHP file, please make a new questionAtomicity
Great answer - but your first file starts with "<?" instead of "<?php". Didn't notice that at first and it kept crashing, telling me the controller doesn't exist. Just wanted to point that out if anyone makes the same mistake as me.Lustick
on Gavin Simpson question; I got same error.. I tried below changes in Controller and it is working.. $data['footer'] = $this->load->controller('common/footer'); $data['column_left'] = $this->load->controller('common/column_left'); $data['header'] = $this->load->controller('common/header'); $this->response->setOutput($this->load->view('kvc/first',$data));Gould
N
5

OpenCart 3.x

We can use same MVC+L structure like in OC 1 and 2. Here is detailed example. Lats call it Custom Page.


Creating model using path /admin/model/custom/page.php

<?php
class ModelCustomPage extends Model {
    
    public function getTotalInformationsOnCustomPage() {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "information");
        return $query->row['total'];
    }

}

Your file path and model name should be the same. model/custom/page.php becomes ModelCustomPage.

Here you can see method public function getTotalInformationsOnCustomPage(), it's just for instance, took it from Information Model. Optional.


Creating controller using path /admin/controller/custom/page.php

<?php
class ControllerCustomPage extends Controller {
    public function index() {
        
        $this->load->language('custom/page'); // calling Custom Page language

        $this->document->setTitle($this->language->get('heading_title')); // set title from Custom Page language

        $this->load->model('custom/page'); // calling Custom Page model
        
        $data['information_total'] = $this->model_custom_page->getTotalInformationsOnCustomPage(); // calling model method 
        
        // breadcrumbs
        $data['breadcrumbs'] = array();

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('custom/page', 'user_token=' . $this->session->data['user_token'], true)
        );
        
        // calling header, footer and column_left for our template to render properly
        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');
        
        $this->response->setOutput($this->load->view('custom/page', $data)); // send our $data array to view
    }
}

This is minimal set for good looking admin page, with all default menus and breadcrumbs.

As in model, your file path and controller name should be the same. controller/custom/page.php becomes ControllerCustomPage.


Creating language using path /admin/language/en-gb/custom/page.php

<?php
// Heading
$_['heading_title']           = 'Custom Page';

// Text
$_['text_custom_block']       = 'Custom Block';
$_['text_total_informations'] = 'Total informations:';

Creating view using path /admin/view/template/custom/page.twig

{{ header }}{{ column_left }}
<div id="content">
  <div class="page-header">
    <div class="container-fluid">
      <h1>{{ heading_title }}</h1>
      <ul class="breadcrumb">
        {% for breadcrumb in breadcrumbs %}
        <li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
        {% endfor %}
      </ul>
    </div>
  </div>
  <div class="container-fluid">    
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title"><i class="fa fa-thumbs-up"></i> {{ text_custom_block }}</h3>
      </div>
      <div class="panel-body">{{ text_total_informations }} {{ information_total }}</div>
    </div>
  </div>
</div>
{{ footer }}

In this example I used standard block structure, inherent in this system. You can use any HTML you want. As you can see, {{ header }}, {{ column_left }}, {{ footer }} added for standard admin navigation support.

Working with .twig files don't forget to clear twig cache to see changes.


After all those manipulations, don't forget to set permissions for your new application. In admin panel go to System > Users > User groups, edit Administrator group (or/and any other you want). On edit page set find custom/page in both Access Permission and Modify Permission blocks, and mark it as selected. Save.


Now your new application is accessible by url yoursite.com/admin/index.php?route=custom/page&user_token=XXXXXX

Form this point you might want to add your custom page to the left menu of admin panel. You can do it by editing core files or, better, by OCMOD file.

Create custom_page.ocmod.xml

<?xml version="1.0" encoding="utf-8"?>
<modification>
  <name>Custom Page OCMOD</name>
  <code>custom-page</code>
  <version>1.0</version>
  <author>Me</author>
  <link>http://mywebsite.com</link>

  <file path="admin/controller/common/column_left.php">
    <operation>
      <search><![CDATA[// Stats]]></search>
      <add position="before"><![CDATA[
      $data['menus'][] = array(
        'id'       => 'menu-custom',
        'icon'     => 'fa-thumbs-up', 
        'name'     => $this->language->get('text_custom'),
        'href'     => $this->url->link('custom/page', 'user_token=' . $this->session->data['user_token'], true)
      );
      ]]></add>
    </operation>
  </file>  
  
  <file path="admin/language/en-gb/common/column_left.php">
    <operation>
      <search><![CDATA[// Text]]></search>
      <add position="after"><![CDATA[
        $_['text_custom']                  = 'Custom Page';
      ]]></add>
    </operation>
  </file>  

</modification>

Install the file in Extensions > Installer

Than go to Extensions > Extensions and clear OCMOD cache.

In this OCMOD file we just modified 2 OpenCart core file without editing them directly. Now you will see a link on a Custom Page in left admin menu.

More about OCMOD you can read in Opencart Modification System Related Questions and OpenCart OCMOD and VQMOD Modification Systems

Nappe answered 26/8, 2020 at 16:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.