Creating a Custom Page in OpenCart – part 2

Written by in Tutorials on August 31, 2012  |  32 Comments

creating-a-custom-page-in-opencart-part-2

Let’s 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 don’t 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.

CREATE TABLE IF NOT EXISTS `my_web_news` (
 `news_id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) NOT NULL,
 `description` text NOT NULL,
 `date_added` datetime NOT NULL,
 PRIMARY KEY (`news_id`)
)

INSERT INTO `my_web_news` (`news_id`, `title`, `description`, `date_added`) VALUES
(1, 'Tutorial by MarketInSG', 'Tutorial by <a href="http://www.marketinsg.com"> MarketInSG</a>! Love us? Treat us to a coffee here: 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:00');

The Model File

Let’s 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

<?php
class ModelCatalogNews extends Model { // Model - type of file this is. Catalog - the folder. News - the file name.
   public function getNews($news_id) { // Function to call for from other files. Name it anything you like, but always remember what you named it!
      $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "my_web_news WHERE news_id = '" . $news_id . "'"); // Running query to retrieve 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 the file that calls for it.
      } else {
         return false;
      }
   }

   public function getAllNews() {
      $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "my_web_news ORDER BY date_added DESC");

      return $query->rows;
   }
}
?>

Wondering what is being done in those codes? Well, if your controller doesn’t 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.

<?php
class ControllerInformationNews extends Controller { // Controller - This is a controller file. Information - This is the folder it is in. News - This file name is news.php

   public function index() {
      $this->language->load('information/news'); // Calling for my language file
      $this->load->model('catalog/news'); // Calling for my model file

      $this->document->setTitle($this->language->get('heading_title')); // Set the title of your web page.

      $this->data['breadcrumbs'] = array(); // Breadcrumbs for your website.
      $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/news'),
         'separator' => $this->language->get('text_separator')
      );

      // Text from language file
      $this->data['heading_title'] = $this->language->get('heading_title');
      $this->data['text_title'] = $this->language->get('text_title');
      $this->data['text_description'] = $this->language->get('text_description');
      $this->data['text_view'] = $this->language->get('text_view');

      // Calling for the function getAllNews from the model file
      $all_news = $this->model_catalog_news->getAllNews();

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

      foreach ($all_news as $news) {
         $this->data['all_news'][] = array (
            'title' => $news['title'],
            'description' => (strlen(html_entity_decode($news['description'])) > 50 ? substr(strip_tags(html_entity_decode($news['description'])), 0, 50) . '..' : html_entity_decode($news['description'])),
            'view' => $this->url->link('information/news/news', 'news_id=' . $news['news_id'])
         );
      }

      // We call this Fallback system
      if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/information/news_list.tpl')) { // if file exists in your current template folder
         $this->template = $this->config->get('config_template') . '/template/information/news_list.tpl'; // get it
      } else {
         $this->template = 'default/template/information/news_list.tpl'; // or else get the file from the default folder (this is a fall back folder) always remember to have your template file in the default folder.
      }

      $this->children = array( // Required. The children files for the page.
         'common/column_left', // Column left which will allow you to place modules at the left of your page.
         'common/column_right',
         'common/content_top',
         'common/content_bottom',
         'common/footer', // the footer of your website
         'common/header'
      );

      $this->response->setOutput($this->render()); // Let's display it all!
   }

   public function news() {
      $this->load->model('catalog/news');
      $this->language->load('information/news');

      if (isset($this->request->get['news_id']) && !empty($this->request->get['news_id'])) {
         $news_id = $this->request->get['news_id'];
      } else {
         $news_id = 0;
      }

      $news = $this->model_catalog_news->getNews($news_id);

      $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/news'),
         'separator' => $this->language->get('text_separator')
      );

      if ($news) {
         $this->data['breadcrumbs'][] = array(
            'text' => $news['title'],
            'href' => $this->url->link('information/news/news', 'news_id=' . $news_id),
            'separator' => $this->language->get('text_separator')
         );

         $this->document->setTitle($news['title']);

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

         if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/information/news.tpl')) {
            $this->template = $this->config->get('config_template') . '/template/information/news.tpl';
         } 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') . '/template/error/not_found.tpl')) {
            $this->template = $this->config->get('config_template') . '/template/error/not_found.tpl';
         } 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());
      }
   }
}
?>

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

<?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']; ?>"><?php echo $breadcrumb['text']; ?></a>
      <?php } ?>
   </div>
   
   <h1><?php echo $heading_title; ?></h1>
   <center>
      <table style="width:80%; border-collapse: collapse; border-left: 1px solid #eeeeee; border-right: 1px solid #eeeeee;">
         <tr style="font-weight:bold;">
            <td style="width:30%; padding:10px 0px 10px 10px; background:#eeeeee; text-align:left;"><?php echo $text_title; ?></td>
            <td style="width:50%; padding:10px 0px 10px 10px; background:#eeeeee; text-align:left;"><?php echo $text_description; ?></td>
            <td style="width:10%; padding:10px 10px 10px 10px; background:#eeeeee; text-align:right;"></td>
         </tr>
         <?php foreach ($all_news as $news) { ?>
            <tr>
               <td style="padding:10px 0px 10px 10px; text-align:left; border-bottom: 1px solid #eeeeee;"><?php echo $news['title']; ?></td>
               <td style="padding:10px 0px 10px 10px; text-align:left; border-bottom: 1px solid #eeeeee; border-left: 1px solid #eeeeee;"><?php echo $news['description']; ?></td>
               <td style="padding:10px 10px 10px 10px; text-align:right; border-bottom: 1px solid #eeeeee; border-left: 1px solid #eeeeee;"><a href="<?php echo $news['view']; ?>"><?php echo $text_view; ?></a></td>
            </tr>
         <?php } ?>
      </table>
   </center>
   
   <?php echo $content_bottom; ?>
</div>
<?php echo $footer; ?>

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

<?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']; ?>"><?php echo $breadcrumb['text']; ?></a>
      <?php } ?>
   </div>
   
   <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.

<?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 multi-language 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:

Download2826 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.

Next: Creating a Custom Page in OpenCart – Final

Tags: , , , , ,

About the Author

Joined OpenCart community since November 2011. MarketInSG is Singapore's first website dedicated to OpenCart web designing & modification.

View all posts by

32 Comments on "Creating a Custom Page in OpenCart – part 2"

  1. shiva February 18, 2016 at 8:36 pm · Reply

    Great tut :)
    how can i link my newly created page in my site, so that i can open it by clicking on related menu tab, also how can i pass the news_id from my from end, so that my users can search for the news using news id

  2. Paul April 25, 2015 at 11:16 pm · Reply

    Finally .. I’ve been trying to find a tutorial like this all day, all other tutorials do not explain how to access the data from the model through the controller and then finally render the view with the data, thank you for this excellent tutorial

  3. info March 29, 2015 at 10:56 pm · Reply

    I am regular reader, how are you everybody? This article posted at this website is actually good.

  4. food home business January 27, 2015 at 2:29 am · Reply

    Everything composed was very logical. However, think on this,
    suppose you were to write a awesome post title? I ain’t suggesting your content is not solid,
    however what if you added something to possibly get a person’s attention? I mean Creating a
    Custom Page in OpenCart – part 2 – OpencartNews is a little plain. You might look at Yahoo’s front page and watch how they write article headlines to get viewers to click.
    You might add a related video or a pic or two to get people excited
    about everything’ve got to say. In my opinion, it could bring your
    posts a little bit more interesting.

  5. rahuvendra January 5, 2015 at 10:30 am · Reply

    Thank you for you valuable articles and these are really helpfull for me.

  6. Hikaye November 6, 2014 at 3:55 pm · Reply

    Your goodwill is good but you can’t teach people MVC buy this way, they don’t have to create language files for each page, or they could use already assigned tpl files. But anyway thanks for this tutorial.

  7. Jenny March 1, 2014 at 7:36 am · Reply

    Hello, ur tutorial is very helpful to understand Opencart folder structure and functionality.
    But I’ve an issue that i am not able to run this code.
    A link that u have suggested to run is – yoursite.com/index.php?route=information/news/new?news_id=xx, which is showing me an error that “PAGE REQUEST CAN NOT BE FOUND”
    Please guide me how to run this?

    And one more thing i wanna know is how to redirect pages in opencart? I mean I have created a button on product display page, now, i just want to make an entry in database and notifications will be displayed by Jquery…
    Plz, help me regarding this…

    • alex March 7, 2014 at 5:03 pm ·

      Excellent content after 20 days trying to resolve a problem with this information could solve in 10 min, very good

  8. Keiron February 1, 2014 at 7:43 pm · Reply

    Great tut, thank you!

    So i know now how I can query the DB to pull information…

    How do I insert info to the DB now? For instance if I wanted to allow users to comment on a news article.

  9. Freddie November 14, 2013 at 4:50 pm · Reply

    Nice tutorial, you just need to make sure you add information of how users can use the SQL scripts,
    (you state that the user need not know what the SQL script text means, but if they don’t understand the script, the the likelihood of them understanding where they need to go to upload it, how to upload it, and why it needs to be uploaded is going to be a bit confusing for them, as this part kinda just gets skipped over.)

    • Maurice van der Veen January 18, 2014 at 10:55 pm ·

      I have no idea what to do with the SQL script, could you please help me out?

  10. These podcasts are designed to be played back
    and help you learn the language at your own pace. that is learning the language from the perspective of
    a second language. Whoever’s doing the teaching can actually influence the
    learners choice of religion.

    My blog effortless english full download – http://www.articlesnatch.com/profile/Lanora-Huerta/2152567 -

  11. Gary July 20, 2013 at 6:12 pm · Reply

    mySQL script has error ?

  12. Gary July 20, 2013 at 6:00 pm · Reply

    Hello. Thanks for your sharing first.
    I encounter a error when run your SQL script in the myphpadmin.
    Any advice ?

  13. Learn More Here February 2, 2013 at 6:17 pm · Reply

    This paragraph is really a good one it assists new web users, who are wishing for blogging.

  14. urusaiii January 21, 2013 at 7:48 am · Reply

    Hi,
    So I followed your part one tutuorial and partially the part two tutorial and ended up having a simple working link:
    http://bishounenboutique.com/static

    However, if you click on the breadcrumb “Static Page” link, it redirects to:
    http://bishounenboutique.com/index.php?route=static

    The reason I am using your static page as practice is because I am having similar problem in my other pages and it’s driving me crazy. I have modified a “manufacturer” module to “series”
    as well as the link too.
    For example:
    http://bishounenboutique.com/series
    the breadcrumbs are fine in that page. However,
    if you click on top image “Psycho pass” for example in that link, it will redirect to:
    http://bishounenboutique.com/index.php?route=product/manufacturer/product&manufacturer_id=13

    (which is not what i want. Ideally I want the link to be bishounenboutique.com/psycho-pass)

    But set that aside, on that page if you click on the breadcrumb link “series”, it gives:
    http://bishounenboutique.com/index.php?route=series

    but it is supposed to be:
    http://bishounenboutique.com/series
    !!!

    Can you please give me an idea of why this is happening, I have been searching for answer forever and have been losing sleep over this. I will be happy to support your business.

    • urusaiii January 28, 2013 at 2:16 am ·

      … No answer?

  15. Rohan January 17, 2013 at 12:21 pm · Reply

    thank you,please tells us how to upload image in admin panel

    • MarketInSG January 17, 2013 at 1:24 pm ·

      refer to our next tutorial which has the full features done.

  16. François December 7, 2012 at 9:15 am · Reply

    Hi,

    Thanks for the code, really helpful! Now, to access those pages (static and new/news_list) can I simply add a link inthe menu in my header.tpl file?

    François.

    • MarketInSG December 7, 2012 at 9:16 am ·

      Of course you can.

  17. Speedovic November 7, 2012 at 10:04 pm · Reply

    Thanks for this good tutorial.
    I have a question I would like to add an entry field for users to select a category news before getting a list (as an example they can enter “general” so they get general news or “sport” so only sport news will be displayed etc.

    I am able to add a new field to the table called Category, I can adapt the query in the model. But my issue is how to get the view and the controller working (I am not that far with (MVC), I need to have an entry field in the view for users to type in “sport” as an example, and when they hit enter the controller call the query in the model to run the search. The result will be displayed exactly as in the tutorial.
    I am really stack so if anyone can help would be really appreciated.

    • MarketInSG November 7, 2012 at 11:52 pm ·

      if you would want to categorize each and every news, you will have to add the ‘category’ field to your news table (not the category table). From there on, you have to add extra field to the template file, allowing them to input and submit the form. Upon submission, the system will search for the category entered following the query in the model file. The results will then be displayed. There’s quite a lot of changes, and it requires user input. If you are not very experience with such changes, it is not recommended. I have a full working news extension provided free on the ‘Final’ tutorial.

  18. rash111 November 6, 2012 at 7:02 am · Reply

    Amazing article man. It is very helpful.

    • MarketInSG November 6, 2012 at 11:55 am ·

      thanks :) read on to the final one :) you may also suggest topics

  19. Emanuel October 31, 2012 at 6:54 pm · Reply

    Hallo, I don’t know how to run the sql cod in the DB….can you tell me please?

    Thanks

    • MarketInSG November 1, 2012 at 12:02 am ·

      you can just run the codes in PHPMyAdmin else you can just look at our next tutorial that wraps up everything including a system that automatically adds the extra table

  20. Humayun October 12, 2012 at 12:21 pm · Reply

    Amazing Articles on Open cart very helpful. Looking Forward to your next tutorials. Thanks

  21. ural September 27, 2012 at 12:21 pm · Reply

    Both articles are really helpfull. Thanks for all and waiting for new Tutorials. Best wishes.

    • MarketInSG September 27, 2012 at 12:29 pm ·

      Thank you. New tutorial will be out in a week or two when I have some time.

Trackbacks for this post

  1. Creating a Custom Page in OpenCart – Final - OpencartNews

Leave a Comment

comm comm comm