Вы находитесь на странице: 1из 38

Creating a Custom Page in OpenCart

How do I create an additional page in my OpenCart website? Thats likely the question that brought you here. So,
here is a simple tutorial for you to begin with. I will assume you already have basic PHP knowledge and HTML
knowledge. If you dont, not to worry, you can read the comments beside each line to help you understand.

Understanding OpenCart
OpenCart uses a MVC + (L) framework. So basically, you will need a few compulsory files created for it to work.
Required files:
1.

A controller file

2.

A template file

Optional files:
1.

Model file

2.

Language file

Controller File
You will need to first create a controller file in the controller folder. For this tutorial, I will create a file named static.php
in the /catalog/controller/information/ folder. Since we named the file static.phpand put it at information/ folder, the
controller class name will be ControllerInformationStatic.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

<?php
class ControllerInformationStatic extends Controller {
public function index() {
$this->language->load('information/static'); //Optional. This calls for your l
$this->document->setTitle($this->language->get('heading_title')); //Optional.
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'text'
=> $this->language->get('text_home'),
'href'
=> $this->url->link('common/home'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'text'
=> $this->language->get('heading_title'),
'href'
=> $this->url->link('information/static'),
'separator' => $this->language->get('text_separator')
);

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

// Text from language file


$this->data['heading_title'] = $this->language->get('heading_title'); //Get "h
$this->data['text_content'] = $this->language->get('text_content');

// We call this Fallback system


if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/templa
your current template folder
$this->template = $this->config->get('config_template') . '/template/infor
} else {
$this->template = 'default/template/information/static.tpl'; //or get the
}
//Required. The children files for the page.
$this->children = array(
'common/column_left',
'common/column_right',
'common/content_top',
'common/content_bottom',
'common/footer',
'common/header'
);

$this->response->setOutput($this->render());

}
?>

So let me explain whats being done above. In a MVC framework, the controller file is loaded. It is literally the brain of
the whole page. It processes and do according to what you asked it to. So $this->template = $this->config>get(config_template) . /template/information/static.tpl; is asking to load for your template file, which will lead us to
the next part.

Template File
So, this is one of the required files too. We will create a file named static.tpl in the
/catalog/view/theme/default/template/information/ folder.

1
2
3
4
5
6
7
8

<?php echo $header; ?><?php echo $column_left; ?><?php echo $column_right; ?>
<div id="content">
<?php echo $content_top; ?>

<div class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<?php echo $breadcrumb['separator']; ?><a href="<?php echo $breadcrumb['href'];
$breadcrumb['text']; ?></a>
<?php } ?>

9
10
11
12
13
14
15
16
17

</div>
<h1><?php echo $heading_title; ?></h1>
<?php echo $text_content; ?>
<?php echo $content_bottom; ?>
</div>
<?php echo $footer; ?>

So what basically happens above is that it is loading all the things you will see in your browser. It will load your header
and footer, which will get the layout of your website. Nothing fancy about it, all your styling is done here. So, you will
wonder about those optional files I mentioned, which will bring us to the next part of the tutorial.

Language File
As most of you know, OpenCart supports multi-language. You can have multiple language file in your language folder
so that it can be loaded in different language. However, for this tutorial, we will be creating only for the English
language. We will start with creating a file named static.php in the catalog/language/english/information/ folder.

1
2
3
4
5
6
7

<?php
// Heading
$_['heading_title'] = 'Static Page'; //Add as many as you want, but remember to call fo
can use it in the template
// Text
$_['text_content']
?>

= 'My Static Page Content';

Wondering what the magical line of code above does? Well, it is what the line of code $this->data['heading_title'] =
$this->language->get(heading_title); in your controller file is calling for. Without this line, your controller file will not
be able to get the words you would like to display.
You can download all files from this tutorial in file below:
Download4154 downloads
So basically, you have successfully made your custom page. You can now access the page you created from
yourwebsite.com/index.php?route=information/static. Easy as it seems, but you can surely do more with these simple
little things, which we will cover in the second part of the tutorial. The second part of the tutorial will cover on using the
model files and search engine optimization.

Lets move on to the advance level now. If you have no basic understanding of OpenCart and the MVC(L) structure,
do refer to part 1 of this tutorial.

In this tutorial, we are going to use the model file too. We will create a page that will retrieve some news from your
database.

SQL Codes
You dont really have to know what this does. Just run this SQL code and it will create a table in your database for
you, with 2 sample news.

1 CREATE TABLE IF NOT EXISTS `my_web_news` (


2 `news_id` int(11) NOT NULL AUTO_INCREMENT,
3 `title` varchar(255) NOT NULL,
4 `description` text NOT NULL,
`date_added` datetime NOT NULL,
5 PRIMARY KEY (`news_id`)
6 )
7
8 INSERT INTO `my_web_news` (`news_id`, `title`, `description`, `date_added`) VALUES
9 (1, 'Tutorial by MarketInSG', 'Tutorial by &lt;a href=&quot;http://www.marketinsg.com&qu
10 http://www.marketinsg.com/donate', '2012-08-23 00:00:00'),
(2, 'My First News Post', 'Just anything about my awesome website!', '2012-08-22 00:00:0
11

The Model File


Lets start with something simple. We are going to get some news from your table! It should be something quite
simple and straightforward for you. We will create a file named news.php in the /catalog/model/catalog/ folder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

<?php
class ModelCatalogNews extends Model { // Model - type of file this is. Catalog - the f
public function getNews($news_id) { // Function to call for from other files. Name i
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "my_web_news WHERE news_
information from your database table.

if ($query->num_rows) { // If row exists


return $query->row; // I retrieved the information, now I must pass it back to
} else {
return false;
}
}

public function getAllNews() {


$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "my_web_news ORDER BY da
return $query->rows;
}
?>

Wondering what is being done in those codes? Well, if your controller doesnt call for the model file, those codes will
just be useless. For a start, the first function will run a query to retrieve a specific news from your database. For the
second function, it will retrieve all news, and order them according to the date they were added into the database. The
newest news will always be at the top. Simple as that, we will move on to the controller file.

Controller File
Well, if you remember in the part 1 of this tutorial, we used a controller file. Well, same here, we will use one. This file
is a must have. So we will create a file named news.php in /catalog/controller/information/ folder. This time, we will
do a little more.

1 <?php
2 class ControllerInformationNews extends Controller { // Controller - This is a controller
3
public function index() {
4
$this->language->load('information/news'); // Calling for my language file
5
$this->load->model('catalog/news'); // Calling for my model file
6
$this->document->setTitle($this->language->get('heading_title')); // Set the title
7
8
$this->data['breadcrumbs'] = array(); // Breadcrumbs for your website.
9
$this->data['breadcrumbs'][] = array(
10
'text' => $this->language->get('text_home'),
11
'href' => $this->url->link('common/home'),
12
'separator' => false
);
13
$this->data['breadcrumbs'][] = array(
14
'text' => $this->language->get('heading_title'),
15
'href' => $this->url->link('information/news'),
16
'separator' => $this->language->get('text_separator')
);
17
18
// Text from language file
19
$this->data['heading_title'] = $this->language->get('heading_title');
20
$this->data['text_title'] = $this->language->get('text_title');
21
$this->data['text_description'] = $this->language->get('text_description');
22
$this->data['text_view'] = $this->language->get('text_view');
23
// Calling for the function getAllNews from the model file
24
$all_news = $this->model_catalog_news->getAllNews();
25
26
$this->data['all_news'] = array();
27
28
foreach ($all_news as $news) {
29
$this->data['all_news'][] = array (
30
'title' => $news['title'],
'description' => (strlen(html_entity_decode($news['description'])) > 50 ? su
31
html_entity_decode($news['description'])),
32
'view' => $this->url->link('information/news/news', 'news_id=' . $news['news_
33
);

}
34
35
// We call this Fallback system
36
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/
37
$this->template = $this->config->get('config_template') . '/template/informatio
38
} else {
$this->template = 'default/template/information/news_list.tpl'; // or else get
39
your
template
file in the default folder.
40
}
41
42
$this->children = array( // Required. The children files for the page.
43
'common/column_left', // Column left which will allow you to place modules at t
44
'common/column_right',
'common/content_top',
45
'common/content_bottom',
46
'common/footer', // the footer of your website
47
'common/header'
48
);
49
$this->response->setOutput($this->render()); // Let's display it all!
50
}
51
52
public function news() {
53
$this->load->model('catalog/news');
54
$this->language->load('information/news');
55
56
if (isset($this->request->get['news_id']) && !empty($this->request->get['news_id']
$news_id = $this->request->get['news_id'];
57
}
else
{
58
$news_id = 0;
59
}
60
61
$news = $this->model_catalog_news->getNews($news_id);
62
63
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
64
'text' => $this->language->get('text_home'),
65
'href' => $this->url->link('common/home'),
66
'separator' => false
67
);
$this->data['breadcrumbs'][] = array(
68
'text' => $this->language->get('heading_title'),
69
'href' => $this->url->link('information/news'),
70
'separator' => $this->language->get('text_separator')
71
);
72
73
if ($news) {
$this->data['breadcrumbs'][] = array(
74
'text' => $news['title'],
75
'href' => $this->url->link('information/news/news', 'news_id=' . $news_id),
76
'separator' => $this->language->get('text_separator')
77
);
78
$this->document->setTitle($news['title']);
79

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
10
0
10
1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
110
111
112
113
}
114}
115?>

$this->data['heading_title'] = $news['title'];
$this->data['description'] = html_entity_decode($news['description']);

if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/templa


$this->template = $this->config->get('config_template') . '/template/informa
} else {
$this->template = 'default/template/information/news.tpl';
}
$this->children = array(
'common/column_left',
'common/column_right',
'common/content_top',
'common/content_bottom',
'common/footer',
'common/header'
);
$this->response->setOutput($this->render());
} else {
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_error'),
'href' => $this->url->link('information/news', 'news_id=' . $news_id),
'separator' => $this->language->get('text_separator')
);
$this->document->setTitle($this->language->get('text_error'));
$this->data['heading_title'] = $this->language->get('text_error');
$this->data['text_error'] = $this->language->get('text_error');
$this->data['button_continue'] = $this->language->get('button_continue');
$this->data['continue'] = $this->url->link('common/home');

if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/templa


$this->template = $this->config->get('config_template') . '/template/error/n
} else {
$this->template = 'default/template/error/not_found.tpl';
}
$this->children = array(
'common/column_left',
'common/column_right',
'common/content_top',
'common/content_bottom',
'common/footer',
'common/header'
);

$this->response->setOutput($this->render());

116
117
118
119
12
0
12
1
12
2
12
3
12
4
12
5
12
6
12
7
12
8
12
9
13
0
13
1
13
2
13
3
13
4
13
5
13
6
13
7
13
8
13
9
14
0

14
1
14
2
14
3
14
4
14
5
Are you still there? Getting dizzy with all those codes? Well, let me explain what those are for. If you look closely, I
have two functions in it public function index() & public function news(). The first one will be accessing the page
through yoursite.com/index.php?route=information/news/ and the second part will allow you to access the page
through yoursite.com/index.php?route=information/news/new?news_id=xx. So the second part will allow you to
retrieve a specific news in a page.

Template File
Hang on there, we are almost done with it! We shall now create a template file. This time, we will have to create two
template file. Notice the difference from part 1 of our tutorial? Well, this is simply because we called for two separate
template file in the controller (news_list.tpl & news.tpl, you can ignore the not_found.tpl file).
/catalog/view/theme/default/template/information/news_list.tpl

1 <?php echo $header; ?><?php echo $column_left; ?><?php echo $column_right; ?>
2 <div id="content">
<?php echo $content_top; ?>
3
4
<div class="breadcrumb">
5
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<?php echo $breadcrumb['separator']; ?><a href="<?php echo $breadcrumb['href'];
6
<?php
} ?>
7
</div>
8
9
<h1><?php echo $heading_title; ?></h1>
1
<center>
0
<table style="width:80%; border-collapse: collapse; border-left: 1px solid #eeeeee
<tr style="font-weight:bold;">
11
<td style="width:30%; padding:10px 0px 10px 10px; background:#eeeeee; text-a
1
<td style="width:50%; padding:10px 0px 10px 10px; background:#eeeeee; text-a
2
<td style="width:10%; padding:10px 10px 10px 10px; background:#eeeeee; text1
</tr>
3
<?php foreach ($all_news as $news) { ?>
<tr>
1
<td style="padding:10px 0px 10px 10px; text-align:left; border-bottom: 1p
4
<td style="padding:10px 0px 10px 10px; text-align:left; border-bottom: 1p
1
<td style="padding:10px 10px 10px 10px; text-align:right; border-bottom:
5 >"><?php echo $text_view; ?></a></td>
</tr>
1

6
1
7
1
8
1
9
2
0
2
1
2
2
<?php } ?>
2
</table>
</center>
3
2
<?php echo $content_bottom; ?>
4
</div>
2
<?php echo $footer; ?>
5
2
6
2
7
2
8
2
9
3
0
3
1
All those codes should be self-explanatory. Those are just basic HTML. This file will display a list of all your news.
Since your model file retrieved them in the order of the latest news at the top, the news will be displayed in the same
way it was retrieved. Beside each news, there will be a View link for us to click to view the full story of each news,
which will lead us to the next template file.
/catalog/view/theme/default/template/information/news.tpl

1
2
3
4
5
6
7
8
9

<?php echo $header; ?><?php echo $column_left; ?><?php echo $column_right; ?>
<div id="content">
<?php echo $content_top; ?>
<div class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<?php echo $breadcrumb['separator']; ?><a href="<?php echo $breadcrumb['href']
$breadcrumb['text']; ?></a>
<?php } ?>
</div>

10
11
12
13
14
15

<h1><?php echo $heading_title; ?></h1>


<p><?php echo $description; ?></p>
<?php echo $content_bottom; ?>
</div>
<?php echo $footer; ?>

This will be simpler than the previous template file. This template file will only display one specific news that the user
called for. Simple, and nothing else. So we shall move on to the language file, which will be similar to part 1 of this
tutorial.

Language File
Create a file named news.php in the /catalog/language/english/information/ folder.

1
2
3
4
5
6
7
8
9
10

<?php
// Heading
$_['heading_title'] = 'Our Latest News';
// Text
$_['text_title'] = 'Title';
$_['text_description'] = 'Description';
$_['text_view'] = 'View';
$_['text_error'] = 'The page you are looking for cannot be
found.';
?>

The codes above will be called for by the controller. No much difference from part 1 of the tutorial, just that there is
more lines of text. All these lines of text will be displayed to the user through the template file. So if you allow multilanguage on your website, you will have to duplicate a few more of this file into different language folder.
You can download all files from this tutorial below:
Download1849 downloads
To wrap it up, you have successfully created a simple page to display all news from your database. However, you are
looking to simplify the long looking link? Sure, try the code below:

RewriteRule ^news$ index.php?route=information/news

Add the line of code to your .htaccess file, just directly below this RewriteBase /. Now, you can easily access all
your news through yoursite.com/news! Nothing tough right? So are you looking forward to another of our tutorial? If
so, do let us know through the comments section below this tutorial. In the next tutorial, we will teach you how to build
you a full news system complete with an admin panel integrated into your OpenCart.

This will be the final part of our tutorial. If you have followed our tutorial all the way, you should be able to work out on
this final tutorial easily. Continuing from where we left off, in this tutorial, we will complete the example we were
working on previously (a simple news extension).

Admin Panel
From where we left off, the page to display news doesnt have an admin panel. So let us work on it now. The admin
panel will just be a simple page where you can view your list of news and add news into the database, allowing it to
be displayed on your store front.

Controller File
We will create a file in admin/controller/extension and name it news.php.

<?php

class ControllerExtensionNews extends Controller {

private $error = array();

4
5
6
7
8
9
10

private function install() {


$this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "news` (
`news_id` int(11) NOT NULL AUTO_INCREMENT,
`date_added` datetime NOT NULL,
`status` tinyint(1) NOT NULL,
PRIMARY KEY (`news_id`)
)");

11
12
13

$this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "news_descriptio


`news_description_id` int(11) NOT NULL AUTO_INCREMENT,

14

`news_id` int(11) NOT NULL,

15

`language_id` int(11) NOT NULL,

16

`title` varchar(255) COLLATE utf8_bin NOT NULL,

17

`description` text COLLATE utf8_bin NOT NULL,

18

PRIMARY KEY (`news_description_id`)


)");

19
20

21
22
23
24
25

public function index() {


$this->install();
$this->load->language('extension/news');
$this->load->model('extension/news');

26
27
28

$this->document->setTitle($this->language->get('heading_title'));

$this->data['breadcrumbs'] = array();

29
30

$this->data['breadcrumbs'][] = array(

31
32
33
34

'text'

=> $this->language->get('text_home'),

'href'

=> $this->url->link('common/home', 'token=' . $this->session->da

'separator' => false


);

35
36

$this->data['breadcrumbs'][] = array(

37
38
39
40

'text'

=> $this->language->get('heading_title'),

'href'

=> $this->url->link('extension/news', 'token=' . $this->session-

'separator' => ' :: '


);

41
42
43

if (isset($this->session->data['success'])) {
$this->data['success'] = $this->session->data['success'];

44
45
46

unset($this->session->data['success']);
} else {
$this->data['success'] = '';

47
48

49
50

if (isset($this->session->data['warning'])) {
$this->data['error'] = $this->session->data['warning'];

51
52

unset($this->session->data['warning']);

53
54
55

} else {
$this->data['error'] = '';
}

56
57

$url = '';

58
59

if (isset($this->request->get['page'])) {

60

$page = $this->request->get['page'];

61

$url .= '&page=' . $this->request->get['page'];

62

} else {

63
64

$page = 1;
}

65
66

$data = array(

67

'page' => $page,

68

'limit' => $this->config->get('config_admin_limit'),

69

'start' => $this->config->get('config_admin_limit') * ($page - 1),

70

);

71
72

$total = $this->model_extension_news->countNews();

73
74

$pagination = new Pagination();

75

$pagination->total = $total;

76
77
78
79
80

$pagination->page = $page;
$pagination->limit = $this->config->get('config_admin_limit');
$pagination->text = $this->language->get('text_pagination');

$pagination->url = $this->url->link('extension/news', 'token=' . $this->sessio

$this->data['pagination'] = $pagination->render();

81
82

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

83
84
85

$this->data['text_title'] = $this->language->get('text_title');
$this->data['text_date'] = $this->language->get('text_date');

86

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

87

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

88
89

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

90

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

91
92

$this->data['insert'] = $this->url->link('extension/news/insert', '&token=' .

93

$this->data['delete'] = $this->url->link('extension/news/delete', 'token=' . $

94
95

$this->data['allnews'] = array();

96
97

$allnews = $this->model_extension_news->getAllNews($data);

98
foreach ($allnews as $news) {

99
100

$this->data['allnews'][] = array (

101

'news_id' => $news['news_id'],


'title' => $news['title'],

102

'date_added' => date('d M Y', strtotime($news['date_added'])),

103

'edit' => $this->url->link('extension/news/edit', '&news_id=' . $news[

104 'SSL')
105

);

106

107
108

$this->template = 'extension/news_list.tpl';

109

$this->children = array(

110

'common/header',
'common/footer'

111
);

112
113

$this->response->setOutput($this->render());

114
115

116
public function edit() {

117
118

$this->load->language('extension/news');
$this->load->model('extension/news');

119
120
121

$this->document->setTitle($this->language->get('heading_title'));

122

if (isset($this->session->data['warning'])) {
$this->data['error'] = $this->session->data['warning'];

123
124

unset($this->session->data['warning']);

125
126

} else {
$this->data['error'] = '';

127
128

129
130
131

if (!isset($this->request->get['news_id'])) {

$this->redirect($this->url->link('extension/news', '&token=' . $this->sess


}

132
133

if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate())

134

$this->model_extension_news->editNews($this->request->get['news_id'], $th

135
136

$this->session->data['success'] = $this->language->get('text_success');

137
138
139

$this->redirect($this->url->link('extension/news', 'token=' . $this->sessi


}

140
141

$this->data['breadcrumbs'] = array();

142
143

$this->data['breadcrumbs'][] = array(

144

'text'

=> $this->language->get('text_home'),

145

'href'

=> $this->url->link('common/home', 'token=' . $this->session->da

146

'separator' => false

147

);

148
149

$this->data['breadcrumbs'][] = array(

150

'text'

=> $this->language->get('heading_title'),

151

'href'

=> $this->url->link('extension/news', 'token=' . $this->session-

152

'separator' => ' :: '


);

153
154
155

$this->data['action'] = $this->url->link('extension/news/edit', '&news_id=' .


>session->data['token'], 'SSL');

156

$this->data['cancel'] = $this->url->link('extension/news', '&token=' . $this->

157

$this->data['token'] = $this->session->data['token'];

158
159
160

$this->form();
}

161
162

public function insert() {

163

$this->load->language('extension/news');

164

$this->load->model('extension/news');

165
166

$this->document->setTitle($this->language->get('heading_title'));

167
168
169

if (isset($this->session->data['warning'])) {
$this->data['error'] = $this->session->data['warning'];

170
171
172
173

unset($this->session->data['warning']);
} else {
$this->data['error'] = '';

174

175
176

if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate())


$this->model_extension_news->addNews($this->request->post);

177
178

$this->session->data['success'] = $this->language->get('text_success');

179
180

$this->redirect($this->url->link('extension/news', 'token=' . $this->sessi

181
182

183
184

$this->data['breadcrumbs'] = array();

185
186

$this->data['breadcrumbs'][] = array(

187
188

'text'

=> $this->language->get('text_home'),

'href'

=> $this->url->link('common/home', 'token=' . $this->session->da

'separator' => false

189

);

190
191

$this->data['breadcrumbs'][] = array(

192
193
194
195

'text'

=> $this->language->get('heading_title'),

'href'

=> $this->url->link('extension/news', 'token=' . $this->session-

'separator' => ' :: '


);

196
197

$this->data['action'] = $this->url->link('extension/news/insert', '&token=' .

198

$this->data['cancel'] = $this->url->link('extension/news', '&token=' . $this->

199

$this->data['token'] = $this->session->data['token'];

200
201
202

$this->form();
}

203
204
205
206
207

private function form() {


$this->load->language('extension/news');
$this->load->model('extension/news');
$this->load->model('localisation/language');

208
209

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

210
211
212
213
214
215

$this->data['text_title'] = $this->language->get('text_title');
$this->data['text_description'] = $this->language->get('text_description');
$this->data['text_status'] = $this->language->get('text_status');
$this->data['text_keyword'] = $this->language->get('text_keyword');
$this->data['text_enabled'] = $this->language->get('text_enabled');
$this->data['text_disabled'] = $this->language->get('text_disabled');

216
217

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

218

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

219
220

$this->data['languages'] = $this->model_localisation_language->getLanguages()

221
222
223
224
225

if (isset($this->request->get['news_id'])) {

$news = $this->model_extension_news->getNews($this->request->get['news_id'
} else {
$news = '';

226

227
228

if (isset($this->request->post['news'])) {
$this->data['news'] = $this->request->post['news'];

229
230

} elseif (!empty($news)) {

$this->data['news'] = $this->model_extension_news->getNewsDescription($th

231
232

} else {
$this->data['news'] = '';

233
234
235

if (isset($this->request->post['keyword'])) {

236
237

$this->data['keyword'] = $this->request->post['keyword'];
} elseif (!empty($news)) {

238
239

$this->data['keyword'] = $news['keyword'];
} else {

240
241

$this->data['keyword'] = '';
}

242
243

if (isset($this->request->post['status'])) {

244
245

$this->data['status'] = $this->request->post['status'];
} elseif (!empty($news)) {
$this->data['status'] = $news['status'];

246
247

} else {
$this->data['status'] = '';

248
249

250
251

$this->template = 'extension/news_form.tpl';

252

$this->children = array(

253

'common/header',

254

'common/footer'
);

255
256

$this->response->setOutput($this->render());

257
258

259
260

public function delete() {


$this->load->language('extension/news');

261

$this->load->model('extension/news');

262
263

$this->document->setTitle($this->language->get('heading_title'));

264
265

if (isset($this->request->post['selected']) && $this->validateDelete()) {

266

foreach ($this->request->post['selected'] as $id) {

267

$this->model_extension_news->deleteNews($id);

268

269
270

$this->session->data['success'] = $this->language->get('text_success');

271

272

$this->redirect($this->url->link('extension/news', 'token=' . $this->session->

273
274

275
276
277

private function validateDelete() {


if (!$this->user->hasPermission('modify', 'extension/news')) {

278

$this->error['warning'] = $this->language->get('error_permission');

279

$this->session->data['warning'] = $this->language->get('error_permission'

280
}

281
282

if (!$this->error) {

283

return true;

284

} else {

285

return false;

286
}

287

288
289

private function validate() {

290

if (!$this->user->hasPermission('modify', 'extension/news')) {

291

$this->error['warning'] = $this->language->get('error_permission');

292

$this->session->data['warning'] = $this->language->get('error_permission'

293

294
295

if (!$this->error) {

296

return true;

297

} else {
return false;

298
}

299
}

300
301
302
303

}
?>

304
305
306
307
308
309
310
311
312
313

Seems long and complicating? Nah, its quite simple. For the function list, it list out all your news. When you click on
the Insert or Edit button, it will render the form instead of displaying the list. The install function will just be checking
if the news table had been added. If it is not in your database, it will add those tables for you. Simple! Not much
teaching will be done in this tutorial, its time to get your hands dirty. Work on it! You will surely get the structure of the
files after reading our previous two tutorials.

Template File
Now, since you have a list view and a form view, you will need to create 2 template files.
news_form.tpl

1 <?php echo $header; ?>


2 <div id="content">
3
4
5
6
7
8

<div class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>

<?php echo $breadcrumb['separator']; ?><a href="<?php echo $breadcrumb['href']; ?>"><


<?php } ?>
</div>
<?php if ($error) { ?>

<div class="warning"><?php echo $error; ?></div>

1
0

<?php } ?>

1
1
1
2
1
3
1
4
1
5

<div class="box">
<div class="heading">
<h1><img src="view/image/feed.png" alt="" /> <?php echo $heading_title; ?></h1>

<div class="buttons"><a onclick="$('#form').submit();" class="button"><?php echo $b


echo $button_cancel; ?></a></div>
</div>
<div class="content">

<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id=


<div id="language" class="htabs">
<?php foreach ($languages as $language) { ?>

1
<a href="#tab-language-<?php echo $language['language_id']; ?>"><img src="vie
6 /> <?php echo $language['name']; ?></a>
1
7
1
8
1
9
2
0

<?php } ?>
</div>
<?php foreach ($languages as $language) { ?>
<div id="tab-language-<?php echo $language['language_id']; ?>">
<table class="form">
<tr>
<td class="left"><?php echo $text_title; ?></td>

2
<td><input type="text" name="news[<?php echo $language['language_id']
1 $news[$language['language_id']]['title'] : ''; ?>" /></td>
2
2
2
3

</tr>
<tr>
<td><?php echo $text_description; ?></td>

<td><textarea name="news[<?php echo $language['language_id']; ?>][des

2
isset($news[$language['language_id']]) ? $news[$language['language_id']]['description'] :
4
2
5

</tr>

2
6

</table>
</div>

2
7

<?php } ?>
<table class="form">

2
8

<tr>
<td><?php echo $text_keyword; ?></td>

2
9

<td><input type="text" value="<?php echo $keyword; ?>" name="keyword"

3
0

</tr>
<tr>

3
1

<td><?php echo $text_status; ?></td>


<td><select name="status">

3
2

<option <?php if ($status == '1') { ?>selected="selected" <?php }

3
3

<option <?php if ($status == '0') { ?>selected="selected" <?php }


</select></td>

3
4
3
5
3
6

</tr>
</table>
</form>
</div>
</div>

3 </div>
7
3
8 <script type="text/javascript" src="view/javascript/ckeditor/ckeditor.js"></script>
3 <script type="text/javascript"><!-9 <?php foreach ($languages as $language) { ?>
4 CKEDITOR.replace('description-<?php echo $language['language_id']; ?>', {
0
4
1
4

filebrowserBrowseUrl: 'index.php?route=common/filemanager&token=<?php echo $token; ?>

filebrowserImageBrowseUrl: 'index.php?route=common/filemanager&token=<?php echo $toke

filebrowserFlashBrowseUrl: 'index.php?route=common/filemanager&token=<?php echo $toke

filebrowserUploadUrl: 'index.php?route=common/filemanager&token=<?php echo $token; ?>

4
3

filebrowserImageUploadUrl: 'index.php?route=common/filemanager&token=<?php echo $toke

filebrowserFlashUploadUrl: 'index.php?route=common/filemanager&token=<?php echo $toke

4 });
4
<?php } ?>

4
5 //--></script>
<script type="text/javascript"><!--

4
6 $('#language a').tabs();
4 //--></script>
7

<?php echo $footer; ?>

4
8
4
9
5
0
5
1
5
2
5
3
5
4
5
5
5
6
5
7
5

8
5
9
6
0
6
1
6
2
6
3
6
4
6
5
6
6
6
7
6
8
6
9
7
0
7
1

This is going to be easy. It displays a form with fields for you to fill it up. Making use of the built in text editor for
OpenCart, it turns your textarea box into a WYSIWYG editor. Now you have made yourself a form!
news_list.tpl

1 <?php echo $header; ?>

2 <div id="content">
3

<div class="breadcrumb">

<?php foreach ($breadcrumbs as $breadcrumb) { ?>

<?php echo $breadcrumb['separator']; ?><a href="<?php echo $breadcrumb['href']; ?>"><

6
7
8
9
1
0
1
1
1
2
1
3

<?php } ?>
</div>
<?php if ($success) { ?>
<div class="success"><?php echo $success; ?></div>
<?php } ?>
<?php if ($error) { ?>
<div class="warning"><?php echo $error; ?></div>
<?php } ?>
<div class="box">
<div class="heading">
<h1><img src="view/image/feed.png" alt="" /> <?php echo $heading_title; ?></h1>

<div class="buttons"><a onclick="location = '<?php echo $insert; ?>'" class="button

1 echo $button_delete; ?></a></div>


4
1
5
1
6
1
7
1
8
1
9
2
0
2

</div>
<div class="content">

<form action="<?php echo $delete; ?>" method="post" enctype="multipart/form-data" id=


<table class="list">
<thead>
<tr>

<td width="1" style="text-align: center;"><input type="checkbox" onclick="$('


<td class="left"><?php echo $text_title; ?></td>
<td class="left"><?php echo $text_date; ?></td>
<td class="right"><?php echo $text_action; ?></td>
</tr>

</thead>

2
2

<tbody>
<?php if ($allnews) { ?>

2
3

<?php foreach ($allnews as $news) { ?>


<tr>

2
4

<td width="1" style="text-align: center;"><input type="checkbox" name

2
5

<td class="left"><?php echo $news['title']; ?></td>

2
6

<td class="right">[ <a href="<?php echo $news['edit']; ?>"><?php echo

<td class="left"><?php echo $news['date_added']; ?></td>

</tr>

2
7

<?php } ?>
<?php } ?>

2
8
2
9
3
0

</tbody>
</table>
</form>
<div class="pagination"><?php echo $pagination; ?></div>

<div style="text-align:center; color:#222222;">Advance News System v1.2 by <a target

3 href="http://www.marketinsg.com/donate" target="_blank">MarketInSG</a></div>
1
</div>

3
2

</div>
</div>

3
3 <?php echo $footer; ?>
3
4
3
5
3
6
3

7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9

This is also similar to what we had previously. We get the news from the database and list them all out for you. So this
template is responsible for the listing of news.

Language File
Of course! How can we miss out this file?! This file, had been called for from our controller, so we should have
news.php in admin/language/english/ folder.

<?php

2
3
4

// Heading
$_['heading_title']

= 'News';

5
6
7
8

// Text
$_['text_title']

= 'Title';

$_['text_description']

= 'Description';

$_['text_date']

= 'Date Added';

$_['text_action']

= 'Action';

10

$_['text_status']

= 'Status';

11

$_['text_keyword']

= 'SEO Keyword';

12
13

// Success

14

$_['text_success']

= 'You have successfully modified news!';

15
16

// Error

17

$_['error_permission']
modify news!';

18

= 'Warning: You do not have permission to

?>

If we explain this again, were gonna explain it for the third time! You can always refer to our previous tutorials for
explanation on the language file, the functions, and how do you use it.

Model File
No, we didnt forget the model file! We will need this. So lets place news.php in admin/model/extension/ folder. The
folder shouldnt be there, so just create one.

1 <?php
2 class ModelExtensionNews extends Model {
3

public function addNews($data) {

$this->db->query("INSERT INTO " . DB_PREFIX . "news SET date_added = NOW(), statu

5
$news_id = $this->db->getLastId();

6
7

foreach ($data['news'] as $key => $value) {

8
9

$this->db->query("INSERT INTO " . DB_PREFIX ."news_description SET news_id =


>escape($value['title']) . "', description = '" . $this->db->escape($value['description']

1
0

1
1

if ($data['keyword']) {

$this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'news_id

1
2
1
3
1
4
1
5
1
6
1
7

}
}

public function editNews($id, $data) {

$this->db->query("UPDATE " . DB_PREFIX . "news SET status = '" . (int)$data['stat

$this->db->query("DELETE FROM " . DB_PREFIX . "news_description WHERE news_id = '

foreach ($data['news'] as $key => $value) {

$this->db->query("INSERT INTO " . DB_PREFIX ."news_description SET news_id =


1
8 >escape($value['title']) . "', description = '" . $this->db->escape($value['description']

1
9

2
0

$this->db->query("DELETE FROM " . DB_PREFIX . "url_alias WHERE query = 'news_id="

2
1
2

if ($data['keyword']) {

$this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'news_id

2
2
3
2
4

}
}

public function getNews($id) {


$query = $this->db->query("SELECT DISTINCT *, (SELECT keyword FROM " . DB_PREFIX

2 "news WHERE news_id = '" . (int)$id . "'");


5
2
6

if ($query->num_rows) {
return $query->row;

2
7

} else {

2
8
2
9
3
0

return false;
}
}

public function getNewsDescription($id) {

3
1

$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "news_description WHERE

3
2

foreach ($query->rows as $result) {


$news_description[$result['language_id']] = array(

3
3

'title'

3
4

'description' => $result['description']


);

3
5

3
6
3
7
3
8

=> $result['title'],

return $news_description;
}

3
9

public function getAllNews($data) {

$sql = "SELECT * FROM " . DB_PREFIX . "news n LEFT JOIN " . DB_PREFIX . "news_desc
4 >get('config_language_id') . "' ORDER BY date_added DESC";

0
4
1

if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {

4
2

$data['start'] = 0;
}

4
3

if ($data['limit'] < 1) {

4
4

$data['limit'] = 20;
}

4
5
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];

4
6

4
7

$query = $this->db->query($sql);

4
8
4
9

return $query->rows;
}

5
0
public function deleteNews($id) {

5
1

$this->db->query("DELETE FROM " . DB_PREFIX . "news WHERE news_id = '" . (int)$id

$this->db->query("DELETE FROM " . DB_PREFIX . "news_description WHERE news_id = '

5
2
5
3
5
4
5

$this->db->query("DELETE FROM " . DB_PREFIX . "url_alias WHERE query = 'news_id="


}

public function countNews() {


$count = $this->db->query("SELECT * FROM " . DB_PREFIX . "news");

5
5
6

return $count->num_rows;
}

5}
7
5
8
5
9
6
0
6
1
6
2
6
3
6
4
6
5
6
6
6
7
6
8
6
9
7
0
7

?>

1
7
2
7
3
7
4
7
5
7
6
7
7
7
8
7
9
8
0
8
1
8
2
8
3
8
4
8
5
8
6
8

There we go! Isnt this simple? Simple functions to insert, get, and update your database.

Putting it together
As usual, I wont be missing out the downloads for you guys! I have put together a fully functional news extension with
SEO URL & multi-language capabilities. Best of all, its free! You can get your free copy of this extension at News
system. Just download a copy of the extension and you can play around with the codes. vQmod will be needed for
this extension as it adds a link to your stores footer. Alternatively, you can access the news page from your store front
at http://yourstore.com/index.php?route=information/news.
As this is the last and final part of our Creating a Custom Page in OpenCart tutorial, should you wish to suggest a
new topic for us to write on, also you can always comment below. Follow MarketInSG on Facebook to get updates on
our new tutorials or follow OpenCartNews to be up to date on OpenCartNews.

Вам также может понравиться