Notes

Misc. OpenCart Snippets

Edit on GitHub

OpenCart
2 minutes

Controller

See if a user is logged in

1$this->customer->isLogged() // returns true/false

Load a language in a controller.php file

1$this->load->language('account/register');

Set language variables (in controller.php) to be used to template.tpl files

1$data['heading_title'] = $this->language->get('heading_title');

Reference URLs

1$this->url->link('account/logout') // URL for logout
2
3// URL saved as a variable which will be used in the template. e.g. <form action="<?php $action; ?>">
4$data['action'] = $this->url->link('account/register', '', true); 

Get a config value

1$this->config->get('config_account_id')

Load a model

1$this->load->model('catalog/information');

Load other controllers

1// LOAD OTHER CONTROLLERS
2$data['column_left'] = $this->load->controller('common/column_left');
3$data['column_right'] = $this->load->controller('common/column_right');
4$data['content_top'] = $this->load->controller('common/content_top');
5$data['content_bottom'] = $this->load->controller('common/content_bottom');
6$data['footer'] = $this->load->controller('common/footer');
7$data['header'] = $this->load->controller('common/header');

Load a template and send it data

1public function index() {
2  // Code goes here
3   
4  $this->response->setOutput($this->load->view('account/register', $data));
5}

Sending responses from controller.php with $this->response

1$this->response->redirect($this->url->link('account/success'));
2$this->response->setOutput($this->load->view('account/register', $data));
3$this->response->addHeader('Content-Type: application/json');
4$this->response->setOutput(json_encode($json));

Sending back JSON data

 1// Define an array
 2$json = array();
 3
 4// add data to that array
 5foreach ($custom_fields as $custom_field) {
 6  $json[] = array( 
 7    'custom_field_id' => $custom_field['custom_field_id'],
 8    'required'        => $custom_field['required']
 9    );
10  }
11
12// send the array as a response
13$this->response->addHeader('Content-Type: application/json');
14$this->response->setOutput(json_encode($json)); 

Breadcrumbs

 1// BREADCRUMBS
 2$data['breadcrumbs'] = array();
 3
 4$data['breadcrumbs'][] = array(
 5	'text' => $this->language->get('text_home'),
 6	'href' => $this->url->link('common/home')
 7);
 8
 9$data['breadcrumbs'][] = array(
10	'text' => $this->language->get('text_account'),
11	'href' => $this->url->link('account/account', '', true)
12);
13
14$data['breadcrumbs'][] = array(
15	'text' => $this->language->get('text_register'),
16	'href' => $this->url->link('account/register', '', true)
17);