Blog

ASP.NET MVC Editable Table jQuery DataTables and ASP.NET MVC integration

admin : November 6, 2011 10:15 pm : Blog

Introduction

The purpose of this article is to show how you can implement a table with the full set of data management functionalities in ASP.NET MVC using jQuery/AJAX with various plug-ins. Here is a list of the aimed functionalities:

  1. Client side pagination, filtering, sorting
  2. CRUD operations – deleting/editing/adding records
  3. Effective client-side functionalities where most of the interaction is done by AJAX

My intention is to show how you can implement these functionalities with minimal effort using a jQuery DataTables Editable plug-in and thereby easily extending DataTable CRUD functionalities.  Example of such kind of table is shown on the figure below:

datatables_edit_cell.png

All functionalities you see in the figure are pure JavaScript enchancement – on the server-side you just need to generate a pure HTML table. Everything you see in the table is implemented on the client-side using the following JavaScript call:

 

$('table#myDataTable').dataTable().makeEditable();

This line of code finds a table with id “myDataTable”, and  applies two JQuery plugins that add to the table all functionalities shown above. In the rest of the article I will show you how you can implement and customize this plugin.

This article might be considered as a second part in the series of articles that describes how to implement effective Web 2.0 interfaces with jQuery, ASP.NET MVC, and the jQuery DataTables plugin. In my previous article, I described how you can implement a DataTable with server-side pagination, filtering, and sorting which enables you to implement high-performance table operations. In this article, server-side actions are not described again, and focus is on the data management functionalities only. These two articles can help you to create effective Web 2.0 data tables with fully AJAXified functionalities.

Background

A common requirement in web projects is to create a table where besides listing data, the user should be able to edit information, and add new or delete existing records. When a fully functional data table/data grid needs to be implemented, my choice is the jQuery DataTables plug-in. This plug-in takes a plain HTML table and adds several functionalities such as pagination, ordering by column, filtering by keyword, changing the number of records that should be displayed per page, etc. All you need to do is to include a single JavaScript call:

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $('#myDataTable').dataTable();
    });  
</script>

In the example, myDataTable is the ID of the table that should be enhanced with the DataTables plug-in. Full description of the jQuery DataTables features can be found here. The picture that follows shows a plain HTML table after applying the DataTables plug-in.

datatables.png

DataTables itself provides a very good API for data manipulation (adding rows, deleting rows, etc.). However, a drawback is that you will need to learn the API functions and implement CRUD functionalities yourself because there is no out-of-the-box solution that enables you to easily implement CRUD functionalities. This might make one think of moving from DataTables to some other plug-in such as jqGrid (which is also a good plug-in, similar to DataTables) just because it has out-of-the-box configuration for CRUD functionalities. Therefore, my goal was to encapsulate the jQuery DataTables functionalities that are needed for the standard CRUD operations into a separate plug-in which adds CRUD functionalities on top of the standard set of DataTables functionalities and makes it possible for a developer to activate it as easily as possible. Code to initialize an editable data table is shown below:

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $('#myDataTable').dataTable().makeEditable();
    });  
</script>

This line of code would result in a table that allows the user to edit data by double clicking on a cell, select and delete any row in the table, and add a new record. An example of the enhanced table can be found on the live demo site. Beside this, you’ll need to create server-side code that accepts AJAX calls sent by the plug-in when the user changes some record and this article will guide you through this task.

Using the code

For illustrative purposes, we’ll use a simple ASP.NET MVC web application to list companies, delete them, add new or update existing company information. The first thing you need to do is to create a standard ASP.NET Model-View-Controller structure. There are three steps required for this setup:

  1. Creating the model classes that represent the data structure that will be shown
  2. Creating the controller class that will react on the user events
  3. Creating the view that will render data and create HTML code that is sent to the browser window

In the beginning, we’ll just display company information in a table. Then, this simple table will be enhanced with the jQuery DataTables Editable plug-in. The following JavaScript components need to be downloaded:

  1. jQuery library v1.4.4., containing standard classes used by the DataTables plug-in
  2. jQuery UI library v1.8.7., containing classes for handling dialogs
  3. jQuery DataTables plug-in v1.7.5., including the optional DataTables CSS style-sheets used for applying the default styles on the page
  4. jQuery Jeditable plug-in v1.6.2., required for inline cell editing
  5. jQuery validation plug-in v1.7., for implementation of client-side validation
  6. jQuery DataTables Editable plug-in that integrates all these mentioned plug-ins into a fully functional editable datatable.

These files should be stored in the local file system and included in the HTML page that is rendered on the client. Example of usage of these files is explained below.

Model

The model comes to a simple class containing company data. The fields that we need are company ID, name, address, and a town. The source code for the company model class is shown below:

public class Company
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Town { get; set; }
}

View

View is used to render data on the server-side and send HTML code to the browser. The example includes three different view pages that show different usage and configuration of the plug-in. There’s one layout page that will be used by all these pages. This layout page is shown below:

<!DOCTYPE html>
<html>
    <head>
        <title>Customization of Editable DataTable</title>
        <link href="@Url.Content("~/Content/dataTables/demo_table.css")" 
              rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/dataTables/demo_table_jui.css")" 
              rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" 
              rel="stylesheet" type="text/css" media="all" />
        <link href="@Url.Content("~/Content/themes/smoothness/jquery-ui-1.7.2.custom.css")" 
              rel="stylesheet" type="text/css" media="all" />
        <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" 
              type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.dataTables.min.js")" 
              type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.jeditable.js")" 
              type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery-ui.js")" 
              type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.validate.js")" 
              type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.dataTables.editable.js")" 
              type="text/javascript"></script>
        @RenderSection("head", required: false);
    </head>
    <body>
        <div id="container">
            <a href="/Company/Index">Basic Example</a>
            <a href="/Company/Ajax">Getting data with Ajax</a>
            <a href="/Company/Customization">Customization</a>
            @RenderBody()
        </div>
    </body>
</html>

This layout page does not have any presentation logic – it just includes all the necessary JavaScript files and contains links to all the pages used in this example. Page specific content will be rendered when the @RenderBody() call is executed. In addition, this layout page allows you to include custom JavaScript that is specific to the pages in the “head” section. Note that the last JavaScript file is the DataTables Editable plug-in which covers the CRUD functionalities that will be presented in this example. The layout page is not required for your projects, but it allows to simplify the views so that they contain only code that is relevant for the examples. The view that renders the table is shown in the listing below:

@{
    Layout = "~/Views/Company/JQueryDataTableEditableLayout.cshtml";
}

@section head{
        <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                $('#myDataTable').dataTable().makeEditable();
            });
        </script>
}

<div id="demo">
    <h1>Basic Example</h1>
    <table id="myDataTable" class="display">
        <thead>
            <tr>
                <th>Company name</th>
                <th>Address</th>
                <th>Town</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr id="@item.ID">
                    <td>@item.Name</td>
                    <td>@item.Address</td>
                    <td>@item.Town</td>
                </tr>
            }
        </tbody>
    </table>
    <div class="add_delete_toolbar" />
</div>

This view uses the layout page described above, and puts the initialization JavaScript in the header that initializes the data table and makes it editable. The body contains a table with a company name, address, and town. The ID of each company is placed in an ID attribute of the surrounding <tr> tag – this is a place where the DataTables Editable plug-in expects to find the ID of the record that will be edited or deleted. Also, there is a <div> element with a class “add_delete_toolbar” which tells the DataTables Editable plug-in where it should place the auto-generated add and delete buttons.

Controller

When a page is required by the user, the controller returns a company list that will be rendered in the view. Instead of a database, there is the DataRepository class that just returns a list of all the companies. An example of the controller with one action method that reacts to the /Company/Index request is shown below:

Collapse | Copy Code
public class CompanyController : Controller
{
        public ActionResult Index()
        {
            var companies = DataRepository.GetCompanies();
            return View(companies);
        }
}

When the “/Company/Index” request is sent from the client, this action method is executed and a set of all the companies from the repository is sent to the view.

The only thing you need to do is to create server-side actions that handle the add, delete, and update requests sent by the plug-in. These actions can be added as controller actions:

public class CompanyController : Controller
{
        public string DeleteData(int id){ ... }
        public string UpdateData(int id, string value, int? rowId, 
               int? columnPosition, int? columnId, string columnName){ ... }    
        public int AddData(string name, string address, string town, int? country){ ... }
}

The DeleteData action accepts the ID of the deleted row as a parameter and returns an “ok” string if the update is successful. Any other string value represents an error message that will be shown to the user.

The UpdateData action accepts the ID of the updated cell, a value entered by the user, and the position of the cell (column and row ID). The action should return text equal to the value input parameter. Any other string value represents an error message that will be shown to the user.

The AddData action has custom parameters representing all the information that should be saved when a new record is added. The given example uses the name, address, town, and country in the new company record, but in the other implementations, you will use arbitrary parameters, so you will need to create a custom form for adding a new record. The DataTables Editable plug-in handles opening your custom form in the dialog and posting form values to the server-side action shown above.

In the next section, I will explain how this plug-in is integrated in the example attached to this article.

Example – Implementation of the controller action methods

The code described in the previous sections is necessary for rendering data and initializing the DataTables Editable plug-in. Once it’s initialized, the plug-in allows you to perform the following functionalities:

  1. Updating cell values – when the user double clicks on a cell, it will be converted into a textbox and when the user finishes editing data and presses Enter, an AJAX call will be sent to the server-side.
  2. Deleting rows – when the user selects a row and presses the Delete button, an AJAX request will be sent to the server so the selected record can be deleted on the server-side.
  3. Adding a new row – when the user adds a new row, an AJAX request is sent with the information about the new record

The picture below shows the trace of AJAX calls that are sent to the server when these operations are performed by the user. The actions “DeleteData“, “AddData“, and “UpdateData” are the default AJAX URLs that are called by the plug-in and can be modified if necessary.

Ajax_trace.png

The following sections describe the implementation of the needed server-side actions that actually perform these operations on the real data.

Updating cells

Updating cells is done by using an inline editable plug-in called Jeditable. The DataTables Editable plug-in is internally configured to replace the cell content with an editable textbox when the user double clicks on the cell. The following figure shows how the user can edit data:

datatables_edit_cell.png

When the user finishes cell editing and presses Enter, the plug-in sends the AJAX call with the information about the edited value. The new cell content is sent to the server with a new value, the ID of the record, and the coordinates of the cell. The AJAX call that is sent to the server-side is shown below:

update_data_ajax_request.png

The AJAX request contains the following parameters:

  1. id of the row taken from the ID attribute of the <tr> tag that surrounds the cell that has been edited. Use this value to find a record that should be updated.
  2. value that is entered in the cell. This value should be written in the company record.
  3. columnName – name of the column (e.g., text found in the column heading). You can use this information to determine which property should be updated.
  4. rowId from the table. If 10 rows are shown per page, this will be a value between 0 and 9.
  5. columnPosition – position of the column value from 0 to the number of columns you see in the table – 1. Hidden columns are not counted. This value can be used instead of the column name to identify the property that should be updated. Use this value if names of the columns can be dynamically changed.
  6. columnId – ID of the column from 0 to the total number of columns – 1. Hidden columns are counted. This value can be used instead of the column name to identify the property that should be updated. You should use columnId instead of columnPosition if you have hidden columns in the table (either initially hidden or dynamically hidden).

You will also need a controller action that will accept the request described above, receive information sent from the plug-in, update actual data, and return response. Example:

public class CompanyController : Controller
{        
    /// <summary>Action that updates data
    /// </summary>
    /// <param name="id">Id of the record</param>
    /// <param name="value">Value that should be set</param>
    /// <param name="rowId">Id of the row</param>
    /// <param name="columnPosition">Position of the
    ///           column(hidden columns are not counted)</param>
    /// <param name="columnId">Position of the column(hidden columns are counted)</param>
    /// <param name="columnName">Name of the column</param>
    /// <returns>value if update suceed - any other value
    ///        will be considered as an error message on the client-side</returns>
    public string UpdateData(int id, string value, int? rowId, 
           int? columnPosition, int? columnId, string columnName)
    {
        var companies = DataRepository.GetCompanies();

        if (columnPosition == 0 && companies.Any(
                  c => c.Name.ToLower().Equals(value.ToLower())))
            return "Company with a name '" + value + "' already exists";
        var company = companies.FirstOrDefault(c => c.ID == id);
        if (company == null)
        {
            return "Company with an id = " + id + " does not exists";
        }
        switch (columnPosition)
        {
            case 0:
                company.Name = value;
                break;
            case 1:
                company.Address = value;
                break;
            case 2:
                company.Town = value;
                break;
            default:
                break;
        }
        return value;
    }
}

This action accepts information about the ID of the updated record, the iD of the row where the updated cell is placed, and ID, position, and name of the column where the updated cell is placed. The code is simple. The company is found by using the ID, and one of the properties of the found record is updated depending on the position of the column. Instead of the column position, column name can be used – it depends on the server-side logic. If everything is fine, the returned value should be the same as a value sent by the plug-in in the request. Otherwise, the DataTables Editable plug-in will assume that the update has failed and that the returned text is an error message that should be shown to user. Hence, to notify the plug-in that an error occurred, the only thing you need to do is to return an error message (as shown in the example).

Deleting rows

The DataTables Editable plug-in enables row selection and initializes a delete button. When the user selects a row, the delete button gets enabled, and after it’s pressed, an AJAX request with an ID of the currently selected row will be sent to the server. The ID is taken from the id attribute of the <tr> tag. The AJAX request that is sent by the plug-in to the server-side page is shown below:

delete_data_ajax.png

The server-side page should return an “ok” string if the record is successfully deleted, or an error message that should be shown to the user.

The Controller action that accepts an ID of the row that needs to be deleted and actually deletes a row is given in the following example:

Collapse | Copy Code
public class CompanyController : Controller
{
    /// <summary>
    /// Method called but plugin when a row is deleted
    /// </summary>
    /// <param name="id">Id of the row</param>
    /// <returns>"ok" if delete is successfully performed - any other
    ///    value will be considered as an error message on the client-side</returns>
    public string DeleteData(int id)
    {
        try
        {
            var company = 
                 DataRepository.GetCompanies().FirstOrDefault(c => c.ID == id);
            if (company == null)
                return "Company cannot be found";
            DataRepository.GetCompanies().Remove(company);
            return "ok";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
}

If everything is fine, an “ok” string is returned back. Any other string that is returned from the code such as “Company cannot be found” or an exception message will be shown on the client-side as an error message, and deleting will be canceled.

Adding new records

Adding a new record is a bit complicated – in this case, it is not enough just to add one action in the controller. For adding a new record, it is necessary to add an HTML form that will be used for adding a new record. This form should have the idformAddNewRow” and should contain the input elements that the user needs to populate. An example of the form is shown in the listing below:

<form id="formAddNewRow" action="#" title="Add new company">
    <label for="name">Name</label><input type="text" 
       name="name" id="name" class="required" rel="0" />
    <br />
    <label for="name">Address</label><input type="text" 
       name="address" id="address" rel="1" />
    <br />
    <label for="name">Postcode</label><input 
       type="text" name="postcode" id="postcode"/>
    <br />
    <label for="name">Town</label><input 
       type="text" name="town" id="town" rel="2" />
    <br />
    <label for="name">Country</label>
        <select name="country" id="country">
            <option value="1">Serbia</option>
            <option value="2">France</option>
            <option value="3">Italy</option>
        </select>
    <br />
</form>

When the DataTables Editable plug-in detects the Adding new record form, the “Add” button will be auto-generated. When a user presses the “Add” button, the DataTables Editable plug-in opens a form in the new dialog window where the user can enter information about the new record (the dialog is shown below).

datatables_add_new.png

This form cannot be auto-generated because I assume that in each add functionality, you will need some custom form with various elements such as textboxes, calendars, etc. Therefore, I assume that it will be easier that you add a plain HTML form that suites you best and style it, rather than use some auto-generated functionality. In this form, it is important to add rel attributes to the input elements that should be copied to the table when a record is added. The rel attributes are used by the DataTable Editable plug-in to map values of the new record with the columns in the table. In the example given above, the values that will be entered in the name, address, and town inputs will be mapped to the columns 0, 1, and 2 of the table – rel attributes are used for this mapping.

As it can be seen, OK and Cancel buttons do not need to be added in the form – the DataTables Editable plug-in adds them automatically as the last elements in the form. The form is automatically validated on the client-side using a jQuery validation plug-in. Therefore, you can add the “required”, “email”, “date”, and other CSS classes to automatically implement client-side validation. In the above example, name is marked as required field and a client-side error message will be shown if this field is not populated. You can see what validation rules can be used on the jQuery validation plug-in site. When the DataTables Editable plug-in detects the “Add new record” form, it will enable the user to add a new record via that form and post elements found in the form to the server-side. When the user presses the “OK” button, an AJAX request is sent to the server and if everything is fine, the dialog is closed and a new row is added to the table. An example of the AJAX request that is sent from the form displayed above is shown on the following figure:

add_data_ajax.png

The AJAX call sends all the values of the input elements in the form and expects to get the ID of the new row back. Once the ID is returned, the new row is added, populated with the values from the form, and the returned ID of the record is set as an ID attribute of the new row.

DataTables Editable handles common operations such as opening a dialog, posting a request to the server, closing a dialog when Cancel is pressed, and adding a row in the table if an operation is successful. The only thing that needs to be done is creating a plain HTML form as a template for adding a new record, and a server-side action that accepts information about the new record.

The Controller action that accepts the data entered in the form is shown below:

Collapse | Copy Code
public class CompanyController : Controller
{
    public int AddData(string name, string address, string town, int country)
    {
        var companies = DataRepository.GetCompanies();
        if (companies.Any(c => c.Name.ToLower().Equals(name.ToLower())))
        {
            Response.Write("Company with the name '" + name + "' already exists");
            Response.StatusCode = 404;
            Response.End();
            return -1;
        }

        var company = new Company();
        company.Name = name;
        company.Address = address;
        company.Town = town;
        companies.Add(company);
        return company.ID;
    }
}

The signature of the method depends on the form parameters – for each parameter that is posted to the server, one argument in the method should be added. As the name, address, town, and country are posted from the client, these parameters are added in the method call. The Action method returns an integer value that represents the ID of the new record. If any error occurs (such as duplicate name constraint violation as shown in the example), an error message should be returned as a response text. Also, the status code of the response should be set to some HTTP error status. The actual value is irrelevant however, it is necessary to return some of the status codes in the 4xx or 5xx family to notify the DataTables Editable plug-in that the error occurred while trying to add a record. In this case, I used a 404 error message but the actual code is irrelevant – the only thing that is needed is that the plug-in detects that the error occurred and that it shows the response text to the user.

Configuration in the Server-side proccesing mode

The DataTables plug-in can use either a row in the table as a source of data or it can be configured to use a JSON source from the server-side page. In the server-side mode, only data that should be shown on the current page is returned from the server and displayed in the table. The standard DataTables functionalities such as filtering, ordering, and pagination just forward the request to the server-side where the information is processed and returned back to the DataTables plug-in. This mode requires some server-side development but can significantly increase the performance. The DataTables Editable plug-in can detect whether the DataTables plug-in is used in server-side mode and support AJAX based functionalities. In this section, I will show you what modifications should be done in the DataTables Editable plug-in to work in this mode.

Model

In the server-side mode, the model is not changed – the same company class is used as in the previous example.

View

I have created a different view page that renders the output to match the DataTables AJAX mode. The view is shown below:

@{
    Layout = "~/Views/Company/JQueryDataTableEditableLayout.cshtml";
}

@section head{

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $('#myDataTable').dataTable({
         "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": 'TableData',
            "aoColumns": [
                             {  "sName": "ID",
                                "bSearchable": false,
                                "bSortable": false,
                                "bVisible": false
                                    },
                     { "sName": "COMPANY_NAME" },
                     { "sName": "ADDRESS" },
                     { "sName": "TOWN" }
                    ]
        }).makeEditable();
    });       
</script>
}

<div id="demo">
    <h2>Ajax example</h2>
    <table id="myDataTable" class="display">
        <thead>
            <tr>
                <th>ID</th>
                <th>Company name</th>
                <th>Address</th>
                <th>Town</th>
            </tr>
        </thead>
        <tbody> 
        </tbody>
    </table>
</div>

In the DataTables call in JavaScript are added the bServerside and sAjaxSource parameters. Also, columns are explicitly defined where you can see that the ID of the column is added as a hidden column. In the AJAX mode, you cannot easily put the ID of the record as an id attribute of the <TR> tag that surrounds a Company. Therefore, in the AJAX mode, the ID of each record that will be edited or deleted must be placed in the first hidden column of the table. The table body is empty because it is not generated on the server. Each time data is required, the DataTables plug-in calls the sAjaxSource page to get the JSON array that will be dynamically injected into the table body on the client-side. The only difference that should be done is in the “Add new row” form. As we have the first column to be the ID of the company, we need to put a matching input element with rel="0" in the form for adding a new row. The most convenient thing to do is to add this element as a hidden input without a name (so it will not be sent to the server), with some dummy value. This element is required so adding a new row in the table would not break due to the fact that the number of inputs in the form and columns in the table do not match. The value of this hidden field is irrelevant as the ID will be taken from the server and set in the table as an ID when a row is added. An example of the “Add new row” form is shown below:

Collapse | Copy Code
<form id="formAddNewRow" action="#" title="Add new company">
    <input type="hidden" id="id" name="id" value="-1" rel="0" />
    <label for="name">Name</label>
    <input type="text" name="name" id="name" class="required" rel="1" />
    <br />
    <label for="name">Address</label>
    <input type="text" name="address" id="address" rel="2" />
    <br />
    <label for="name">Postcode</label>
    <input type="text" name="postcode" id="postcode"/>
    <br />
    <label for="name">Town</label>
    <input type="text" name="town" 
         id="town" rel="3" />
    <br />
    <label for="name">Country</label>
        <select name="country" id="country">
            <option value="1">Serbia</option>
            <option value="2">France</option>
            <option value="3">Italy</option>
        </select>   
    <br />         
</form>

Controller

In my previous article, I explained how you can implement a controller to work with DataTables in server-side mode. In short, two major differences are:

  1. Controller action that is executed when the view page is requested does nothing. No model is associated to the view as data binding is not done on the server-side.
  2. An additional action that will be referenced via sAjaxSource must be implemented where all the processing is done on the server-side.

Integration of the DataTables plug-in with server-side code is not covered here, but you can find how this can be implemented in the article Integrating the jQuery DataTables plug-in into an ASP.NET MVC application. In this article, you can find how to replace client-side pagination, filtering, and ordering functionalities used in this article, with server-side actions, in order to improve the performance of DataTables.

Full customization

In the examples above, I have shown a few out of the box functionalities of the DataTable Editable plug-in that can be used without any change. However, similar to the original DataTables plug-in, the DataTables Editable plug-in allows you to configure properties of the plug-in and customize it. In this section, I will explain how this plug-in can be customized.

Setting AJAX URLs

The first thing you might want to change are URLs that will be called to update, delete, or add data. By default, if the URL of the page where the table is rendered is /Company/Index, URLs for data management operation will be /Company/UpdateData, /Company/AddData, and /Company/DeleteData. This is very convenient for ASP.NET MVC applications because these actions can be placed inside the same controller. If you have a different controller or set of views, e.g., /Employee/List or /Manager/Details, where the editable data table is placed, you will just add UpdateData, DeleteData, and AddData into the appropriate controllers and each page will call its data management action. However, you are able to completely customize data management URLs and put any URL you want. The example below shows how you can configure the DataTables Editable table to use PHP pages instead of ASP.NET MVC pages. You can put any value instead of these (other MVC pages, ASPX pages, etc.).

$('#myDataTable').dataTable().makeEditable({
                    sUpdateURL: "/Home/UpdateData.php",
                    sAddURL: "/Home/AddData.php",
                    sDeleteURL: "/Home/DeleteData.php"
                });

Configuring DOM

You saw that lot of elements such as buttons are auto-generated by the plug-in. The only thing you need to do is to define an element with class “add_delete_toolbar” that will be the placeholder for Add and Delete buttons. If you want full control over the content, you can put these buttons directly in the view page. If DataTables Editable finds that buttons already exists, new ones will not be generated and event handlers will be attached to the existing ones. The only thing you need to do is to put the expected IDs into the HTML elements you want to use so DataTables Editable can find them. The default IDs of the elements are:

  • formAddNewRow – ID of the form that will be shown in the popup dialog when a new row is added
  • btnAddNewRow – button that opens the dialog for adding a new row
  • btnAddNewRowOk – confirmation button in the Add New Row dialog
  • btnAddNewRowCancel – cancel button in the Add New Row dialog
  • btnDeleteRow – button for deleting the selected row

Note that these elements do not need to be <button> HTML elements – you can place anything you want, e.g., <a>, <span>, <input>, <img>, etc. The only requirement is that these elements have expected IDs. If you do not like these IDs, you can change them too. This is suitable if you have two different tables you enhanced with the DataTables Editable plug-in on the same page and you do not want to mix their control buttons. An example configuration of the DataTables Editable plug-in with the definition of IDs of the control buttons is shown below:

Collapse | Copy Code
$('#myDataTable').dataTable().makeEditable({
                        sAddNewRowFormId: "formAddNewCompany",
                    sAddNewRowButtonId: "btnAddNewCompany",
                    sAddNewRowOkButtonId: "btnAddNewCompanyOk",
                    sAddNewRowCancelButtonId: "btnAddNewCompanyCancel",
                    sDeleteRowButtonId: "btnDeleteCompany",
                });

To use this configuration, you will need to place elements with exactly same IDs and position them into the page wherever you like. If you don’t want a placeholder for adding Add and Delete buttons to be a div with class add_delete_toolbar, you can change this too. The configuration I frequently use to inject the buttons in the table header on the right side of “Show XXX entries per page” is shown in the example below:

Collapse | Copy Code
$('#myDataTable').dataTable().makeEditable({ 
                'sAddDeleteToolbarSelector': '.dataTables_length'
                });

The DataTables plug-in places “Show XXX entries per page” into the div with class “datatable_length“. If I put this class as a selector for the toolbar, the DataTables Editable plug-in will inject Add and Delete buttons in that div.

Customizing the error messages

If you don’t like the standard browser’s message box that is shown when an error occurs, you can change this behaviour. In the DataTables Editable initialization, you can pass your custom error function. This function should accept two parameter messages that will be shown and the action that caused an error. An example of using a custom show message function is shown in the example below:

Collapse | Copy Code
$('#myDataTable').dataTable().makeEditable({
                    fnShowError: function (message, action) {
                        switch (action) {
                            case "update":
                                jAlert(message, "Update failed");
                                break;
                            case "delete":
                                jAlert(message, "Delete failed");
                                break;
                            case "add":
                                $("#lblAddError").html(message);
                                $("#lblAddError").show();
                                break;
                        }
                    }
                });

In this example, when an error occurs when adding a new record, a message is placed in the error label with an ID “lblAddError” (the assumption is that this label is placed in the form that will be shown in the dialog and that it is initially hidden). For update and delete, error messages are used in a custom jAlert plug-in that shows a “fancy” message box instead of the standard one. You can use any other plug-in you want instead of this one. An example of implementation of custom messages can be found on this live demo site.

Configure custom editors for the columns

Editing cells using textboxes is default behaviour for the Jeditable but this plug-in enables you to use different editors for each column. As an example, in some cases, you will want to use a TextArea or select list for inline editing instead of a textbox.

If you pass aoColumns parameter to the datatable’s initialization function, you will be able to configure the editors for each column in the table. The parameter aoColumns represents an array of objects containing the properties of the inline editor. An example of the implementation of custom editors can be found in this live demo site. Configuration of the custom column editors is shown in the script below:

$('#myDataTable').dataTable().makeEditable({
    "aoColumns": [
    {
        //Empty object is used for the default editable settings
    },
    null,//null for read-only columns
    {
        indicator: 'Saving...',
        tooltip: 'Click to select town',
        loadtext: 'loading...',
        type: 'select',
        onblur: 'submit',
        data: "{'London':'London','Liverpool':'Liverpool','Portsmouth':
              'Portsmouth','Edinburgh':'Edinburgh', 'Blackburn':'Blackburn',
              'Kent':'Kent','Essex':'Essex','Oxon':'Oxon','Lothian':'Lothian',
              'West Sussex':'West Sussex','Lanarkshire':'Lanarkshire',
              'Birmingham':'Birmingham','East Sussex':'East Sussex','Surrey':'Surrey'}"
    }
]
});

The first object in the aoColumns array definition is an empty object {}. If you pass an empty object as a configuration parameter for some column, the default editor will be used. The second object in the array is a null value. This value makes the column read-only, i.e., the editable plug-in will not be applied on the cells in the second column. This is useful if you have HTML links in some cells and you do not want to allow the user to edit them.

The third element is the most interesting one. Here is placed a configuration object for the Jeditable editor that will be applied on the cells in the third column. The editor that will be used on the cells in the third column will be a select list (type: ‘select’) with the list elements defined in the data property. The inline select list that will be shown when the user click on the cells in the third column is shown in the following figure:

inline-select-list.png

The data property contains a set of value:label pairs that will be used to build a list. A label will be shown in the list and the value will be used to update the cell content and it will be sent to the server-side. Submitting the selected value happens when the user clicks on any other cell causing the onblur event. The configuration is set so that the onblur selected value should be submitted to the server (onblur:'submit'). If you do not want this behaviour, you can remove the onblur:'submit' option and place the submit:'Ok' option in the configuration. This will add a submit button with the label ‘Ok’ to the left of the select list and the value will be submitted to the server when the user presses this button. You can even use a server-side page as a data source for the list if you put the loadurl parameter instead of the data parameter. This configuration forces the the loadurl parameter to read values for the select list from the URL instead of the local data array.

Other parameters in the column configuration set the tooltip and text that will be shown while the editor is processing results using the AJAX call. The configuration parameters that can be used for the individual editor setup can be found on the Jeditable site, therefore it might be good to take a look at this site first if you are going to configure the individual editors per column.

Jeditable is av ery powerfull plugin that has a lot of plugins for custom input types so you can use date/time pickers, masked inputs, AJAX uploads, or even easily create your own editor. You can see the various input types on the Jeditable custom input demo site.

Summary

This article shows you how to create a datatable that has integrated add, edit, and delete functionalities using the jQuery Datatables Editable plug-in. This plug-in enables you to focus just on the server-side functionalities that handle data management requests and implement only code that is specific for your application. The complete example can be downloaded from above..

The plug-in with documentation is hosted here so you can take the plug-in or example of usage and include it in your project.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Leave a response »

c# – How to change appearance of TabItems in a scrolling WPF TabControl? – Stack Overflow

admin : November 5, 2011 8:26 am : Blog

I have a scrolling TabControl, using a ScrollViewer and StackPanel (with the StackPanel set as IsItemsHost=”true”). To begin with, I am working from a solution originally outlined here – Creating Scrolling Tabs Using WPF’s TabControl . At the moment it has broken links (Edit: I have tracked down one instance of his code in a forum here – How to prevent TabControl from doing multi rows?), so here is the xaml for the TabControl (does not require any further code):

<TabControlx:Name="TabControl2"Height="Auto"TabStripPlacement="Bottom"VerticalAlignment="Bottom"Template="{DynamicResource TabControlControlTemplate1}"IsSynchronizedWithCurrentItem="True">
  <TabControl.Resources>
    <Stylex:Key="TabScrollerRepeatButtonStyle"TargetType="{x:Type RepeatButton}">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate>
            <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1" Margin="1,0">
              <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Content="{TemplateBinding ContentControl.Content}"/>
            </Border>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>

    <ControlTemplatex:Key="TabControlControlTemplate1"TargetType="{x:Type TabControl}">
      <Gridx:Name="Grid"KeyboardNavigation.TabNavigation="Local">
        <Grid.ColumnDefinitions>
          <ColumnDefinitionx:Name="ColumnDefinition0"/>
          <ColumnDefinitionx:Name="ColumnDefinition1"Width="0"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinitionx:Name="RowDefinition0"Height="Auto"/>
          <RowDefinitionx:Name="RowDefinition1"Height="*"/>
        </Grid.RowDefinitions>
        <BorderGrid.Row="1"Grid.Column="0"x:Name="ContentPanel"BorderBrush="{TemplateBinding BorderBrush}"BorderThickness="0,0,1,1"KeyboardNavigation.TabIndex="2"KeyboardNavigation.TabNavigation="Local"KeyboardNavigation.DirectionalNavigation="Contained">
          <Borderx:Name="Border"BorderBrush="{TemplateBinding BorderBrush}"BorderThickness="{TemplateBinding BorderThickness}">
            <BorderBackground="{TemplateBinding Background}"x:Name="Border1">
              <ContentPresenterDataContext="{x:Null}"Margin="{TemplateBinding Padding}"x:Name="PART_SelectedContentHost"Content="{TemplateBinding SelectedContent}"ContentTemplate="{TemplateBinding SelectedContentTemplate}"ContentTemplateSelector="{TemplateBinding SelectedContentTemplateSelector}"ContentSource="SelectedContent"/>
            </Border>
          </Border>
        </Border>
        <ScrollViewerx:Name="HeaderPanel"Grid.Row="0"Grid.Column="0"HorizontalAlignment="Stretch"VerticalAlignment="Stretch"Margin="0,0,0,0"HorizontalScrollBarVisibility="Auto"VerticalScrollBarVisibility="Disabled">
          <ScrollViewer.Style>
            <StyleTargetType="{x:Type ScrollViewer}">
              <Setter Property="Template">
                <Setter.Value>
                  <ControlTemplate>
                    <Grid Margin="0,0,0,0" Grid.Row="0" Grid.Column="0"x:Name="HeaderPanel">
                      <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="20"/>
                        <ColumnDefinition Width="20"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="20"/>
                      </Grid.ColumnDefinitions>
                      <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                      </Grid.RowDefinitions>
                      <RepeatButton Grid.Column="1" Content="&lt;" Command="ScrollBar.LineLeftCommand" Style="{DynamicResource TabScrollerRepeatButtonStyle}" Visibility="{Binding Path=ComputedHorizontalScrollBarVisibility, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}"/>
                      <ScrollContentPresenter Grid.Column="2" Content="{TemplateBinding ScrollViewer.Content}"/>
                      <RepeatButton Grid.Column="3" Content="&gt;" Command="ScrollBar.LineRightCommand" Style="{DynamicResource TabScrollerRepeatButtonStyle}" Visibility="{Binding Path=ComputedHorizontalScrollBarVisibility, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}"/>
                    </Grid>
                  </ControlTemplate>
                </Setter.Value>
              </Setter>
            </Style>
          </ScrollViewer.Style>
          <StackPanelIsItemsHost="true"Orientation="Horizontal"Background="{x:Null}"KeyboardNavigation.TabIndex="1"/>
        </ScrollViewer>
      </Grid>
    </ControlTemplate>
  </TabControl.Resources>
  <TabItemx:Name="TabItem1"Header="TabItem1"/>
  <TabItemx:Name="TabItem2"Header="TabItem2"/>
</TabControl>

How might I adjust the appearance of each TabItem? For instance, I would like to place a TextBox and TextBlock inside each TabItem, with the help of a StackPanel, so that I can have renameable tabs (collapsing one or the other as appropriate).

 

I think I’ve got it (though still crossing fingers a bit — I haven’t yet dealt with Visibility of the TextBlock vs TextBox for renaming).

It is similar to Val’s solution in that I’m working in TabControl.Resources on its TabItem, but the Property concerned is HeaderTemplate and I just override the ContentPresenter in a DataTemplate. (measures to avoid replacing\destroying a lot of good behavior that comes for free with the TabControl)

 

<TabControl.Resources>
    <StyleTargetType="{x:Type TabItem}">
        <Setter Property="HeaderTemplate">
            <Setter.Value>
                <DataTemplate>
                    <ContentPresenter>
                        <ContentPresenter.Content>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{TemplateBinding Content}"/>
                                <TextBox Text="{TemplateBinding Content}"/>
                            </StackPanel>
                        </ContentPresenter.Content>
                    </ContentPresenter>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</TabControl.Resources>

via c# – How to change appearance of TabItems in a scrolling WPF TabControl? – Stack Overflow.

Leave a response »

xaml – WPF tabcontrol styling – Stack Overflow

admin : November 5, 2011 8:15 am : Blog

I’ve got a UI with a fairly standard look and feel. It has a column of icons on the left side which when clicked open a different user control on the right side. Currently I’m using separate controls for the selection icons and the usercontrol containment. I’m having strange focus issues that I am tired of trying to mitigate and am wondering if I could style a tabcontrol to look like my UI (under the assumption a tabcontrol would not have focus issues when navigating tabs).

Here is a screenshot of the basic UI. The styling is mostly about how to get the tabcontrols page selection to look like my column of icons. Anyone want to throw their hat in the ring as to how I might accomplish this with a tabcontrol?

alt text

Answer:

<TabControlTabStripPlacement="Left">     ... </TabControl>

Then you put the icons in the Header property of the TabItems and the UserControls in the Content property. That will get you about halfway there. If you want the exact same look you’ll need to retemplate the TabControl and TabItem by copying the current template (use Blend or ShowMeTheTemplate to copy the current template) and modifying it as needed. But just changing those properties will let you test whether a TabControl gets rid of your focus issues.

Edit: Here’s an example template that should be pretty close to your screenshot


It’s basically a copy of the normal TabControl with some Borders added and removed. Hope that helps.

<Style TargetType="{x:Type TabItem}">
<Setter Property="Background" Value="Transparent" />

<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">

<Border x:Name="PART_Border" Background="{TemplateBinding Background}" BorderThickness="1" BorderBrush="LightGray" Margin="2">
<ContentPresenter ContentSource="Header" Margin="2" />
</Border>

<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="PART_Border" Property="BorderBrush" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<Style TargetType="{x:Type TabControl}">
<Setter Property="TabStripPlacement" Value="Left" />
<Setter Property="Margin" Value="2" />
<Setter Property="Padding" Value="2"    />
<Setter Property="Background" Value="White" />

<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabControl}">
<Grid ClipToBounds="True" SnapsToDevicePixels="True" KeyboardNavigation.TabNavigation="Local">
<Grid.ColumnDefinitions>
<ColumnDefinition Name="ColumnDefinition0" />
<ColumnDefinition Width="0" Name="ColumnDefinition1" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" Name="RowDefinition0" />
<RowDefinition Height="*" Name="RowDefinition1" />
</Grid.RowDefinitions>

<Border x:Name="HeaderBorder"
BorderBrush="Black"
BorderThickness="1"
CornerRadius="5"
Background="#FAFAFA"
Margin="0,0,0,5">
<TabPanel IsItemsHost="True"
Name="HeaderPanel"
Panel.ZIndex="1"
KeyboardNavigation.TabIndex="1"
Grid.Column="0"
Grid.Row="0"
/>
</Border>

<Grid Name="ContentPanel"
KeyboardNavigation.TabIndex="2"
KeyboardNavigation.TabNavigation="Local"
KeyboardNavigation.DirectionalNavigation="Contained"
Grid.Column="0"
Grid.Row="1">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="5">
<ContentPresenter Content="{TemplateBinding SelectedContent}"
ContentTemplate="{TemplateBinding SelectedContentTemplate}"
ContentStringFormat="{TemplateBinding SelectedContentStringFormat}"
ContentSource="SelectedContent"
Name="PART_SelectedContentHost"
Margin="2"
SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"
/>
</Border>
</Grid>
</Grid>

<ControlTemplate.Triggers>
<Trigger Property="TabControl.TabStripPlacement" Value="Bottom">
<Setter TargetName="HeaderPanel" Property="Grid.Row" Value="1" />
<Setter TargetName="ContentPanel" Property="Grid.Row" Value="0" />
<Setter TargetName="RowDefinition0" Property="RowDefinition.Height" Value="*" />
<Setter TargetName="RowDefinition1" Property="RowDefinition.Height" Value="Auto" />
<Setter TargetName="HeaderBorder" Property="FrameworkElement.Margin" Value="0,5,0,0" />
</Trigger>
<Trigger Property="TabControl.TabStripPlacement" Value="Left">
<Setter TargetName="HeaderPanel" Property="Grid.Row" Value="0" />
<Setter TargetName="ContentPanel" Property="Grid.Row" Value="0" />
<Setter TargetName="HeaderPanel" Property="Grid.Column" Value="0" />
<Setter TargetName="ContentPanel" Property="Grid.Column" Value="1" />
<Setter TargetName="ColumnDefinition0" Property="ColumnDefinition.Width" Value="Auto" />
<Setter TargetName="ColumnDefinition1" Property="ColumnDefinition.Width" Value="*" />
<Setter TargetName="RowDefinition0" Property="RowDefinition.Height" Value="*" />
<Setter TargetName="RowDefinition1" Property="RowDefinition.Height" Value="0" />
<Setter TargetName="HeaderBorder" Property="FrameworkElement.Margin" Value="0,0,5,0" />
</Trigger>
<Trigger Property="TabControl.TabStripPlacement" Value="Right">
<Setter TargetName="HeaderPanel" Property="Grid.Row" Value="0" />
<Setter TargetName="ContentPanel" Property="Grid.Row" Value="0" />
<Setter TargetName="HeaderPanel" Property="Grid.Column" Value="1" />
<Setter TargetName="ContentPanel" Property="Grid.Column" Value="0" />
<Setter TargetName="ColumnDefinition0" Property="ColumnDefinition.Width" Value="*" />
<Setter TargetName="ColumnDefinition1" Property="ColumnDefinition.Width" Value="Auto" />
<Setter TargetName="RowDefinition0" Property="RowDefinition.Height" Value="*" />
<Setter TargetName="RowDefinition1" Property="RowDefinition.Height" Value="0" />
<Setter TargetName="HeaderBorder" Property="FrameworkElement.Margin" Value="5,0,0,0" />
</Trigger>
<Trigger Property="UIElement.IsEnabled" Value="False">
<Setter Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

via xaml – WPF tabcontrol styling – Stack Overflow.

Leave a response »

WPF change windows Close, minimize, maximize button style like windows vista on Microsoft XP

admin : November 5, 2011 8:09 am : Blog

In WPF change the windows Close, minimize, maximize button style like windows vista on Microsoft XP

It is always being difficult to have an application window running on windows XP machine, which override the style or look and feel of close, maximize, minimize and restore buttons. How great it could be, if can have some kind of glassy effect on those buttons (like vista , or windows 7).

Well, thanks to WPF and the its custom style feature, which give us an opportunity to do that very efficiently. To make the whole window’s look and feel similar to windows vista can be more tricky. We may have to set the windows style to none, border = none and bordertransparency = transparent. And then write our own buttons and write our own events to close, minimize, maximize and restoring the window.

Here in this sample, you will see this layout makeover for all those buttons, and a sample custom windows with those glassy buttons on top. The buttons will look like as shown in the image below.

In the solution, you will find the following resourcebudle files.

MaximizeButtonStyle.xaml – Contains the “ControlTemplate” to change the button style which look like maximize button in windows vista.

MinimizeButtonStyle.xaml – Contains the “ControlTemplate” to change the button style which look like minimize button in windows vista.

CloseButtonStyle.xaml – Contains the “ControlTemplate” to change the button style which look like close button in windows vista.

RestoreButtonStyle.xaml – Contains the “ControlTemplate” to change the button style which look like restore button in windows vista.

Click below to download the source code. Your comments and suggestions are always appreciated.

via In WPF change the windows Close, minimize, maximize button style like windows vista on Microsoft XP.

Leave a response »

magento common issues and fixes

admin : May 11, 2011 10:19 am : Blog

How to configure Magento to work with a new domain

There are two things you should do in order to configure Magento to work with a new domain:

  • Edit the Magento database

Go to your cPanel > phpMyAdmin. Select your Magento database from the  left menu, find the table called core_config_data and click on it.

Click the Browse tab and edit the first two fields:

web/unsecure/base_url
web/secure/base_url
by clicking the pen icon in front of each of them. Replace your old domain name with your new one and click the Go button to save the change.

  • Clear the Magento cache.

The Magento cache folder is located in your Magento installation directory > /var/cache. To clear the cache, simply delete the folder.

Many Magento issues can be fixed just by deleting the cache.

How to reset Magento Admin Password

To change your Magento admin password, go to your cPanel > phpMyAdmin, select your Magento database, click the SQL tab and paste this query:

UPDATE admin_user SET password=CONCAT(MD5(‘sGnewpass’), ‘:sG’) WHERE username=’AdminUsername’;
Note: You have to change newpass in the MD5(‘sGnewpass‘) with your new password, and change *AdminUsername* to your Magento admin username.

Execute the query by clicking the Go buttong and your password will be changed.

How to enable Search Engine Friendly URLs in Magento

To enable Search Engine Friendly URLs in Magento, you have to log in to the Magento’s administration area and click on the Configuration button. Under the System navigation menu, switch to Web page from the sub-navigation panel on the left.

When the page loads, you will see blue lines which represent closed options tablets. Click on the Search Engines Optimization tab and turn on the Use Web Server Rewrites (mark as Yes). Click on the Save Config button and your Magento SEF URLs will be enabled.

How to speed up Magento

Many Magento issues are caused by slow performance. The recommended way to speed up Magento’s performance is to enable its Compilation function.  The performance increase is between 25%-50% on page loads.

You can enable Magento Compilation from your Magento admin panel > System > Tools > Compilation.

How to redirect Magento to open through www

For SEO and usability purposes you may want to redirect your visitors to open your site only through www (http://www.yourdomain.com).

To do this in Magento, you should open the .htaccess file in the folder where your Magento is installed. In it locate the RewriteEngine on line and right after it add the following lines:

RewriteCond %{HTTP_HOST} ^yourdomain.com$ [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]

Once you do this, save the .htaccess file and log in to the Magento admin area > System > Configuration menu and from the left panel click the Web button.

Unfold the Unsecured set of options and change the Base URL option from http://yourdomain.com to http://www.yourdomain.com.

Save the changes and your Magento will start working through www.yourdomain.com only!

How to disable the Compare products functionality

You can disable the Compare products functionality in Magento by following these steps:

  • Edit app/code/core/Mage/Catalog/Helper/Product/Compare.php and change the following code:

public function getAddUrl($product)
{
return $this->_getUrl(’catalog/product_compare/add’, $this->_getUrlParams($product));
}

to

public function getAddUrl($product)
{
//return $this->_getUrl(’catalog/product_compare/add’, $this->_getUrlParams($product)); return false;
}

  • Edit ./app/design/frontend/base/default/layout/catalog.xml (if you are using a different Magento theme, enter its name instead of default) and change the following code:

<block type=”catalog/product_compare_sidebar” before=”cart_sidebar” name=”catalog.compare.sidebar” template=”catalog/product/compare/sidebar.phtml”/>

to

<!– <block type=”catalog/product_compare_sidebar” before=”cart_sidebar” name=”catalog.compare.sidebar” template=”catalog/product/compare/sidebar.phtml”/> –>

  • Flush the Magento cache from your Magento admin area > System > Cache Management.

How to set up a blog in Magento

It is not difficult to set up a blog in Magento. However, note that  functionality is not included by default and you will have to use a custom extension to add it.

You can search Magento Connect for an extension that will fully suit your needs. One of the popular free extensions that you can use is the Magento Blog – Community Edition.

All Magento extensions are installed in a similar way that is thoroughly explained in our Magento Connect Tutorial.

Once the extensions is installed, you will have one additional section in the top menu of your Magento admin area called Blog. From there you can adjust the newly-installed Blog settings, add posts etc.

How to add a Contact Us form in Magento

Magento includes contact form functionality by default. A link to a contact form can usually be found in the footer of your Magento installation.

Of course, you can add a contact form on any page. All you need to do is:

  • Log in to the administrator area.
  • Go to CMS > Pages.
  • Select the page you want to edit or create a new page.

Paste the following code using the HTML option of the WYSIWYG editor:

<!– CONTACT FORM CODE BEGIN–>
{{block type=’core/template’ name=’contactForm’ template=’contacts/form.phtml’}}
<!– CONTACT FORM CODE END–>

Save the changes and the contact form will appear on the desired page.

“Access denied” issue

As a solution to the “Access denied” issue, you should log out from the Magento admin area and then log in again.

If the above does not help, you should reset the admin privileges. This can be done through the Magento admin area > System > Permissions > Roles > Administrators.

Click on the Role Resources option from the left menu and make sure that Resource Access is set to All.

Click on the Save Role button and the permissions will be reset.

How to set a custom group of users

You can add a new group from the Magento admin area > Customers > Customer Groups > Add New Customer Group.

Once a customer registers, you can change the group he/she belongs to from the Magento admin area > Customers > Manage Customers. Click on the Edit link next to the customer and change the group from the Account Information > Customer Group. Click Save Customer.

Set the discount from Promotions > Catalog Price Rules > Add New Rule.

In the Customer Groups select the customers’ groups for which the promotion is valid. Enter the other details, set the rule actions and conditions.  Finally, click Save Rule.

The above ten tips will hopefully help you resolve at least some of the Magento issues you have faced or are about to face.

1 Comment »

Include Toolbar And Pagination in CMS page

admin : May 10, 2011 12:41 pm : Blog

Listing products on a CMS page can be painful as many people are seen asking for help on the Magento forums.

How to show the toolbar and pagination when listing products on pages other than category pages is actually quite simple. In fact it’s very simple!

The problem:

You may be using something like the code below to insert new products on your home page:

{{block type="catalog/product_new" name="home.catalog.product.new" alias="product_homepage" template="catalog/product/new.phtml"}}

Source: Magento: display new products on the home page

Or you may use this method (something like the code below) to display new products from a specific category:

{{block type=”catalog/product_list” category_id=”3″ name=”home.catalog.product.new” alias=”product_homepage” template=”catalog/product/featured.phtml”}}

Source: Magento: display new products on home page – by category!

But now you also want to include the toolbar and pagination. In Magento versions prior to 1.4, you could have used something like this:

{{block type="catalog/product_list" category_id="3" template="catalog/product/list.phtml"}}

Where the “category_id” is your category id.

In Magento 1.4, this method no longer works. The pagination and toolbar will NOT display because it is now handled in a different way.

The solution:

So here’s a simple way to display products on any CMS page and include the toolbar and pagination:

1. Go to CMS > Manage Pages and click on the page where you want to display your products.

2. Under the “Design” tab, insert the following code in the “Update Layout XML” field:

<reference name="content">
<block type="catalog/product_list" name="product_list" template="catalog/product/list.phtml">
<action method="setCategoryId"><category_id>3</category_id></action>
<block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
<block type="page/html_pager" name="product_list_toolbar_pager"/>
</block>
<action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
</block>
</reference>

Make sure to change the category id to your own id. That’s it!

More information needed? Goto http://www.dnawebagency.com/displaying-new-products-in-magento-with-pagination

Leave a response »

Best javaScript practice using jQuery

admin : April 21, 2011 12:53 am : Blog

1. Why jQuery?

jQuery is ideal because it can create impressive
animations and interactions. jQuery is simple to understand and easy to use, which
means the learning curve is small, while the possibilities are (almost) infinite.

Javascript and Best Practices

Javascript has long been the subject of many heated debates about whether it is
possible to use it while still adhering to best practices regarding accessibility
and standards compliance.

The answer to this question is still unresolved, however, the emergence of Javascript
frameworks like jQuery has provided the necessary tools to create beautiful websites
without having to worry (as much) about accessibility issues.

Obviously there are cases where a Javascript solution is not the best option. The
rule of thumb here is: use DOM scripting to enhance functionality,
not create it.

Unobtrusive DOM Scripting

While the term “DOM scripting” really just refers to the use of scripts (in this
case, Javascripts) to access the Document Object Model, it has widely become accepted
as a way of describing what should really be called “unobtrusive DOM scripting”—basically,
the art of adding Javascript to your page in such a way that if there were NO Javascript,
the page would still work (or at least degrade gracefully). In the website world,
our DOM scripting is done using Javascript.

The Bottom Line: Accessible, Degradable Content

The aim of any web producer, designer or developer is to create content that is
accessible to the widest range of audience. However, this has to be carefully balanced
with design, interactivity and beauty. Using the theories set out in this article,
designers, developers and web producers will have the knowledge and understanding
to use jQuery for DOM scripting in an accessible and degradable way; maintaining
content that is beautiful, functional AND accessible.

2. Unobtrusive DOM Scripting?

In an ideal world, websites would have dynamic functionality AND effects that degrade
well. What does this mean? It would mean finding a way to include, say, a snazzy
Javascript Web 2.0 animated sliding news ticker widget in a web page, while still
ensuring that it fails gracefully if a visitor’s browser can’t (or won’t) run Javascripts.

The theory behind this technique is quite simple: the ultimate aim is to use Javascript
for non-invasive, “behavioural” elements of the page. Javascript is used to add
or enhance interactivity and effects. The primary rules for DOM scripting follow.

Rule #1: Separate Javascript Functionality

Separate Javascript functionality into a “behavioural layer,” so that it is separate
from and independent of (X)HTML and CSS. (X)HTML is the markup, CSS the presentation
and Javascript the behavioural layer. This means storing ALL Javascript code in
external script files and building pages that do not rely on Javascript to be
usable.

For a demonstration, check out the following code snippets:


Cross in jQuery and JavaScript Coding: Examples and Best Practices
Bad
markup:

Never include Javascript events as inline attributes. This practice should be completely
wiped from your mind.

1 <a onclick="doSomething()"
href="#">Click!</a>
Tick in jQuery and JavaScript Coding: Examples and Best PracticesGood
markup:

All Javascript behaviours should be included in external script files and linked
to the document with a <script> tag in the head of the page. So, the anchor
tag would appear like this:

1 <a href="backuplink.html"
class="doSomething">Click!</a>

And the Javascript inside the myscript.js file would contain something like this:

1 ...
2
3 $('a.doSomething').click(function(){
4 // Do something
here!
5 alert('You did something, woo hoo!');
6 });
7 ...

The .click() method in jQuery
allows us to easily attach a click event to the result(s) of our selector. So the
code will select all of the <a> tags of class “doSomething” and attach a click
event that will call the function. In practice, this

In Rule #2 there is a further demonstration of how a similar end can be achieved
without inline Javascript code.

Rule #2: NEVER Depend on Javascript

To be truly unobtrusive, a developer should never rely on Javascript support to
deliver content or information. It’s fine to use Javascript to enhance the information,
make it prettier, or more interactive—but never assume the user’s browser will have
Javascript enabled. This rule of thumb can in fact be applied to any third-party
technology, such as Flash or Java. If it’s not built into every web browser (and
always enabled), then be sure that the page is still completely accessible and usable
without it.


Cross in jQuery and JavaScript Coding: Examples and Best PracticesBad
markup:

The following snippet shows Javascript that might be used to display a “Good morning”
(or “afternoon”) message on a site, depending on the time of day. (Obviously this
is a rudimentary example and would in fact probably be achieved in some server-side
scripting language).

1 <script
language
="javascript">
2 var now = new Date();
3 if(now.getHours() < 12)
4 document.write('Good
Morning!');
5 else
6 document.write('Good
Afternoon!');
7 </script>

This inline script is bad because if the target browser has Javascript disabled,
NOTHING will be rendered, leaving a gap in the page. This is NOT graceful degradation.
The non-Javascript user is missing out on our welcome message.

Tick in jQuery and JavaScript Coding: Examples and Best PracticesGood
markup:

A semantically correct and accessible way to implement this would require much simpler
and more readable (X)HTML, like:

1 <p title="Good Day Message">Good Morning!</p>

By including the “title” attribute, this paragraph can be selected in jQuery using
a selector (selectors
are explained later in this article
) like the one in the following Javascript
snippet:

1 var now =
new
Date();
2 if(now.getHours() >= 12)
3 {
4 var
goodDay = $('p[title="Good
Day Message"]'
);
5 goodDay.text('Good Afternoon!');
6 }

The beauty here is that all the Javascript lives in an external script file and
the page is rendered as standard (X)HTML, which means that if the Javascript isn’t
run, the page is still 100% semantically pure (X)HTML—no Javascript cruft. The only
problem would be that in the afternoon, the page would still say “Good morning.”
However, this can be seen as an acceptable degradation.

Rule #3: Semantic and Accessible Markup Comes First

It is very important that the (X)HTML markup is semantically structured. (While
it is outside the scope of this article to explain why, see the links below for
further reading on semantic markup.) The general rule here is that if the page’s
markup is semantically structured, it should follow that it is also accessible to
a wide range of devices. This is not always true, though, but it is a good rule
of thumb to get one started.

Semantic markup is important to unobtrusive DOM scripting because it shapes the
path the developer will take to create the DOM scripted effect. The FIRST step in
building any jQuery-enhanced widget into a page is to write the markup and make
sure that the markup is semantic. Once this is achieved, the developer can then
use jQuery to interact with the semantically correct markup (leaving an (X)HTML
document that is clean and readable, and separating the behavioural layer).


Cross in jQuery and JavaScript Coding: Examples and Best PracticesTerrible
markup:

The following snippet shows a typical list of items and descriptions in a typical
(and terribly UNsemantic) way.

01 <table>
02 <tr>
03 <td onclick="doSomething();">First Option</td>
04 <td>First
option description</
td>
05 </tr>
06 <tr>
07 <td onclick="doSomething();">Second Option</td>
08 <td>Second
option description</
td>
09 </tr>
10 </table>

Cross in jQuery and JavaScript Coding: Examples and Best PracticesBad markup:

The following snippet shows a typical list of items and descriptions in a more semantic
way. However, the inline Javascript is far from perfect.

1 <dl>
2 <dt onclick="doSomething();">First Option</dt>
3 <dd>First option description</dd>
4 <dt onclick="doSomething();">Second Option</dt>
5 <dd>Second option description</dd>
6 </dl>

Tick in jQuery and JavaScript Coding: Examples and Best PracticesGood markup:

This snippet shows how the above list should be marked up. Any
interaction with Javascript would be attached at DOM load using jQuery, effectively
removing all behavioural markup from the rendered (X)HTML.

1 <dl
id
="OptionList">
2 <dt>First Option</dt>
3 <dd>First option description</dd>
4 <dt>Second Option</dt>
5 <dd>Second option description</dd>
6 </dl>

The <id> of “OptionList” will enable us to target this particular definition
list in jQuery using a selector—more
on this later
.

3. Understanding jQuery for Unobtrusive DOM Scripting

This section will explore three priceless tips and tricks for using jQuery to implement
best practices and accessible effects.

Understanding Selectors: the Backbone of jQuery

The first step to unobtrusive DOM scripting (at least in jQuery and Prototype) is
using selectors. Selectors can (amazingly) select an element out of the DOM tree
so that it can be manipulated in some way.

If you’re familiar with CSS then you’ll understand selectors in jQuery; they’re
almost the same thing and use almost the same syntax. jQuery provides a special
utility function to select elements. It is called $.

A set of very simple examples of jQuery selectors:
1 $(document); // Activate jQuery for
object
2 $('#mydiv')
// Element with ID "mydiv"
3 $('p.first')
// P tags with class first.
4 $('p[title="Hello"]') // P tags with title "Hello"
5 $('p[title^="H"]') // P tags title starting with H
So, as the Javascript comments suggest:
  1. $(document);The first option will apply the jQuery library methods to a DOM object (in this
    case, the document object).
  2. $(‘#mydiv’)The second option will select every <div> that has the <id> attribute
    set to “mydiv”.
  3. $(‘p.first’)The third option will select all of the <p> tags with the class of “first”.
  4. $(‘p[title="Hello"]‘)This option will select from the page all <p> tags that have a title of “Hello”.
    Techniques like this enable the use of much more semantically correct (X)HTML markup,
    while still facilitating the DOM scripting required to create complex interactions.
  5. $(‘p[title^="H"]‘)This enables the selection of all of the <p> tags on the page that have a
    title that starts with the letter H.
These examples barely scratch the surface.

Almost anything you can do in CSS3 will work in jQuery, plus many more complicated
selectors. The complete list of selectors is well documented on the
jQuery Selectors documentation page
. If you’re feeling super-geeky, you
could also read the CSS3 selector specification
from the W3C.

Get ready. 

$(document).ready()

Traditionally Javascript events were attached to a document using an “onload” attribute
in the <body> tag of the page. Forget this practice. Wipe it from your mind.

jQuery provides us with a special utility on the document object, called “ready”,
allowing us to execute code ONLY after the DOM has completely finished loading.
This is the key to unobtrusive DOM scripting, as it allows us to completely separate
our Javascript code from our markup. Using $(document).ready(), we
can queue up a series of events and have them execute after the DOM is initialized.

This means that we can create entire effects for our pages without changing the
markup for the elements in question.

Hello World! Why $(document).ready() is SO cool

To demonstrate the beauty of this functionality, let’s recreate the standard introduction
to Javascript: a “Hello World” alert box.

The following markup shows how we might have run a “Hello World” alert without jQuery:


Cross in jQuery and JavaScript Coding: Examples and Best Practices
Bad markup:
1 <script
language
="javascript">
2 alert('Hello World');
3 </script>

Tick in jQuery and JavaScript Coding: Examples and Best Practices
Good markup:

Using this functionality in jQuery is simple. The following code snippet demonstrates
how we might call the age-old “Hello World” alert box after our document has loaded.
The true beauty of this markup is that it lives in an external Javascript file.
There is NO impact on the (X)HTML page.

1 $(document).ready(function()
2 {
3 alert('Hello World');
4 });
How it works

The $(document).ready() function takes a function as its argument. (In this case,
an anonymous function is created inline—a technique that is used throughout the
jQuery documentation.) The function passed to $(document).ready() is called after
the DOM has finished loading and executes the code inside the function, in this
case, calling the alert.

Dynamic CSS Rule Creation

One problem with many DOM scripting effects is that they often require us to hide
elements of the document from view. This hiding is usually achieved through CSS.
However, this is less than desirable. If a user’s browser does not support Javascript
(or has Javascript disabled), yet does support CSS, then the elements that
we hide in CSS will never be visible, since our Javascript interactions will not
have run.

The solution to this comes in the form of a plugin for jQuery called
cssRule
, which allows us to use Javascript to easily add CSS rules to the
style sheet of the document. This means we can hide elements of the page using CSS—however
the CSS is ONLY executed IF Javascript is running.


Cross in jQuery and JavaScript Coding: Examples and Best Practices
Bad markup:
01 HTML:
02 <h2>This
is a heading</
h2>
03 <p class="hide-me-first">
04 This is some information about the heading.
05 </p>
06
07 CSS:
08 p.hide-me-first
09 {
10 display: none;
11 }

Assuming that a paragraph with the class of “hide-me-first” is going to first be
hidden by CSS and then be displayed by a Javascript after some future user interaction,
if the Javascript never runs the content will never be visible.


Tick in jQuery and JavaScript Coding: Examples and Best Practices
Good markup:
01 HTML:
02 <h2>This
is a heading</
h2>
03 <p class="hide-me-first">
04 This is some information about the heading.
05 </p>
06
07 jQuery Javascript:
08 $(document).ready(function{
09 jQuery.cssRule("p.hide-me-first",
"display", "none");
10 });

Using a $(document).ready() Javascript here to hide the paragraph element means
that if Javascript is disabled, the paragraphs won’t ever be hidden—so the content
is still accessible. This is the key reason for runtime, Javascript-based, dynamic
CSS rule creation.

4. Conclusion

jQuery is an extremely powerful library that provides all the tools necessary to
create beautiful interactions and animations in web pages, while empowering the
developer to do so in an accessible and degradable manner.

This article has covered:

  1. Why unobtrusive DOM scripting is so important for accessibility,
  2. Why jQuery is the natural choice to implement unobtrusive DOM scripting effects,
  3. How jQuery selectors work,
  4. How to implement unobtrusive CSS rules in jQuery.

5. Further Reading

Further Reading: jQuery and JavaScript Practices

  1. jQuery Web Site: How
    jQuery Works
    and Tutorials 

    John Resig + Other Contributors

    One of jQuery’s true strengths is the documentation provided by John Resig and his
    team.


  2. 51 Best jQuery Tutorials and Examples

  3. Easy As Pie: Unobtrusive JavaScript
  4. Seven
    Rules of Unobtrusive JavaScript
  5. Learning jQuery
  6. Visual jQuery

  7. jQuery Tutorials For Designers
  8. jQuery For DesignersjQuery for Designers: learn how easy it is to apply web interaction using jQuery.
  9. 15 Days Of jQueryjQuery tutorials and example code that takes you from zero to hero in no time flat.

  10. 15 Resources To Get You Started With jQuery From Scratch

  11. The Seven Rules Of Pragmatic Progressive Enhancement
  12. The Behaviour Layer SlidesJeremy Keith

    Great slide notes giving a quick rundown on unobtrusive Javascripting.

  13. A List Apart:
    Behavioral Separation 

    Jeremy Keith

    A more in-depth explanation of the idea of separating Javascript into an unobtrusive
    “behavioural” layer.

  14. Unobtrusive JavaScript with
    jQuery
     

    Simon Willison

    A great set of slides about using jQuery unobtrusively. Also, finishes with a wonderful
    summary of jQuery methods and usage.

Further Reading: Semantic Markup

  1. Wikipedia: Definition of SemanticsIt’s worth understanding the idea of semantics in general prior to trying to wrap
    one’s head around the concept of semantic markup.
  2. Who cares about
    semantic markup?
     

    Dave Shea

    Dave Shea explores the benefits of semantic markup and

  3. Standards don’t
    necessarily have anything to do with being semantically correct
     

    Jason Kottke

    Kottke discusses the differences between standards compliance and semantic markup.

  4. CSS3 selector specificationW3C

    The complete specification for CSS3 selectors (most of which work perfectly in jQuery
    selectors also). This is great reading for anyone who likes to keep up to date with
    best practices and standards compliance.

Leave a response »

Backlinks : the best practise for seo

admin : April 20, 2011 3:14 pm : Blog

A quality backlink pointing to your site should be in the same category and relevant in content to your website. The page where your link is located should be indexed by Google and the page should also have a Google page rank. The webpage where your link is located should also contain no more than 30 other out-going links to other websites. Link pages with more than 30 out-going links are less relevant to the search engines. Having your link posted on this type of webpage can affect your search engine rankings in a negative way. Other excellent techniques of acquiring backlinks are directory submissions, posting articles, blogs and forums.

For directory submissions select the proper directory category and take a look at how many other websites are contained in the category where your link would be posted, if you can manage to get on the first or second page of the listings, this is a quality backlink. Also look at the Google page rank of the landing page for your link. If the page has a Google page rank this is also a quality backlink.

Stay within your category, relevant content is very important to the search engines. Write an article preferably relevant in content to your website and submit the article to high quality article directories. Blogs are an excellent way to get quality one-way backlinks, Blog sites also receive tons of traffic, which in turn give your site more exposure. Posting your link on forum pages is also an efficient method of aquiring backlinks instantly.

Backlinks to avoid would be a zero page ranked webpage, especially if the home page has a zero page rank. Links posted within framed webpages which will also steal your traffic. Especially avoid link farms, webpages which contain more than 100 unrelated outgoing links, This type of link page is frowned upon by many major search engines. Avoid Webpages with mirror sites containing the exact same content with a different URL, also pages that utilize redirects and URL cloaking. Never post your link on a webpage that contains a “no follow” or “no index” robots meta tag within the source code. Dynamic websites with question marks in the URL should be avoided because they are not always indexed by the search engines.

Avoid posting your link on a page that opens very slow or contains mostly ads and flash banners. Try not to aquire or purchase great numbers of backlinks in a short period of time, backlinks should be accumulated gradually. Also avoid webpages and directories that list their results in alphabetical order, as their database increases your link could be moved to a less relevant page with less pagerank. Quality backlinks are one of the most important factors involved in the process of acheiving high search engine ranking.

Leave a response »

keyword for better SEO

admin : April 20, 2011 12:02 am : Blog
Keyword research, finding the right keywords for your website or product, is one of the fundamental activities in SEO.

The keywords you use to promote your website effectively selects what people will be visiting your website and you better make sure this is people interested in buying your products and services!
If you sell your own product the type of visitor will determine your conversion rate and visitor value. If you use AdSense on your website the type of visitor will determine your CPM. If you sell advertising directly the type of visitor will determine how long people are staying on your website which affects your page view statistics.

The keywords you use to promote your website directly determines the level of income you will have from your website.

How To Choose Keywords
Fist of all you need to have an idea of what products or services your are going to sell. At this point I’ll just assume you already know that.
Now you start by making a list of all keywords related to you main product or service by brainstorming. Just write down everything you can think of, here’s a list to get your started.

  • Brand names
  • Who is using the product (dentist,webmaster, mothers etc)
  • Where is the product used (home, office, underwater, on website etc)
  • Related products (soap – shampoo, car – insurance, hosting – domain names)
  • Season (summer, Christmas, harvest etc)
  • Product features (low noise, easy to use, cheap, high availability, tasty, blue)
When you have a list of 50-200 keywords you are ready for the next step which is keyword tools.

Keywords tools helps you find synonyms and related keywords that you didn’t think about. They also help you determine if a keyword is likely to bring in paying customers or just browsers. And finally they help you determine the level of SEO competition for a keyword.

The fist tool to use is the Google keyword tool which is free and uses the Google index to find relevant keywords. The Google keyword tool tells you exactly what people are searching for on Google, it lets you know what people are interested in and in great detail.

As en example I type in the keyword “add url” into the box I quickly find out that there is several types of “add url” searched for.

  • directory add url
  • search engine add url
  • seo add url

There is also some synonyms for add url

  • submit url
  • adding url
  • register url
  • add link

In my case as I run a search engine I might want to concentrate on the “search engine add url” and “seo add url”. I also want to use the variations “submit url” and “add link” and probably also “search engine submit url” and “search engine add link”

As you see there is endless variations and you should now write down all the keyword that is relevant to your business and has some level of traffic. Use Excel or the free alternative OpenOffice.org, to easily keep track of your keyword lists.

Now that you have the keywords you need to find out the competition. If you are just starting out you don’t want to take on a big competitor head on, instead try finding areas (keywords) that you competitor is neglecting and with those.

For every keyword in your list type in this at Google

all in title:your keywords

Replace “your keywords” with your actual keyword phrase.
This query returns the sites that have your keyword phrase in the title of the webpage. Note the number of search results returned and write it down in your Excel or OpenOffice spreadsheet This is a rough indicator of the level of competition for that keyword.

And yes I know this is a lot of work so you might want to start with your most important keywords and continue with the rest later. (There’s tools to make this task easier but they are not free so I’ll tell you about them later…)

You now need to decide what page on your website is going to target what keyword. No single page should target more than two or in some cases three keywords/phrases, otherwise you have a loss of focus and the page will not be effective for sales or for SEO.

Finally you need to decide where to start. What pages you are going to build first and what keywords to optimize for first. A good idea is to start with the EASIEST keywords with the least amount of competition.
Sure you are not going to get a lot of traffic with these keywords, but you can expect to get a #1 Google ranking fairly quickly and with that you’ll get some visitors and much needed feedback on you website and marketing message.

You’ll also start generating some cash to help you along.

When you have mastered the easy keywords you just go on to the medium competition ones, and then you have those at #1 go on with the tough ones.

Now you probably think that this is a lot of work, and it is! But choosing the right keywords and target market can mean a ten fold increase in income ones the traffic is starting to flow.

And as I said earlier there’s tools to make your work easier.

I’ll end with a quick recap of what to do

  • Brainstorm initial keyword list based on your experience
  • Use Google search, Market Samurai or NicheBotX to evaluate the competition for the keywords (this is where the tools save a lot of time)
  • Implement easy keywords and optimize until you have Google #1 listings
  • Implement medium competition keywords and optimize until you have Google #1 listings
  • Implement tough competition keywords and optimize until you have Google #1 listings
  • At this point you are making money
Now get to work!
Leave a response »

12 wordpress tricks

admin : April 19, 2011 10:12 pm : Blog

Too many requests to write something on wordpress. Just thought it would be nice to make a list of useful WordPress tricks and you are probably already using some of them. As you already know WordPress is one of the most popular blog platforms these days and it has grown so powerful that you can use it also use as Content Management System (CMS).

<?php endwhile; ?>

You’ll notice these two are very similar so what ever you feel like using, i personally use the first one links and the second one for content. I’ve used it in my “Tabbed Featured Post” tutorial, click here to see how it looks like.

The php solution

 
<?php $i=1; ?>

<?php while (have_posts()) : the_post(); ?>      

<?php if ($i == 1) { ?>
<div id="post-<?php the_ID(); ?>" class="featured">

      featured content
</div>

<?php } else { ?>
<div id="post-<?php the_ID(); ?>">

      rest of content
</div>

<!-- post -->
<?php } ?>       

<?php $i++; ?>

<?php endwhile; ?>

I think it’s pretty much clear, it changed first post into a different div style (you can use here what ever you want of course). I’ve used this in my Solemnity free WordPress theme and if you would like to see how it looks click here for demo page. The only thing i don’t like about this way is that your main loop in this case has to be in seperate div, you know you can’t have anything between featured post and rest of posts (for example sidebar etc…) like here on Stylized Web. So becarefull how you will code it into html first.

Include a specific file

 
<?php include (TEMPLATEPATH . '/sidebar2.php'); ?>

If you need to include some other file than <?php get_sidebar(); ?> for example different sidebar or footer file etc…

Conditional Tags

 
<?php
 if ( is_front_page() ) { include (TEMPLATEPATH . '/home1.php'); }

 else { include (TEMPLATEPATH . '/rest.php'); }
 ?>

Don’t think it needs some explanation, this also could be used for featured content/post and here are some other Conditional Tags:

 
is_home(), is_category(), is_archive(), is_search(), is_single(), is_date(), is_404(), etc...

Reverse post order

 
In your index.php file, look for this bit of code:

<?php if(have_posts()) : ?><?php while(have_posts()) : the_post(); ?>

Right before that line, add this code:

<?php query_posts($query_string . “&order=ASC”) ?>

If you are the old-fashion guy and like the old ones on the top:

wp_specialchars()
 
Bad code used in title tags or search templates:
<?php echo $s; ?>

as it allows malicious code injection.

You should use this one
<?php echo wp_specialchars($s, 1); ?>

Reverse comment order

 
<?php $comments = array_reverse($comments, true); ?>
   <?php foreach ($comments as $comment) : ?>

   		content here
   <?php endforeach; ?>

Exclude first posts/post

 
<?php $posts=query_posts($query_string . 'posts_per_page=10&offset=2'); while (have_posts()) : the_post(); ?>

this will exclude first two posts
<?php endwhile; ?>
Leave a response »