Adapting allArticles() in Articles.bx

On this page

Background

The whole point of the articles is to appear on the front page of our bookstore. To that end, we have a few more quick edits.

Editing our allArticles function to have a status and id arguments

On the main page of our site, we want only articles which have status==1 to appear. However, we are already using allArticles in our manageArticle.bxm page and we want it to show all articles so that we can edit them. There are several ways we can reconcile these differences.

We do NOT want to create a new query, however, because of a principle called "DRY" which stands for Don't Repeat Yourself. We don't want another function which is almost entirely the same as an existing one. This increases the amount of code we have to maintain and gets hard to read and debug.

Instead, we're going to adapt our existing allArticles function. When we call this function there are three possibilities when it comes to the active status

  1. Active only ( active=1)
  2. InActive only ( active=0)
  3. Both ( no active filter ). If we default the active submission to -1, we can only add the condition if active=1 or active =1.
1
Adding arguments to allArticles in Articles.bx

Add two arguments called id and status which both default to -1

We need to insert a condition into our SQL. Something like where status = 1 or id = 1, but we don't want that condition to be there if neither status nor id are submitted. If we add this line inside our function but above, the queryExecute(), we can create the string we need. If we don't submit a status, we have an empty string. If we submit a status, an id or both, we get our conditions.

    function allArticles( ){
    function allArticles( status=-1, id=0 ){
        var extra = status > -1 ? "where status=#status#" : "";
        extra &= id > 0 ? " and id=#id#" : "";
        return queryExecute("SELECT * FROM articles",{},{returntype:"array"});
        return queryExecute("SELECT * FROM articles #extra#",{},{returntype:"array"});
    }

Lesson 1 of 3 - Displaying Articles