<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Superdit.com &#187; Codeigniter</title>
	<atom:link href="http://superdit.com/category/codeigniter/feed/" rel="self" type="application/rss+xml" />
	<link>http://superdit.com</link>
	<description>blogging, design, tech, and web</description>
	<lastBuildDate>Sat, 31 Mar 2012 20:40:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Simple Ajax Pagination With JQuery and Codeigniter</title>
		<link>http://superdit.com/2011/11/22/simple-ajax-pagination-with-jquery-and-codeigniter/</link>
		<comments>http://superdit.com/2011/11/22/simple-ajax-pagination-with-jquery-and-codeigniter/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 01:41:31 +0000</pubDate>
		<dc:creator>aditia rahman</dc:creator>
				<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[snippet]]></category>

		<guid isPermaLink="false">http://superdit.com/?p=9336</guid>
		<description><![CDATA[Codeigniter pagination class is really useful for me, it help to cut the repetitive task when we are creating pagination with large data, today I want to share a little of my thought, using codeigniter pagination class with ajax jquery. Here I show with a simple codeigniter code.  This post only show the code example,<a href="http://superdit.com/2011/11/22/simple-ajax-pagination-with-jquery-and-codeigniter/" class="read-more">Continue Reading</a>]]></description>
			<content:encoded><![CDATA[<p>Codeigniter pagination class is really useful for me, it help to cut the repetitive task when we are creating pagination with large data, today I want to share a little of my thought, using codeigniter pagination class with ajax jquery. Here I show with a simple codeigniter code.  This post only show the code example, cause i don&#8217;t think it necessary to provide a downloadable code.</p>
<p style="text-align: center;"><a title="Simple Ajax Pagination With JQuery and Codeigniter" href="http://superdit.com/2011/11/22/simple-ajax-pagination-with-jquery-and-codeigniter/"><img class="size-full wp-image-9343" title="codeigniter ajax pagination jquery" src="http://superdit.com/wp-content/uploads/2011/11/ci_ajax_pagination_jquery.jpg" alt="codeigniter ajax pagination jquery" width="500" height="56" /></a></p>
<h6>Controller</h6>
<p>Here are the controller, to make it easier the data in this example using a static array variable, so it very easy for us to get the data by the array index, and we need to load the url helper and of course the pagination library.<span id="more-9336"></span></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {

  public function index($start = 0) {
    $data_paging = array('John 1', 'John 2', 'John 3', 'John 4',
      'John 5', 'John 6', 'John 7', 'John 8', 'John 9', 'John 10',
      'John 11', 'John 12', 'John 13', 'John 14', 'John 15', 'John 16',
      'John 17', 'John 18', 'John 19', 'John 20', 'John 21', 'John 22',
      'John 23', 'John 24', 'John 25', 'John 26', 'John 27', 'John 28',
      'John 29', 'John 30', 'John 31', 'John 32', 'John 33', 'John 34',
      'John 35', 'John 36', 'John 37', 'John 38', 'John 39', 'John 40',
      'John 41', 'John 42', 'John 43', 'John 44', 'John 45', 'John 46',
      'John 47', 'John 48', 'John 49', 'John 50', 'John 51', 'John 52',
      'John 53', 'John 54');

    $this-&gt;load-&gt;helper('url');
    $this-&gt;load-&gt;library('pagination');

    $config['base_url']   = site_url('user/index');
    $config['total_rows'] = count($data_paging);
    $config['per_page']   = 5;

    $data['user'] = array();

    for ($i=$start; $i&lt;$start+$config['per_page']; $i++) {
      if (isset($data_paging[$i])) {
        $data['user']['name'][] = $data_paging[$i];
      }
    }

    $this-&gt;pagination-&gt;initialize($config);
    $data['pagination'] = $this-&gt;pagination-&gt;create_links();

    if ($this-&gt;input-&gt;post('ajax')) {
      $this-&gt;load-&gt;view('user/ajax_index', $data);
    } else {
      $this-&gt;load-&gt;view('user/index', $data);
    }
  }
}

?&gt;
</pre>
<h6>View</h6>
<p>The jquery code I added on the top of the page, and these are where the idea lies, put the pagination content on some div element with unique id, and with jquery you can applied the click function on each pagination link. The content that will be updated is div#content you can add a loading message by your self, the ajax content will update not only the data but the pagination too.</p>
<pre class="brush: php; title: ; notranslate">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;header&gt;
  &lt;title&gt;CodeIgniter Ajax Jquery Pagination&lt;/title&gt;
  &lt;script src=&quot;&lt;?php echo base_url(); ?&gt;assets/js/jquery-1.6.4.min.js&quot;&gt;&lt;/script&gt;
  &lt;script&gt;
  $(function() {
    applyPagination();

    function applyPagination() {
      $(&quot;#ajax_paging a&quot;).click(function() {
        var url = $(this).attr(&quot;href&quot;);
        $.ajax({
          type: &quot;POST&quot;,
          data: &quot;ajax=1&quot;,
          url: url,
          beforeSend: function() {
            $(&quot;#content&quot;).html(&quot;&quot;);
          },
          success: function(msg) {
            $(&quot;#content&quot;).html(msg);
            applyPagination();
          }
        });
        return false;
      });
    }
  });
  &lt;/script&gt;
&lt;/header&gt;
&lt;body&gt;
&lt;div id=&quot;content&quot;&gt;
  &lt;div id=&quot;data&quot;&gt;
    &lt;?php foreach($user['name'] as $u): ?&gt;
        &lt;div&gt;&lt;?php echo $u; ?&gt;&lt;/div&gt;
    &lt;?php endforeach; ?&gt;
  &lt;/data&gt;

  &lt;div id=&quot;ajax_paging&quot;&gt;
    &lt;?php echo $pagination; ?&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h6>Ajax View</h6>
<pre class="brush: php; title: ; notranslate">
&lt;div id=&quot;data&quot;&gt;
  &lt;?php foreach($user['name'] as $u): ?&gt;
      &lt;div&gt;&lt;?php echo $u; ?&gt;&lt;/div&gt;
  &lt;?php endforeach; ?&gt;
&lt;/data&gt;

&lt;div id=&quot;ajax_paging&quot;&gt;
  &lt;?php echo $pagination; ?&gt;
&lt;/div&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://superdit.com/2011/11/22/simple-ajax-pagination-with-jquery-and-codeigniter/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Codeigniter Layout Library For Autoload Frequently Used Views</title>
		<link>http://superdit.com/2011/05/02/codeigniter-layout-library-for-autoload-frequently-used-views/</link>
		<comments>http://superdit.com/2011/05/02/codeigniter-layout-library-for-autoload-frequently-used-views/#comments</comments>
		<pubDate>Mon, 02 May 2011 02:33:54 +0000</pubDate>
		<dc:creator>aditia rahman</dc:creator>
				<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[layout]]></category>
		<category><![CDATA[library]]></category>

		<guid isPermaLink="false">http://superdit.com/?p=6399</guid>
		<description><![CDATA[I came up with idea how to automatically load most used layout in Codeigniter, basically I came from CakePHP that automated all default layout, in this case we can call it views part of MVC, when creating codeingniter application usually I follow the documentation when load some views from controller, something like this code Or<a href="http://superdit.com/2011/05/02/codeigniter-layout-library-for-autoload-frequently-used-views/" class="read-more">Continue Reading</a>]]></description>
			<content:encoded><![CDATA[<p>I came up with idea how to automatically load most used layout in Codeigniter, basically I came from CakePHP that automated all default layout, in this case we can call it views part of MVC, when creating codeingniter application usually I follow the documentation when load some views from controller, something like this code</p>
<pre class="brush: php; title: ; notranslate">
$data['page_title'] = 'Your title';
$this-&gt;load-&gt;view('header');
$this-&gt;load-&gt;view('menu');
$this-&gt;load-&gt;view('content', $data);
$this-&gt;load-&gt;view('footer');
</pre>
<p>Or the worse before this sometimes I include the <em>header </em>and <em>footer </em>directly on the view file, well these method really wasting time, an make the code on the views not really well organized.<span id="more-6399"></span></p>
<p>This post is my little idea to automatically load most used layout part in Codeigniter using our custom library, Lets get through the code, first create a library file in <em>application/libraries/</em> for example <strong>My_Layout.php</strong>, and these all the code for the library</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

class MY_Layout extends CI_Controller {

    public $header = 'header';
    public $footer = 'footer';

    public function content($views = '', $data = '')
    {
        // load header
        if ($this-&gt;header)
        {
            $this-&gt;load-&gt;view($this-&gt;header, $data);
            $data = '';
        }

        // load content, can be more than one views
        if (is_array($views))
        {
            foreach ($views as $view)
            {
                $this-&gt;load-&gt;view($view, $data);
                $data = '';
            }
        }
        else
        {
            $this-&gt;load-&gt;view($views, $data);
        }

        // load footer
        if ($this-&gt;footer)
        {
            $this-&gt;load-&gt;view($this-&gt;footer);
        }
    }
}
</pre>
<p>Basically this library just manipulating the default view function, I set <em>$header</em> and <em>$footer</em> attributes as values that most common used name, but you can change it on the fly, the content function load three main view, first the header, we can set the header to FALSE if do not wan to load it, and if the header load first the dynamic data that came from controller, loaded too, in case we need a dynamic data on the header. Second, the content, this section can be consist more than one views, and the last is footer, similar to header it can be loaded or not.</p>
<p><strong>Sample Usage</strong></p>
<p>This is the sample usage in controller, using single view.<strong><br />
</strong></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

class User extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this-&gt;load-&gt;library('MY_Layout');
    }

    public function test()
    {
        $data['title'] = 'dynamic_string';

        $this-&gt;my_layout-&gt;content('user/test', $data);
    }
}
</pre>
<p><strong>Using More Than One Views</strong></p>
<p>To use two or more layout you can assign the views as array</p>
<pre class="brush: php; title: ; notranslate">
$data['title'] = 'dynamic_string';
$views = array(
    'menu' =&gt; 'menu',
    'content' =&gt; 'user/test'
);

$this-&gt;my_layout-&gt;content($views, $data);
</pre>
<p><strong>Header &amp; Footer</strong></p>
<p>You can set your own header and footer by directly set the its properties, to your header value, or maybe just set to FALSE to turn the header or footer off.</p>
<pre class="brush: php; title: ; notranslate">
$this-&gt;my_layout-&gt;header = 'user/custom_user_header';
// or turn off header
$this-&gt;my_layout-&gt;header = FALSE;
</pre>
<p>That&#8217;s all hope that can give you some idea to start with, or maybe you can give some more features to this library to make it better, and easy to use.</p>
]]></content:encoded>
			<wfw:commentRss>http://superdit.com/2011/05/02/codeigniter-layout-library-for-autoload-frequently-used-views/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>[Opinion] Why PHP Developers Choose CodeIgniter</title>
		<link>http://superdit.com/2011/03/28/opinion-why-php-developers-choose-codeigniter/</link>
		<comments>http://superdit.com/2011/03/28/opinion-why-php-developers-choose-codeigniter/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 04:09:44 +0000</pubDate>
		<dc:creator>aditia rahman</dc:creator>
				<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[opinion]]></category>

		<guid isPermaLink="false">http://superdit.com/?p=4073</guid>
		<description><![CDATA[Codeigniter is one of the most popular php framework out there, that have been used by many php developers around the world. This post is just my own opinion from my technical experience while using codeigniter. This graphic below is taken from google trends to compare codeigniter search popularity, than any other popular php framework.<a href="http://superdit.com/2011/03/28/opinion-why-php-developers-choose-codeigniter/" class="read-more">Continue Reading</a>]]></description>
			<content:encoded><![CDATA[<p>Codeigniter is one of the most popular php framework out there, that have been used by many php developers around the world. This post is just my own opinion from my technical experience while using codeigniter. This graphic below is taken from <a title="codeigniter, cakephp, zend framework, symfony google trends" href="http://www.google.co.id/trends?q=codeigniter%2C+cakephp%2C+zend+framework%2C+symfony&amp;ctab=0&amp;geo=all&amp;date=all&amp;sort=0" target="_blank">google trends</a> to compare codeigniter search popularity, than any other popular php framework.</p>
<p><img class="alignnone size-full wp-image-5829" title="codeigniter, cakephp, zend framework, symfony google trend" src="http://superdit.com/wp-content/uploads/2011/03/Google-Trends_-codeigniter-cakephp-zend-framework-symfony2.png" alt="codeigniter, cakephp, zend framework, symfony google trend" width="540" height="276" /></p>
<p>The first php framework I use is <a href="http://cakephp.org" target="_blank">cakephp</a>, it has a lot more features than codeigniter, very detail documentation too, for the first time it will take some time to understanding, exploring the features and find some other reference online.<span id="more-4073"></span></p>
<p>Below I mention some my opinion why people choose codeigniter, some may show it lack of features, but behind the lack of features, codeigniter can be use to get an  easy understanding of php framework, and the most important thing is to  get the job done as soon as possible. <em>please note that this reason maybe for a who are new with php framework</em></p>
<h6>1) Do Not Have Command Line</h6>
<p>Most of php framework come a command line feature, I haven&#8217;t fell the benefit command line in the real project, but <a title="Building CLI Apps With Symfony Console Component" href="http://dev.umpirsky.com/building-cli-apps-with-symfony-console-component/" target="_blank">this article</a> will help you to get an idea why command line is useful, my point is not much web application need to have command line.</p>
<h6>2) Do Not Have ORM</h6>
<p><a title="Object Relational Mapping Wikipedia" href="http://en.wikipedia.org/wiki/Object-relational_mapping" target="_blank">ORM</a> is very useful when dealing so many database tables, but in simple web application this feature do not need to use, when I first learn php framework, I don&#8217;t really know about ORM, and when I read the ORM section I feel like that it need to be in every web application. The good thing I learn about what ORM is, the bad thing is if we are in hurry, it will cost more time.</p>
<h6>3) Great Documentation</h6>
<p>Codeigniter documentation sure really written well, even for developer who are not familiar to <a title="MVC Codeigniter Documentation" href="http://codeigniter.com/user_guide/overview/mvc.html" target="_blank">MVC</a> pattern codeigniter documentation is one of good place to start, it is not really perfect but you can get the most out of the features here.</p>
<h6>4) No Plugin</h6>
<p>Since version 2 codeigniter remove plugins, from it feature, because he ambiguous with &#8220;Library&#8221; and &#8220;Helper&#8221;. It good to not to make a term confusion.</p>
<h6>5) Performance</h6>
<p>Codeigniter not really the fastest but one of the fastest, also I never test it by myself, cause I think it doesn&#8217;t really necessary, this two benchmark maybe can be as your benchmark reference (<a href="http://www.yiiframework.com/performance/" target="_blank">benchmark 1</a>, <a href="http://doophp.com/benchmark" target="_blank">benchmark 2</a>), but don&#8217;t rely on these to much cause &#8220;Hello World&#8221; application benchmark cannot measure overall performance when the web goes live.</p>
<p><img class="alignleft size-full wp-image-5838" title="codeigniter logo" src="http://superdit.com/wp-content/uploads/2011/03/codeigniter_logo_small.jpg" alt="codeigniter logo" width="42" height="54" />The conclusion is I&#8217;m not saying codeigniter is the best php framework, but it really good for everyone to getting started with php framework. One point, It will save more time when learning all the framework scope, but if you are a experience php developer and have more time to learn why not trying some more advanced framework like <a title="symfony" href="http://www.symfony-project.org/" target="_blank">Symfony</a> or <a title="Zend Framework" href="http://framework.zend.com/" target="_blank">Zend Framework</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://superdit.com/2011/03/28/opinion-why-php-developers-choose-codeigniter/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Extjs: Simple User Managament Using Codeigniter</title>
		<link>http://superdit.com/2010/12/09/extjs-simple-user-managament-using-codeigniter/</link>
		<comments>http://superdit.com/2010/12/09/extjs-simple-user-managament-using-codeigniter/#comments</comments>
		<pubDate>Thu, 09 Dec 2010 08:07:28 +0000</pubDate>
		<dc:creator>aditia rahman</dc:creator>
				<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[Extjs]]></category>
		<category><![CDATA[user management]]></category>

		<guid isPermaLink="false">http://superdit.com/?p=1718</guid>
		<description><![CDATA[Hello again this is another post of ExtJS, this post is to showing my little idea how to manage user permission in ExtJS component, In this post I not showing the full source code, just a little part of the code to get the idea how it works, however the complete source code still available<a href="http://superdit.com/2010/12/09/extjs-simple-user-managament-using-codeigniter/" class="read-more">Continue Reading</a>]]></description>
			<content:encoded><![CDATA[<p>Hello again this is another post of ExtJS, this post is to showing my little idea how to manage user permission in ExtJS component, In this post I not showing the full source code, just a little  part of the code to get the idea how it works, however the complete source code still  available on the download link at the end of this post.</p>
<p><img class="size-full wp-image-3265 alignleft" title="Ext User Management File-Structure" src="http://superdit.com/wp-content/uploads/2010/12/File-Structure.png" alt="" width="217" height="288" /></p>
<p>This example is a simple user management that user can manipulate other user data and users groups, user need to logged in to the system to do some action, and the feature are:</p>
<p>- Add, Update, Delete Users<br />
- Add, Update, Delete Groups<br />
- Administrator cannot be deleted or updated</p>
<p>Which  mean it will take different action button in the application screen, depend on the  users groups, what is not handled in this example is user   restriction, if a group have granted to modify certain user,   it can modify whole user although it is the administrator.</p>
<p>The image is the file structure that I have created on this example, there will be a form and two grid panel in this application, a usual login form with label and textfield, a grid contain user data with the toolbar menu and a grid contain group data.</p>
<p>In the database we need to make a relation between user and groups and here the sql code that I created, for both groups and users table<span id="more-1718"></span></p>
<pre class="brush: sql; title: ; notranslate">
-- Table structure for table `groups`

CREATE TABLE IF NOT EXISTS `groups` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `user_add` int(1) NOT NULL,
  `user_edit` int(1) NOT NULL,
  `user_delete` int(1) NOT NULL,
  `group_add` int(1) NOT NULL,
  `group_edit` int(1) NOT NULL,
  `group_delete` int(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;

-- Table structure for table `users`

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `group_id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(100) NOT NULL,
  `real_name` varchar(150) NOT NULL,
  `email` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;</pre>
<p>The groups table contains id, group name and all the action that user can do to the application, from the user_add field until group_delete column the value only contains 1 or 0, which mean 1 for user can do this action and zero otherwise, The idea to managing user interface is by  disabling the button on the toolbar based on the user group permissions and this are generated from groups table,  so we need to give a unique Id for each button.</p>
<p>As well in the controller there are two controller that we need to create, user controller in <em>application/controllers/user.php </em>and group controller in <em>application/controllers/group.php</em>. Inside the user controller create the function for login and fetching users session inside user controller</p>
<pre class="brush: php; title: ; notranslate">
public function ext_login()
{
    $cond = array(
        'username' =&gt; $_POST['textusername'],
        'password' =&gt; $_POST['textpassword']
    );
    $query = $this-&gt;db-&gt;get_where('users', $cond);
    if ($query-&gt;num_rows() != 0)
    {
        $row = $query-&gt;row();

        // get group detail
        $g_cond = array(
            'id' =&gt; $row-&gt;group_id
        );
        $g_query = $this-&gt;db-&gt;get_where('groups', $g_cond);
        $g_row = $g_query-&gt;row();

        // pass the the info to session
        $this-&gt;session-&gt;set_userdata('u_id', $row-&gt;id);
        $this-&gt;session-&gt;set_userdata('u_name', $_POST['textusername']);
        $this-&gt;session-&gt;set_userdata('g_id', $g_row-&gt;id);
        $this-&gt;session-&gt;set_userdata('g_u_add', $g_row-&gt;user_add);
        $this-&gt;session-&gt;set_userdata('g_u_edit', $g_row-&gt;user_edit);
        $this-&gt;session-&gt;set_userdata('g_u_delete', $g_row-&gt;user_delete);
        $this-&gt;session-&gt;set_userdata('g_g_add', $g_row-&gt;group_add);
        $this-&gt;session-&gt;set_userdata('g_g_edit', $g_row-&gt;group_edit);
        $this-&gt;session-&gt;set_userdata('g_g_delete', $g_row-&gt;group_delete);

        echo &quot;{success:true}&quot;;
    }
    else
    {
        echo &quot;{success:false, error:'User not found!'}&quot;;
    }
}

public function ext_get_session()
{
    $output = &quot;{success:true, sessions: {&quot;;
    $output .= &quot;u_id: '&quot;.$this-&gt;session-&gt;userdata('u_id').&quot;',&quot;;
    $output .= &quot;u_name: '&quot;.$this-&gt;session-&gt;userdata('u_name').&quot;',&quot;;
    $output .= &quot;g_id: '&quot;.$this-&gt;session-&gt;userdata('g_id').&quot;',&quot;;
    $output .= &quot;g_u_add: '&quot;.$this-&gt;session-&gt;userdata('g_u_add').&quot;',&quot;;
    $output .= &quot;g_u_edit: '&quot;.$this-&gt;session-&gt;userdata('g_u_edit').&quot;',&quot;;
    $output .= &quot;g_u_delete: '&quot;.$this-&gt;session-&gt;userdata('g_u_delete').&quot;',&quot;;
    $output .= &quot;g_g_add: '&quot;.$this-&gt;session-&gt;userdata('g_g_add').&quot;',&quot;;
    $output .= &quot;g_g_edit: '&quot;.$this-&gt;session-&gt;userdata('g_g_edit').&quot;',&quot;;
    $output .= &quot;g_g_delete: '&quot;.$this-&gt;session-&gt;userdata('g_g_delete').&quot;'&quot;;
    $output .= &quot;}}&quot;;
    echo $output;
}
</pre>
<p>The ext_get_sessions function above is to get session and pass it to the browser, and in the login function the session value will be defined when user logged in to the system, ext_get_sessions function will be used in the <em>permissions.js</em>, I&#8217;m sure you can add the logout function contain the code to unset all the sessions value and here the permissions function look like inside the <em>permissions.js</em></p>
<pre class="brush: php; title: ; notranslate">
 function setPermissions() {
    Ext.Ajax.request({
        url: BASE_URL + 'user/ext_get_session',
        method: 'POST',
        success: function(o) {
            var obj = Ext.util.JSON.decode(o.responseText);
            // set enable/disable grid panel
            if (obj.sessions.u_id != '') {
                Ext.getCmp('fLogin').setDisabled(true);
                Ext.getCmp('gUsers').setDisabled(false);
                Ext.getCmp('gGroups').setDisabled(false);
                Ext.getCmp('userLabel').setText('Welcome &quot;'+obj.sessions.u_name+'&quot;');
            } else {
                Ext.getCmp('fLogin').setDisabled(false);
                Ext.getCmp('gUsers').setDisabled(true);
                Ext.getCmp('gGroups').setDisabled(true);
                Ext.getCmp('userLabel').setText('Please Login');
            }

            // set users toolbar button
            if (obj.sessions.g_u_add == '1') {
                Ext.getCmp('tbUserAdd').setDisabled(false);
            } else {
                Ext.getCmp('tbUserAdd').setDisabled(true);
            }
            if (obj.sessions.g_u_edit == '1') {
                Ext.getCmp('tbUserEdit').setDisabled(false);
            } else {
                Ext.getCmp('tbUserEdit').setDisabled(true);
            }
            if (obj.sessions.g_u_delete == '1') {
                Ext.getCmp('tbUserDelete').setDisabled(false);
            } else {
                Ext.getCmp('tbUserDelete').setDisabled(true);
            }

            // set groups toolbar button
            if (obj.sessions.g_g_add == '1') {
                Ext.getCmp('tbGroupAdd').setDisabled(false);
            } else {
                Ext.getCmp('tbGroupAdd').setDisabled(true);
            }
            if (obj.sessions.g_g_edit == '1') {
                Ext.getCmp('tbGroupEdit').setDisabled(false);
            } else {
                Ext.getCmp('tbGroupEdit').setDisabled(true);
            }
            if (obj.sessions.g_g_delete == '1') {
                Ext.getCmp('tbGroupDelete').setDisabled(false);
            } else {
                Ext.getCmp('tbGroupDelete').setDisabled(true);
            }
        }
    });
}
</pre>
<p>As you can see on the code above, I manipulate the ExtJS component based on &#8220;Id&#8221;, so we need to to add Id properties for the required component,  here a part of login form script and the form id I called it &#8216;fLogin&#8217; (<em> assets/js/login.js </em>)</p>
<pre class="brush: jscript; title: ; notranslate">
// part of login.js
var loginForm = new Ext.FormPanel({
    id: 'fLogin'
});

function fnLogin() {
    loginForm.getForm().submit({
        success: function() {
            setPermissions();
            strUsers.load();
        },
        failure: function(form, o) {
            if (typeof(o.response) != 'undefined') {
                var json = o.response.responseText;
                var r = Ext.util.JSON.decode(json);
                Ext.Msg.alert('Login failed', r.error);
            }
        }
    });
}</pre>
<p>Now part of the user script in ExtJS (<em> assets/js/user.js </em>)</p>
<pre class="brush: jscript; title: ; notranslate">
// part of user.js
var tbUsers = new Ext.Toolbar({
    items: [{
        text: 'Add',
        id: 'tbUserAdd'
    }, '-', {
        text: 'Edit',
        id: 'tbUserEdit'
    }, '-', {
        text: 'Delete',
        id: 'tbUserDelete'
    }, '-&gt;', {
        text: '',
        xtype: 'label',
        style: 'color:#0066cc;font-weight:bold;',
        id: 'userLabel'
    }, '-', {
        text: 'Logout'
    }]
});

var gridUsers = new Ext.grid.GridPanel({
    id: 'gUsers'
});
</pre>
<p>In the group script (<em>assets/js/group.js</em>)</p>
<pre class="brush: jscript; title: ; notranslate">
var tbGroups = new Ext.Toolbar({
    items: [{
        text: 'Add',
        id: 'tbGroupAdd'
    }, '-', {
        text: 'Edit',
        id: 'tbGroupEdit'
    }, '-', {
        text: 'Delete',
        id: 'tbGroupDelete'
    }]
});

var gridGroups = new Ext.grid.GridPanel({
    id: 'gGroups'
});
</pre>
<p>For the adding and editing users and group I&#8217;m using a pop up window that have form to be submitted inside it, and for delete action I&#8217;m just using simple alert confirmation box. Well I think it is too much if I show all the code in this post, just go to the download link if you want to see full source code of this example, and here some of the screen capture.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-3366" title="Extjs User Management - Index" src="http://superdit.com/wp-content/uploads/2010/12/Extjs-User-Management-Index.png" alt="" width="500" height="212" /></p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-3367" title="Extjs User Management - Edit User" src="http://superdit.com/wp-content/uploads/2010/12/ExtUserMan-Edit-User.png" alt="" width="500" height="379" /></p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-3368" title="Extjs User Management - Edit Group" src="http://superdit.com/wp-content/uploads/2010/12/ExtUserMan-Edit-Group.png" alt="" width="500" height="300" /></p>
<p style="text-align: center;"><a href="http://www.box.net/shared/m91x1k4z1m" target="_blank">Download Source</a></p>
]]></content:encoded>
			<wfw:commentRss>http://superdit.com/2010/12/09/extjs-simple-user-managament-using-codeigniter/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Drag and Drop Shopping Cart Using ExtJS and CodeIgniter Cart</title>
		<link>http://superdit.com/2010/08/21/drag-and-drop-shopping-cart-using-extjs-and-codeigniter-cart/</link>
		<comments>http://superdit.com/2010/08/21/drag-and-drop-shopping-cart-using-extjs-and-codeigniter-cart/#comments</comments>
		<pubDate>Sat, 21 Aug 2010 09:55:23 +0000</pubDate>
		<dc:creator>aditia rahman</dc:creator>
				<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[Extjs]]></category>
		<category><![CDATA[cart]]></category>
		<category><![CDATA[drag n drop]]></category>
		<category><![CDATA[snippet]]></category>

		<guid isPermaLink="false">http://superdit.com/?p=1967</guid>
		<description><![CDATA[This is my other post about simple usage of ExtJS with CodeIgniter, this time I want to create a simple drag and drop shopping cart, I have learn about how to use the cart class in CodeIgniter that I have posted in the previous post, i&#8217;m using MySQL for the storing the product data. I<a href="http://superdit.com/2010/08/21/drag-and-drop-shopping-cart-using-extjs-and-codeigniter-cart/" class="read-more">Continue Reading</a>]]></description>
			<content:encoded><![CDATA[<p>This is my other post about simple usage of ExtJS with CodeIgniter, this time I want to create a simple drag and drop shopping cart, I have learn about how to use the cart class in CodeIgniter that I have posted in the <a title="Understanding CodeIgniter Cart Class" href="http://superdit.com/2010/08/04/understanding-codeigniter-cart-class/" target="_blank">previous post</a>, i&#8217;m using MySQL for the storing the product data. I prepared the mockup it something like this</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-2417" src="http://superdit.com/wp-content/uploads/2010/08/the_mockup.jpg" alt="" width="500" height="257" /><span id="more-1967"></span></p>
<p>Let just get started to the code:</p>
<h4>1. Prepare The Database</h4>
<p>Create table named <em>&#8220;ci_extjs_cart&#8221;</em> or with other name that you desired, next create the table and here the sql code</p>
<pre class="brush: sql; title: ; notranslate">
CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(64) DEFAULT NULL,
  `price` varchar(32) DEFAULT NULL,
  `image` varchar(128) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
</pre>
<p>And this are the sample data (I already included the sample image on the code that you can download)</p>
<pre class="brush: sql; title: ; notranslate">
INSERT INTO `products` (`id`, `name`, `price`, `image`) VALUES
(1, 'HP - 20 Inch Widescreen Flat-Panel LCD Monitor', '169', 'hp.jpg'),
(2, 'Gateway - 20 Inch Widescreen Flat-Panel LCD Monitor', '159', 'gateway.jpg'),
(3, 'Apple - 30 Flat-Panel TFT-LCD Monitor', '1799', 'apple.jpg'),
(4, 'Acer - 24 Inch Flat-Panel LED-LCD Monitor', '299', 'acer.jpg'),
(5, 'Asus - 24 Inch Widescreen Flat-Panel LCD Monitor', '249', 'asus.jpg');
</pre>
<h4>2. Setting Up CodeIgniter</h4>
<p>First time to get hand dirty with a framework is to set all the config file (in folder: <em>&#8220;application/config/&#8221;</em>). The four files that we have to configure are:</p>
<p><strong>config.php</strong></p>
<pre class="brush: php; title: ; notranslate">
$config['base_url']	= &quot;http://localhost/ci_extjs_cart/&quot;;
</pre>
<p><strong>database.php</strong></p>
<pre class="brush: php; title: ; notranslate">
$db['default']['hostname'] = &quot;localhost&quot;;
$db['default']['username'] = &quot;root&quot;;
$db['default']['password'] = &quot;admin&quot;;
$db['default']['database'] = &quot;ci_extjs_cart&quot;;
$db['default']['dbdriver'] = &quot;mysql&quot;;
</pre>
<p><strong>routes.php</strong></p>
<pre class="brush: php; title: ; notranslate">
$route['default_controller'] = &quot;product&quot;;
</pre>
<p>The default controller is set to product controller, in this step we have not create the controller yet, but it will be.</p>
<p><strong>autoload.php</strong></p>
<pre class="brush: php; title: ; notranslate">
$autoload['libraries'] = array('database', 'session');
$autoload['helper'] = array('url');
</pre>
<h4>4. Setting Up ExtJS on CodeIgniter</h4>
<p>Like always I always included ExtJS file on separate folder from Codeigniter</p>
<h4>5. Create a Controller and a View</h4>
<p><strong>The Controller</strong>, create file <em>product.php </em>inside the controllers folder, the very usual method on the controller is the contrustion and the index method, in the construction method the codeigniter cart class loaded. <em><br />
</em></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

class Product extends Controller {

    public function  __construct()
    {
        parent::Controller();
        $this-&gt;load-&gt;library('cart');
    }

    public function index()
    {
        $this-&gt;load-&gt;view('product/index');
    }
}
</pre>
<p><strong>The View</strong>, create the view file inside views folder <em>&#8220;index.php&#8221;</em>, the first step to preparing the view is to preparing the HTML layout, include the ExtJS file, and create a basic layout style in CSS.</p>
<pre class="brush: php; title: ; notranslate">
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;&lt;?php echo base_url(); ?&gt;assets/js/ext/resources/css/ext-all.css&quot;/&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;&lt;?php echo base_url(); ?&gt;assets/js/ext/adapter/ext/ext-base.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;&lt;?php echo base_url(); ?&gt;assets/js/ext/ext-all.js&quot;&gt;&lt;/script&gt;
    &lt;!-- product data view style --&gt;
    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;&lt;?php echo base_url(); ?&gt;assets/js/ext/ux/data-view.css&quot;/&gt;

    &lt;script type=&quot;text/javascript&quot;&gt;
    var BASE_URL = '&lt;?php echo site_url(); ?&gt;/';

    Ext.onReady(function() {
    });
    &lt;/script&gt;
    &lt;title&gt;Extjs Image Gallery Using DataView&lt;/title&gt;
    &lt;style type=&quot;text/css&quot;&gt;
        body {
            padding: 20px;
            margin: 0 auto;
        }
        #container {
            padding: 10px;
            background: #e3e3e3;
            border: 1px solid #d3d3d3;
            margin: 0 auto;
            text-align: left;
            width: 630px;
        }
        #top {

        }
        #bottom {
            margin-top: 10px;
        }
    &lt;/style&gt;
    &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;div id=&quot;container&quot;&gt;
          &lt;div id=&quot;top&quot;&gt;&lt;/div&gt;
          &lt;div id=&quot;bottom&quot;&gt;&lt;/div&gt;
      &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The Ext.ready function is still empty, inside this function all the ExtJS component will be placed, and I always using BASE_URL value that have value of <em>site_url(); </em>function<em>, </em>to make it easier when accessing a url.</p>
<h4>6. Get Product List</h4>
<p><strong>The Controller</strong>, this is the method the get all the product data, and sending the data as json format.</p>
<pre class="brush: php; title: ; notranslate">
public function ext_get_all()
{
    $query = $this-&gt;db-&gt;get('products');
    $product_arr = array();
    foreach($query-&gt;result() as $key =&gt; $data)
    {
        $product_arr[] = array(
            'id'    =&gt; $data-&gt;id,
            'name'  =&gt; $data-&gt;name,
            'price' =&gt; $data-&gt;price,
            'image' =&gt; $data-&gt;image
        );
    }
    echo json_encode(array('products' =&gt; $product_arr));
}
</pre>
<p><strong>The View</strong>, this is the code for creating the product list in dataview, and a function to make the dataview draggable.</p>
<pre class="brush: jscript; title: ; notranslate">
var proxyProduct = new Ext.data.HttpProxy({
    url: BASE_URL + 'product/ext_get_all', method: 'POST'
});

var strProduct = new Ext.data.JsonStore({
    proxy: proxyProduct,
    root: 'products',
    fields: [
        'id', 'name', 'price', 'image'
    ]
});

strProduct.load();

var tplProduct = new Ext.XTemplate(
    '&lt;tpl for=&quot;.&quot;&gt;',
        '&lt;div class=&quot;thumb-wrap&quot; id=&quot;{name}&quot;&gt;',
        '&lt;div class=&quot;thumb&quot;&gt;&lt;img src=&quot;http://localhost/ci_extjs_cart/assets/img/{image}&quot; title=&quot;{name}&quot;&gt;&lt;/div&gt;',
        '&lt;span class=&quot;name&quot;&gt;{name}&lt;/span&gt;',
        '&lt;div class=&quot;price&quot;&gt;$ {price}&lt;/div&gt;&lt;/div&gt;',
    '&lt;/tpl&gt;',
    '&lt;div class=&quot;x-clear&quot;&gt;&lt;/div&gt;'
);

var dvProduct = new Ext.DataView({
    autoScroll: true, store: strProduct, tpl: tplProduct,
    autoHeight: false, height: 200, multiSelect: false,
    overClass: 'x-view-over', itemSelector: 'div.thumb-wrap',
    emptyText: 'No product to display',
    style: 'border:1px solid #99BBE8;',
    listeners: {
        render: initializeItemDragZone
    }
});

function initializeItemDragZone(v) {
    v.dragZone = new Ext.dd.DragZone(v.getEl(), {
        getDragData: function(e) {
            var sourceEl = e.getTarget(v.itemSelector, 10);
            if (sourceEl) {
                d = sourceEl.cloneNode(true);
                d.id = Ext.id();
                return v.dragData = {
                    sourceEl: sourceEl,
                    repairXY: Ext.fly(sourceEl).getXY(),
                    ddel: d,
                    itemData: v.getRecord(sourceEl).data
                }
            }
        },

        getRepairXY: function() {
            return this.dragData.repairXY;
        }
    });
}

var panelProduct = new Ext.Panel({
    id: 'images-view',
    frame: true,
    width: 620,
    autoHeight: true,
    title: 'Product DataView',
    style: 'margin:0 auto;',
    items: [dvProduct]
});

panelProduct.render('top');
</pre>
<h4>7. Create The Cart (Using EditorGridPanel)</h4>
<p><strong>The Controller</strong>, we will create some basic function to manipulating the cart I try to explain them in the separate way, but still in the same controller</p>
<p><strong>7.1 Get All Cart</strong></p>
<pre class="brush: php; title: ; notranslate">
public function ext_get_cart()
{
    if ($this-&gt;cart-&gt;total_items() != 0)
    {
        foreach($this-&gt;cart-&gt;contents() as $product)
        {
            $cart_arr[] = array(
                'rowid' =&gt; $product['rowid'],
                'id'    =&gt; $product['id'],
                'qty'   =&gt; $product['qty'],
                'name'  =&gt; $product['name'],
                'price' =&gt; $product['price'],
                'subtotal' =&gt; $product['subtotal']
            );
        }
        $cart_arr[] = array(
            'rowid' =&gt; '',
            'id'    =&gt; '',
            'qty'   =&gt; '',
            'name'  =&gt; '',
            'price' =&gt; '&lt;b&gt;Total:&lt;/b&gt;',
            'subtotal' =&gt; '&lt;b&gt;'.$this-&gt;cart-&gt;total().'&lt;/b&gt;'
        );
        echo json_encode(array('cart' =&gt; $cart_arr));
    }
    else
    {
        $cart_arr[] = array();
        echo json_encode(array('cart' =&gt; $cart_arr));
    }
}
</pre>
<p>This function is to getting all the available product in the cart in the session, if the cart is not empty then just loop through the cart function <em>&#8220;$this-&gt;cart-&gt;contents()&#8221; </em>and put this to array. I add another array to showing the total value from the cart, this will be treated different in the ExtJS grid, and send it as json format</p>
<p><strong>7.2 Add a Product to Cart</strong></p>
<pre class="brush: php; title: ; notranslate">
public function ext_add_cart()
{
    if ($_POST['rowid'] == '')
    {
        $data = array(
            'id'    =&gt; $_POST['id'],
            'qty'   =&gt; 1,
            'price' =&gt; $_POST['price'],
            'name'  =&gt; $_POST['name']
        );
        $this-&gt;cart-&gt;insert($data);
    }
    else
    {
        $data = array(
          'rowid'   =&gt; $_POST['rowid'],
          'qty'     =&gt; intval($_POST['qty']) + 1
        );
        $this-&gt;cart-&gt;update($data);
    }
    echo '{success:true, total: &quot;'.$this-&gt;cart-&gt;total().'&quot;}';
}
</pre>
<p>You must be can see in the add cart function there are conditional statement that updating the cart instead insert a new data to cart, well this is to handle if a user adding the product that already available on the cart, so the cart must be updating only the quantity.</p>
<p><strong>7.3 Update a Product Quantity</strong></p>
<pre class="brush: php; title: ; notranslate">
public function ext_update_cart()
{
    $data = array(
      'rowid'   =&gt; $_POST['rowid'],
      'qty'     =&gt; $_POST['qty']
    );
    $this-&gt;cart-&gt;update($data);
    echo '{success:true}';
}
</pre>
<p>This function is to updating a product quantity on the cart, I make the quantity editable on the grid so the user can easy put the number of a product that he desired, and to deleting a product from cart the user have to put zero value on the quantity editable grid.</p>
<p><strong>7.4 Clear Cart</strong></p>
<pre class="brush: php; title: ; notranslate">
public function ext_clear_cart()
{
    $this-&gt;cart-&gt;destroy();
    echo '{success:true}';
}
</pre>
<p>Well nothing really hard in this function, using &#8220;$this-&gt;cart-&gt;destroy()&#8221; all the cart clear.</p>
<p><strong>7.5 The Cart</strong></p>
<pre class="brush: jscript; title: ; notranslate">
var strCart = new Ext.data.JsonStore({
    root: 'cart',
    fields: [
        'rowid', 'id', 'qty', 'name', 'price', 'subtotal'
    ],
    proxy: new Ext.data.HttpProxy({
        url: BASE_URL + 'product/ext_get_cart', method: 'POST'
    })
});
strCart.load();

var cb_select = new Ext.grid.CheckboxSelectionModel();

function showDollar(val) {
    if (val == '' || val == '&lt;b&gt;Total:&lt;/b&gt;') {
        return val;
    }
    else {
        return '$ ' + val;
    }
}

var panelCart = new Ext.grid.EditorGridPanel({
    frame: true, border: true, stripeRows: true,
    store: strCart, loadMask: true, title: 'Your Cart (Drag Here)',
    style: 'margin:0 auto;font-size:13px;',
    height: 220, width: 500, sm: cb_select,
    columns: [{
        header: 'rowid',
        dataIndex: 'rowid',
        hidden: true,
        hideable: false
    }, {
        header: 'id',
        dataIndex: 'id',
        hidden: true,
        hideable: false
    }, {
        header: &quot;Product Name&quot;,
        dataIndex: 'name',
        sortable: true,
        width: 280
    }, {
        header: &quot;Qty&quot;,
        align: 'center',
        width: 40,
        dataIndex: 'qty',
        menuDisabled: true,
        editor: new Ext.form.TextField({
            allowBlank: false,
            vtype: 'alphanum',
            id: 'qtyField'
        })
    }, {
        header: &quot;Price&quot;,
        dataIndex: 'price',
        sortable: true,
        align: 'right',
        renderer: showDollar,
        width: 80
    }, {
        header: &quot;Subtotal&quot;,
        sortable: true,
        align: 'right',
        width: 80,
        renderer: showDollar
    }],
    listeners: {
        'afteredit': function() {
            var sm = panelCart.getSelectionModel().getSelections();
            panelCart.getSelectionModel().clearSelections();
            Ext.Ajax.request({
                method: 'POST',
                url: BASE_URL + 'product/ext_update_cart',
                params: {
                    rowid: sm[0].get('rowid'),
                    qty: Ext.getCmp('qtyField').getValue()
                },
                success: function() {
                    strCart.load();
                }
            });
        }
    },
    buttons: [{
        text: 'Clear Cart',
        handler: function() {
            Ext.Ajax.request({
                url: BASE_URL + 'product/ext_clear_cart',
                method: 'POST',
                success: function() {
                    strCart.load();
                }
            });
        }
    }, {
        text: 'Check Out',
        handler: function() {

        }
    }]
});

panelCart.render('bottom');

var formPanelDropTargetEl =  panelCart.getView().scroller.dom;

var formPanelDropTarget = new Ext.dd.DropTarget(formPanelDropTargetEl, {
    notifyDrop  : function(ddSource, e, data){
        panelCart.getSelectionModel().selectAll();
        var sm = panelCart.getSelectionModel().getSelections();
        panelCart.getSelectionModel().clearSelections();

        data.itemData.rowid = '';
        for (i=0; i&lt;=sm.length-1; i++) {
            if (sm[i].get('id') == data.itemData.id) {
                data.itemData.rowid = sm[i].get('rowid');
                data.itemData.qty = sm[i].get('qty');
                // so can out from loop
                i = sm.length;
            }
        }

        Ext.Ajax.request({
            url: BASE_URL + 'product/ext_add_cart',
            method: 'POST',
            params: {
                'id': data.itemData.id,
                'price': data.itemData.price,
                'name': data.itemData.name,
                'rowid': data.itemData.rowid,
                'qty': data.itemData.qty
            },
            success: function() {
                strCart.load();
            }
        });
        return(true);
    }
});
</pre>
<p>That&#8217;s all for the Cart features, there is <em>CheckboxSelectionModel</em> component, this component is to check whether the product is already on the cart, you can see it used on <em>notifyDrop</em> inside the <em>dropTarget</em> you have to add, the expected result is something like this.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-2407" title="ExtJS &amp; CodeIgniter Cart" src="http://superdit.com/wp-content/uploads/2010/08/localhost_ci_extjs_cart.png" alt="ExtJS &amp; CodeIgniter Cart" width="500" height="375" /></p>
<p style="text-align: center;"><a title="CodeIgniter ExtJS Drag n Drop Cart" href="http://www.box.net/shared/qamveqfxlt" target="_blank">Download Source</a></p>
]]></content:encoded>
			<wfw:commentRss>http://superdit.com/2010/08/21/drag-and-drop-shopping-cart-using-extjs-and-codeigniter-cart/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Understanding CodeIgniter Cart Class</title>
		<link>http://superdit.com/2010/08/04/understanding-codeigniter-cart-class/</link>
		<comments>http://superdit.com/2010/08/04/understanding-codeigniter-cart-class/#comments</comments>
		<pubDate>Wed, 04 Aug 2010 06:21:20 +0000</pubDate>
		<dc:creator>aditia rahman</dc:creator>
				<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[cart]]></category>

		<guid isPermaLink="false">http://superdit.com/?p=2214</guid>
		<description><![CDATA[Cart is one of the most important feature when creating an online store. In this post I want to have more understanding about Cart Class in CodeIgniter, cause maybe come in handy in the future, you can see how many new online store out there open in business, and in this internet age, online store<a href="http://superdit.com/2010/08/04/understanding-codeigniter-cart-class/" class="read-more">Continue Reading</a>]]></description>
			<content:encoded><![CDATA[<p><img class="size-full wp-image-2248 alignleft" title="CodeIgniter Cart Class" src="http://superdit.com/wp-content/uploads/2010/08/1280895266_shopping_cart-red.jpg" alt="CodeIgniter Cart Class" width="61" height="61" />Cart is one of the most important feature when creating an online store. In this post I want to have more understanding about Cart Class in CodeIgniter, cause maybe come in handy in the future, you can see how many new online store out there open in business, and in this internet age, online store seems the must have for many people who have retail business, in this post I&#8217;m not writing about how to use it in some example, the code I posted in here just copying from the original <a title="Code Igniter Cart Class Documentation" href="http://codeigniter.com/user_guide/libraries/cart.html" target="_blank">cart class documentation</a>, but i&#8217;m included the link to the example usage of this class on the section 4 below.<span id="more-2214"></span></p>
<h4>1. What is Cart Class in CodeIgniter?</h4>
<p>First from the official documentation</p>
<p><em>- The Cart class utilizes CodeIgniter&#8217;s Session Class to save the cart information to a database, so before using the Cart class you must set up a database table as indicated in the Session Documentation , and set the session preferences in your appliction/config/config.php file to utilize a database.</em> -</p>
<p>which mean this class save the cart from the users and save it to database, you have to create this table</p>
<pre class="brush: sql; title: ; notranslate">
CREATE TABLE IF NOT EXISTS  `ci_sessions` (
	session_id varchar(40) DEFAULT '0' NOT NULL,
	ip_address varchar(16) DEFAULT '0' NOT NULL,
	user_agent varchar(50) NOT NULL,
	last_activity int(10) unsigned DEFAULT 0 NOT NULL,
	user_data text NOT NULL,
	PRIMARY KEY (session_id)
);
</pre>
<p>You can change the table name, but it have to be adapted to the config.php</p>
<pre class="brush: php; title: ; notranslate">
$config['sess_cookie_name']		= 'ci_session';
$config['sess_expiration']		= 7200;
$config['sess_encrypt_cookie']	= FALSE;
$config['sess_use_database']	= FALSE;
$config['sess_table_name']		= 'ci_sessions';
$config['sess_match_ip']		= FALSE;
$config['sess_match_useragent']	= TRUE;
$config['sess_time_to_update'] 	= 300;
</pre>
<p>When you add an array data to the cart class, the data would be inserted to ci_sessions table in user_data field. Saving data to cart class is have to be in array format, it can be single or multidimensional array, this code I take from the original documentation</p>
<pre class="brush: php; title: ; notranslate">
// the single array
$data = array(
   'id'      =&gt; 'sku_123ABC',
   'qty'     =&gt; 1,
   'price'   =&gt; 39.95,
   'name'    =&gt; 'T-Shirt',
   'options' =&gt; array('Size' =&gt; 'L', 'Color' =&gt; 'Red')
);

// the multidimensional array
$data = array(
   array(
           'id'      =&gt; 'sku_123ABC',
           'qty'     =&gt; 1,
           'price'   =&gt; 39.95,
           'name'    =&gt; 'T-Shirt',
           'options' =&gt; array('Size' =&gt; 'L', 'Color' =&gt; 'Red')
        ),
   array(
           'id'      =&gt; 'sku_567ZYX',
           'qty'     =&gt; 1,
           'price'   =&gt; 9.95,
           'name'    =&gt; 'Coffee Mug'
        ),
   array(
           'id'      =&gt; 'sku_965QRS',
           'qty'     =&gt; 1,
           'price'   =&gt; 29.95,
           'name'    =&gt; 'Shot Glass'
        )
);

// insert the data
$this-&gt;cart-&gt;insert($data);
</pre>
<p>The required index in the array are <strong>id</strong>, <strong>qty</strong>, <strong>price</strong>, <strong>name</strong> you can add the additional index but you can&#8217;t use that four index and the <strong>options</strong> index is optional, in case you want to save another information of the product for example, T-Shirt with the same product id but different size. The last thing from the array is you can&#8217;t use another words that reserved, they are <strong>rowid</strong> and <strong>subtotal</strong>.</p>
<h4>2. Displaying The Items</h4>
<pre class="brush: php; title: ; notranslate">
&lt;?php echo form_open('path/to/controller/update/function'); ?&gt;

&lt;table cellpadding=&quot;6&quot; cellspacing=&quot;1&quot; style=&quot;width:100%&quot; border=&quot;0&quot;&gt;

&lt;tr&gt;
  &lt;th&gt;QTY&lt;/th&gt;
  &lt;th&gt;Item Description&lt;/th&gt;
  &lt;th style=&quot;text-align:right&quot;&gt;Item Price&lt;/th&gt;
  &lt;th style=&quot;text-align:right&quot;&gt;Sub-Total&lt;/th&gt;
&lt;/tr&gt;

&lt;?php $i = 1; ?&gt;

&lt;?php foreach($this-&gt;cart-&gt;contents() as $items): ?&gt;

	&lt;?php echo form_hidden($i.'[rowid]', $items['rowid']); ?&gt;

	&lt;tr&gt;
	  &lt;td&gt;&lt;?php echo form_input(array('name' =&gt; $i.'[qty]', 'value' =&gt; $items['qty'], 'maxlength' =&gt; '3', 'size' =&gt; '5')); ?&gt;&lt;/td&gt;
	  &lt;td&gt;
		&lt;?php echo $items['name']; ?&gt;

			&lt;?php if ($this-&gt;cart-&gt;has_options($items['rowid']) == TRUE): ?&gt;

				&lt;p&gt;
					&lt;?php foreach ($this-&gt;cart-&gt;product_options($items['rowid']) as $option_name =&gt; $option_value): ?&gt;

						&lt;strong&gt;&lt;?php echo $option_name; ?&gt;:&lt;/strong&gt; &lt;?php echo $option_value; ?&gt;&lt;br /&gt;

					&lt;?php endforeach; ?&gt;
				&lt;/p&gt;

			&lt;?php endif; ?&gt;

	  &lt;/td&gt;
	  &lt;td style=&quot;text-align:right&quot;&gt;&lt;?php echo $this-&gt;cart-&gt;format_number($items['price']); ?&gt;&lt;/td&gt;
	  &lt;td style=&quot;text-align:right&quot;&gt;$&lt;?php echo $this-&gt;cart-&gt;format_number($items['subtotal']); ?&gt;&lt;/td&gt;
	&lt;/tr&gt;

&lt;?php $i++; ?&gt;

&lt;?php endforeach; ?&gt;

&lt;tr&gt;
  &lt;td colspan=&quot;2&quot;&gt; &lt;/td&gt;
  &lt;td class=&quot;right&quot;&gt;&lt;strong&gt;Total&lt;/strong&gt;&lt;/td&gt;
  &lt;td class=&quot;right&quot;&gt;$&lt;?php echo $this-&gt;cart-&gt;format_number($this-&gt;cart-&gt;total()); ?&gt;&lt;/td&gt;
&lt;/tr&gt;

&lt;/table&gt;

&lt;p&gt;&lt;?php echo form_submit('', 'Update your Cart'); ?&gt;&lt;/p&gt;
</pre>
<p>The code above is to displaying the current cart on the web pages, and theres a hidden field on the form this is used when we want to updating the cart, the difference between insert and update is, insert function is to adding new items to the cart, yet the update function is to updating items on the cart whether the quantity the options or something else, so when you updating the cart you need the rowid to pass it through. Here is the code</p>
<pre class="brush: php; title: ; notranslate">
$data = array(
   'rowid' =&gt; 'b99ccdf16028f015540f341130b6d8ec',
   'qty'   =&gt; 3
);

$this-&gt;cart-&gt;update($data);

// or a multi-dimensional array

$data = array(
   array(
           'rowid'   =&gt; 'b99ccdf16028f015540f341130b6d8ec',
           'qty'     =&gt; 3
        ),
   array(
           'rowid'   =&gt; 'xw82g9q3r495893iajdh473990rikw23',
           'qty'     =&gt; 4
        ),
   array(
           'rowid'   =&gt; 'fh4kdkkkaoe30njgoe92rkdkkobec333',
           'qty'     =&gt; 2
        )
);

$this-&gt;cart-&gt;update($data);
</pre>
<h4>3. The Available Function</h4>
<p><strong>$this-&gt;cart-&gt;insert();</strong><br />
- <em>Permits you to add items to the shopping cart, as outlined above.</em> -</p>
<p><strong>$this-&gt;cart-&gt;update();</strong><br />
- <em>Permits you to update items in the shopping cart, as outlined above.</em> -</p>
<p><strong>$this-&gt;cart-&gt;total();</strong><br />
- <em>Displays the total amount in the cart.</em> -</p>
<p><strong>$this-&gt;cart-&gt;total_items();</strong><br />
- <em>Displays the total number of items in the cart.</em> -</p>
<p><strong>$this-&gt;cart-&gt;contents();</strong><br />
- <em>Returns an array containing everything in the cart.</em> -</p>
<p><strong>$this-&gt;cart-&gt;has_options(rowid);</strong><br />
- <em>Returns TRUE (boolean) if a particular row in the cart contains options.  This function is designed to be used in a loop with <dfn>$this-&gt;cart-&gt;contents()</dfn>, since you must pass the <kbd>rowid</kbd> to this function, as shown in the <dfn>Displaying the Cart</dfn> example above. -<br />
</em></p>
<p><strong>$this-&gt;cart-&gt;options(rowid);</strong><br />
- <em>Returns an array of options for a particular product. This function is designed to be used in a loop with <dfn>$this-&gt;cart-&gt;contents()</dfn>, since you must pass the <kbd>rowid</kbd> to this function, as shown in the <dfn>Displaying the Cart</dfn> example above.</em> -</p>
<p><strong>$this-&gt;cart-&gt;destroy();</strong><br />
- <em>Permits you to destroy the cart.  This function will likely be called when you are finished processing the customer&#8217;s order.</em> -</p>
<p><strong>$this-&gt;cart-&gt;product_options(rowid);</strong><br />
- <em>This function not described in the documentation but used in the example, this is to get the available options on the product.</em> -</p>
<h4>4. The Examples</h4>
<p>I&#8217;m not providing any code from this post, these tutorial below can provide you to get started with this cart class. Maybe I&#8217;ll post the different tutorial from these. Just enjoy it.</p>
<p>CodeIgniter From Scratch: Shopping Cart ( <a title="CodeIgniter From Scratch: Shopping Cart" href="http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-shopping-cart/" target="_blank">link</a> )</p>
<p><a title="CodeIgniter From Scratch: Shopping Cart" href="http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-shopping-cart/" target="_blank"><img class="alignnone size-full wp-image-2252" title="net.tutsplus.com tutorials php codeigniter from scratch shopping cart" src="http://superdit.com/wp-content/uploads/2010/08/net_tutsplus_com_tutorials_php_codeigniter-from-scratch-shopping-cart.png" alt="net.tutsplus.com tutorials php codeigniter from scratch shopping cart" width="500" height="198" /></a></p>
<p>How to Build a Shopping Cart using CodeIgniter and jQuery ( <a title="How to Build a Shopping Cart using CodeIgniter and jQuery" href="http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using-codeigniter-and-jquery/" target="_blank">link</a> )</p>
<p><a title="How to Build a Shopping Cart using CodeIgniter and jQuery" href="http://net.tutsplus.com/tutorials/php/how-to-build-a-shopping-cart-using-codeigniter-and-jquery/" target="_blank"><img class="alignnone size-full wp-image-2253" title="net.tutsplus.com tutorials php how to build a shopping cart using codeigniter and jquery" src="http://superdit.com/wp-content/uploads/2010/08/net_tutsplus_com_tutorials_php_how-to-build-a-shopping-cart-using-codeigniter-and-jquery.png" alt="net.tutsplus.com tutorials php how to build a shopping cart using codeigniter and jquery" width="500" height="198" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://superdit.com/2010/08/04/understanding-codeigniter-cart-class/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Cropping Image To Square Dimension With CodeIgniter</title>
		<link>http://superdit.com/2010/07/14/cropping-image-to-square-dimension-with-codeigniter/</link>
		<comments>http://superdit.com/2010/07/14/cropping-image-to-square-dimension-with-codeigniter/#comments</comments>
		<pubDate>Wed, 14 Jul 2010 09:21:03 +0000</pubDate>
		<dc:creator>aditia rahman</dc:creator>
				<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[crop]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[snippet]]></category>

		<guid isPermaLink="false">http://superdit.com/?p=1499</guid>
		<description><![CDATA[I&#8217;ve posted similar article before but this time I want to do it with codeigniter, codeigniter have a powerful image manipulation class, in this post I will use it to make thumbnail square from image, let get directly to the code. I make the function inside the controller, this code is cropping image that already<a href="http://superdit.com/2010/07/14/cropping-image-to-square-dimension-with-codeigniter/" class="read-more">Continue Reading</a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve posted similar article <a title="Cropping Image to Square Dimension Using PHP" href="http://superdit.com/2010/07/01/cropping-image-to-square-dimension-using-php/" target="_blank">before</a> but this time I want to do it with codeigniter, codeigniter have a powerful <a title="Codeigniter Image Manipulation" href="http://codeigniter.com/user_guide/libraries/image_lib.html" target="_blank">image manipulation class</a>, in this post I will use it to make thumbnail square from image, let get directly to the code. I make the function inside the controller, this code is cropping image that already located on the server so the image path (not URL) have to be defined.<span id="more-1499"></span></p>
<p>If you have dynamic variable to locate image on the server you can create function to check image type wheter is .png, .gif or .jpg then use the PHP GD function (imagecreatefromjpeg or imagecreatefrompng or imagecreatefromgif) to get the image width and height, in this code below it assume the image only in .jpg format.</p>
<p>And if you want to crop image from the uploaded file by the user it will make it easier, cause when you use codeigniter <a title="CodeIgniter File Uploading Class" href="http://codeigniter.com/user_guide/libraries/file_uploading.html" target="_blank">file uploading class</a> there&#8217;s a built in property to get uploaded image width and image height automatically after the image was uploaded.</p>
<pre class="brush: php; title: ; notranslate">
public function crop()
{
    $img_path = 'uploads\capsamples.jpg';
    $img_thumb = 'uploads\capsamples_thumb.jpg';

    $config['image_library'] = 'gd2';
    $config['source_image'] = $img_path;
    $config['create_thumb'] = TRUE;
    $config['maintain_ratio'] = FALSE;

    $img = imagecreatefromjpeg($img_path);
    $_width = imagesx($img);
    $_height = imagesy($img);

    $img_type = '';
    $thumb_size = 100;

    if ($_width &gt; $_height)
    {
        // wide image
        $config['width'] = intval(($_width / $_height) * $thumb_size);
        if ($config['width'] % 2 != 0)
        {
            $config['width']++;
        }
        $config['height'] = $thumb_size;
        $img_type = 'wide';
    }
    else if ($_width &lt; $_height)
    {
        // landscape image
        $config['width'] = $thumb_size;
        $config['height'] = intval(($_height / $_width) * $thumb_size);
        if ($config['height'] % 2 != 0)
        {
            $config['height']++;
        }
        $img_type = 'landscape';
    }
    else
    {
        // square image
        $config['width'] = $thumb_size;
        $config['height'] = $thumb_size;
        $img_type = 'square';
    }

    $this-&gt;load-&gt;library('image_lib');
    $this-&gt;image_lib-&gt;initialize($config);
    $this-&gt;image_lib-&gt;resize();

    // reconfigure the image lib for cropping
    $conf_new = array(
        'image_library' =&gt; 'gd2',
        'source_image' =&gt; $img_thumb,
        'create_thumb' =&gt; FALSE,
        'maintain_ratio' =&gt; FALSE,
        'width' =&gt; $thumb_size,
        'height' =&gt; $thumb_size
    );

    if ($img_type == 'wide')
    {
        $conf_new['x_axis'] = ($config['width'] - $thumb_size) / 2 ;
        $conf_new['y_axis'] = 0;
    }
    else if($img_type == 'landscape')
    {
        $conf_new['x_axis'] = 0;
        $conf_new['y_axis'] = ($config['height'] - $thumb_size) / 2;
    }
    else
    {
        $conf_new['x_axis'] = 0;
        $conf_new['y_axis'] = 0;
    }

    $this-&gt;image_lib-&gt;initialize($conf_new);

    $this-&gt;image_lib-&gt;crop();
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://superdit.com/2010/07/14/cropping-image-to-square-dimension-with-codeigniter/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>CRUD using CodeIgniter and EXTJS Grid – Part 3</title>
		<link>http://superdit.com/2010/07/13/crud-using-codeigniter-and-extjs-grid-part-3/</link>
		<comments>http://superdit.com/2010/07/13/crud-using-codeigniter-and-extjs-grid-part-3/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 03:55:08 +0000</pubDate>
		<dc:creator>aditia rahman</dc:creator>
				<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[Extjs]]></category>
		<category><![CDATA[grid]]></category>

		<guid isPermaLink="false">http://superdit.com/?p=1561</guid>
		<description><![CDATA[This is the final post of the series CodeIgniter and Extjs CRUD, if you want to read the previous posts, here the first part and the second part of this post. Basically we already finish all the crud feature on the second part this only another common feature to add in the application, so we<a href="http://superdit.com/2010/07/13/crud-using-codeigniter-and-extjs-grid-part-3/" class="read-more">Continue Reading</a>]]></description>
			<content:encoded><![CDATA[<p>This is the final post of the series CodeIgniter and Extjs CRUD, if you want to read the previous posts, here <a href="http://superdit.com/2010/07/10/crud-using-codeigniter-and-extjs-grid-part-1/" target="_blank">the first part</a> and <a href="http://superdit.com/2010/07/12/crud-using-codeigniter-and-extjs-grid-part-2/" target="_blank">the second part</a> of this post. Basically we already finish all the crud feature on the second part this only another common feature to add in the application, so we will add a quick search  field on the grid, and what you need is the search grid plugin, I&#8217;m using the extjs example search field plugin from this <a title="Tutorial:Grid PHP SQL Part1" href="http://www.sencha.com/learn/Tutorial:Grid_PHP_SQL_Part1" target="_self">extjs grid tutorial</a>, you can download the complete code and find this file <em>searchfield.js </em>and put it your desire folder, in this post i put on the <em>&#8220;assets/js/ext/plugins/&#8221; </em>folder. Now all you have to do just include the js file in the view file and change the controller method.<span id="more-1561"></span></p>
<p><strong>This is what to be included in view</strong> <em>&#8220;system/views/user/index.php&#8221;</em></p>
<pre class="brush: xml; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot; src=&quot;&lt;?php echo base_url(); ?&gt;assets/js/ext/plugins/searchfield.js&quot;; ?&gt;&quot;&gt;&lt;/script&gt;
</pre>
<p>Create and add new search field plugin to the grid toolbar</p>
<pre class="brush: jscript; title: ; notranslate">
// the new search field
var searchUsers = new Ext.app.SearchField({
    store: strUsers,
    params: {start: 0, limit: 10},
    width: 180,
    id: 'fieldUsersSearch'
});

// add to the toolbar grid
var tbUsers = new Ext.Toolbar({
    items:[{
        text: 'Add',
        icon: BASE_ICONS + 'user_add.png',
        handler: function() {
            var User = gridUsers.getStore().recordType;
            var u = new User({
                fullname: 'New Full Name',
                email: 'New Email',
                country: 'Water Seven',
                occupation: 'Occupation',
                birthdate: '1899-10-10'
            });
            gridUsers.stopEditing();
            strUsers.insert(0, u);
            gridUsers.startEditing(0, 0);
        }
    }, '-', {
        text: 'Save Selected',
        disabled: true,
        id: 'btnSave',
        icon: BASE_ICONS + 'save.gif',
        handler: updateUsers
    }, '-', {
        text: 'Delete',
        icon: BASE_ICONS + 'user_delete.png',
        handler: deleteUsers
    }, '-&gt;', searchUsers]
});
</pre>
<p>Alternatively you can use saki grid search plugin follow this link <a href="http://gridsearch.extjs.eu/" target="_blank">http://gridsearch.extjs.eu/</a></p>
<p><strong>And a little modification in controller</strong> <em>&#8220;system/controller/user.php&#8221;</em></p>
<p>When<em> </em>you add search grid and doing a search query, the search field will give <em>$_POST['query'] </em>to the server and all we have to do is check whether the <em>$_POST['query'] </em>is set or not, if is set then do some query LIKE, in codeigniter you can see on the <a href="http://codeigniter.com/user_guide/database/active_record.html#select" target="_blank">active record class</a> .</p>
<pre class="brush: php; title: ; notranslate">
public function ext_get_all()
{
    $start = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
    $limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : 10;

    if (isset($_POST['query']))
    {
        $this-&gt;db-&gt;like('users.fullname', $_POST['query']);
        $this-&gt;db-&gt;or_like('users.email', $_POST['query']);
        $this-&gt;db-&gt;or_like('users.occupation', $_POST['query']);
        $this-&gt;db-&gt;or_like('users.birthdate', $_POST['query']);
        $this-&gt;db-&gt;or_like('countries.country_name', $_POST['query']);
    }

    $this-&gt;db-&gt;select('users.*, countries.country_name');
    $this-&gt;db-&gt;from('users');
    $this-&gt;db-&gt;join('countries',
            'countries.id = users.country_id');
    $this-&gt;db-&gt;order_by('users.fullname');

    $this-&gt;db-&gt;limit($limit, $start);

    $query = $this-&gt;db-&gt;get();
    $results = $this-&gt;db-&gt;count_all('users');
    $arr = array();
    foreach ($query-&gt;result() as $obj)
    {
        $arr[] = $obj;
    }
    echo '{success:true,results:'. $results .
            ',rows:'.json_encode($arr).'}';
}
</pre>
<p>you can download all the source code in this post and here the final screen thumbnail result from all the of the post</p>
<p style="text-align: center;"><img class="alignnone size-full wp-image-1571" title="localhost_ci_extjs_crud3" src="http://superdit.com/wp-content/uploads/2010/07/localhost_ci_extjs_crud3.png" alt="ci_extjs_crud_3_final" width="500" height="235" /></p>
<p style="text-align: center;"><a href="http://www.2shared.com/file/wJPFd-TG/CRUD_using_CodeIgniter_and_EXT.html" target="_blank">Download Source</a></p>
]]></content:encoded>
			<wfw:commentRss>http://superdit.com/2010/07/13/crud-using-codeigniter-and-extjs-grid-part-3/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>CRUD using CodeIgniter and EXTJS Grid – Part 2</title>
		<link>http://superdit.com/2010/07/12/crud-using-codeigniter-and-extjs-grid-part-2/</link>
		<comments>http://superdit.com/2010/07/12/crud-using-codeigniter-and-extjs-grid-part-2/#comments</comments>
		<pubDate>Mon, 12 Jul 2010 07:45:48 +0000</pubDate>
		<dc:creator>aditia rahman</dc:creator>
				<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[Extjs]]></category>
		<category><![CDATA[grid]]></category>

		<guid isPermaLink="false">http://superdit.com/?p=1544</guid>
		<description><![CDATA[This post is continuation of the part 1, in part 1 we already created the Extjs grid with pagination and load the store grid from the database, in this part we will add the save, edit and delete feature to that grid, and for make it easier it will use the editor grid. First Edit<a href="http://superdit.com/2010/07/12/crud-using-codeigniter-and-extjs-grid-part-2/" class="read-more">Continue Reading</a>]]></description>
			<content:encoded><![CDATA[<p>This post is continuation of the <a href="http://superdit.com/2010/07/10/crud-using-codeigniter-and-extjs-grid-part-1/" target="_blank">part 1</a>, in part 1 we already created the Extjs grid with pagination and load the store grid from the database, in this part we will add the save, edit and delete feature to that grid, and for make it easier it will use the editor grid.</p>
<p><strong>First Edit The View </strong>( in <em>&#8220;application/views/user/index.php&#8221; )</em></p>
<p>We will use the editorGrid, one of them should be editable on the combobox field and the value is fetched from the database, so we create country store component and set like the code below (in this step we haven&#8217;t created the method to get all countries. it described in the controller section).<span id="more-1544"></span></p>
<pre class="brush: jscript; title: ; notranslate">
var strCountries = new Ext.data.Store({
    reader: new Ext.data.JsonReader({
        fields: ['id', 'country_name'], root: 'countries'
    }),
    proxy: new Ext.data.HttpProxy({
        url: BASE_URL + 'user/ext_get_all_countries', method: 'POST'
    })
});
</pre>
<p>Now edit the toolbar so it can manipulate the grid and the data inside it, the <em>&#8220;Add&#8221; </em>button<em> </em>is to creating new data by adding the new row on the grid, and the user has to double click the new row to be edited. <em>&#8220;Save Selected&#8221; </em>button is to save the selected row button, it means user have to click the button and select the row to be saved, means can save multiple row at the save time. Last is <em>&#8220;Delete&#8221; </em>button that can be delete multiple row.</p>
<pre class="brush: jscript; title: ; notranslate">
var tbUsers = new Ext.Toolbar({
    items:[{
        text: 'Add',
        icon: BASE_ICONS + 'user_add.png',
        handler: function() {
            var User = gridUsers.getStore().recordType;
            var u = new User({
                fullname: 'New Full Name',
                email: 'New Email',
                country: 'Water Seven',
                occupation: 'Occupation',
                birthdate: '1899-10-10'
            });
            gridUsers.stopEditing();
            strUsers.insert(0, u);
            gridUsers.startEditing(0, 0);
        }
    }, '-', {
        text: 'Save Selected',
        disabled: true,
        id: 'btnSave',
        icon: BASE_ICONS + 'save.gif',
        handler: updateUsers
    }, '-', {
        text: 'Delete',
        icon: BASE_ICONS + 'user_delete.png',
        handler: deleteUsers
    }]
});

function updateUsers() {
    var sm = gridUsers.getSelectionModel();
    var sel = sm.getSelections();
    var data = '';
    for (i = 0; i&lt;sel.length; i++) {
        data = data + sel[i].get('id') + ';'
                + sel[i].get('fullname')
                + ';' + sel[i].get('email')
                + ';' + sel[i].get('country_id')
                + ';' + sel[i].get('occupation')
                + ';' + sel[i].get('birthdate')
                + '||';
    }
    Ext.Ajax.request({
        url: BASE_URL + 'user/ext_update',
        method: 'POST',
        params: { postdata: data }
    });
    strUsers.load();
}

function deleteUsers() {
    Ext.Msg.show({
        title: 'Confirm',
        msg: 'Delete Selected Users ?',
        buttons: Ext.Msg.YESNO,
        fn: function(btn) {
            if (btn == 'yes') {
                var sm = gridUsers.getSelectionModel();
                var sel = sm.getSelections();
                var data = '';
                for (i = 0; i&lt;sel.length; i++) {
                    data = data + sel[i].get('id') + ';';
                }
                Ext.Ajax.request({
                    url: BASE_URL + 'user/ext_delete',
                    method: 'POST',
                    params: { postdata: data }
                });
                strUsers.load();
            }
        }
    });
}
</pre>
<p>And don&#8217;t forget to change the grid panel component from <em>Ext.grid.GridPanel</em> to <em>Ext.grid.EditorGridPanel </em>and add the editor property to each column like this one.</p>
<pre class="brush: jscript; title: ; notranslate">
columns: [
    cbGrid, {
        header: &quot;Fullname&quot;,
        dataIndex: 'fullname',
        width: 180,
        editor: new Ext.form.TextField({
            allowBlank: false
        })
    }, {
        header: &quot;Email&quot;,
        dataIndex: 'email',
        width: 180,
        editor: new Ext.form.TextField({
            allowBlank: false,
            vtype: 'email'
        })
    }, {
        header: &quot;Country&quot;,
        dataIndex: 'country_name',
        width: 120,
        editor: new Ext.form.ComboBox({
            id: 'cbCountry',
            triggerAction: 'all',
            store: strCountries,
            valueField: 'id',
            displayField: 'country_name'
        })
    }, {
        header: &quot;Occupation&quot;,
        dataIndex: 'occupation',
        width: 120,
        editor: new Ext.form.TextField({
            allowBlank: false
        })
    }, {
        header: &quot;Birth&quot;,
        dataIndex: 'birthdate',
        width: 80,
        renderer : Ext.util.Format.dateRenderer('d/m/Y'),
        editor: new Ext.form.DateField({
            format: 'd/m/Y',
            allowBlank: false
        })
    }
]
</pre>
<p><strong>Second Edit The Controller</strong> (in <em>&#8220;application/controllers/user.php&#8221;)</em></p>
<p>Add new function inside the controller to get all the countries, add user, edit user and delete user. The first snippet below is function to get all the countries data, ideally I always create another controller because it accessing the different table and this country data have <em>&#8220;has one&#8221; </em>relationship to user controller, but in this post to make it fast I put that function in the same controller.</p>
<pre class="brush: php; title: ; notranslate">
public function ext_get_all_countries()
{
    $this-&gt;db-&gt;order_by('country_name');
    $query = $this-&gt;db-&gt;get('countries');
    $json = &quot;{'countries':[&quot;;
    foreach($query-&gt;result() as $data)
    {
        $json .= '{&quot;id&quot;:&quot;'.$data-&gt;id .
                '&quot;, country_name:&quot;' . $data-&gt;country_name.'&quot;},';
    }
    $json .= &quot;]}&quot;;
    echo $json;
}
</pre>
<p>And next is adding function for adding new data and edit existing data, you can see below there are looping when inserting the data, it because from the Extjs grid send multiple value, so I need to break down in array using <em>explode</em> function ini PHP, and there some converting date format cause the Extjs given the different date format when converting to string than mysql.</p>
<pre class="brush: php; title: ; notranslate">
public function ext_update()
{
    /* ex ext date: 1899-11-27T00:00:00
       mysql : YYYY-MM-DD */

    $records = explode('||', $_POST['postdata']);

    foreach ($records as $row)
    {
        $field = explode(';', $row);

        $birthdate = substr($field[5], 0, 10);

        $data = array(
            'fullname' =&gt; $field[1],
            'email' =&gt; $field[2],
            'occupation' =&gt; $field[4],
            'birthdate' =&gt; $birthdate
        );

        if (is_numeric($field[3]))
        {
            $data['country_id'] = $field[3];
        }
        else
        {
            $data['country_id'] = 1;
        }

        if (is_numeric($field[0]))
        {
            $this-&gt;db-&gt;where('id', $field[0]);
            $this-&gt;db-&gt;update('users', $data);
        }
        else
        {
            $this-&gt;db-&gt;insert('users', $data);
        }
    }
}
</pre>
<p>And the last is to delete all selected row from the grid, it is the way from the above snippet, the id that we want to deleted<br />
consolidated in one string, and php explode it to an array</p>
<pre class="brush: php; title: ; notranslate">
public function ext_delete()
{
    $records = explode(';', $_POST['postdata']);
    foreach($records as $id)
    {
        $this-&gt;db-&gt;where('id', $id);
        $this-&gt;db-&gt;delete('users');
    }
}
</pre>
<p>Well that for the part two, most feature have already been added for the CRUD grid, for part just for finishing I may add a quaick search field on the grid, and here&#8217;s below the complete code from this post.</p>
<p style="text-align: center;"><a href="http://www.box.net/shared/9f0h7e6q0q" target="_blank">Download Source</a></p>
]]></content:encoded>
			<wfw:commentRss>http://superdit.com/2010/07/12/crud-using-codeigniter-and-extjs-grid-part-2/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>CRUD using CodeIgniter and EXTJS Grid &#8211; Part 1</title>
		<link>http://superdit.com/2010/07/10/crud-using-codeigniter-and-extjs-grid-part-1/</link>
		<comments>http://superdit.com/2010/07/10/crud-using-codeigniter-and-extjs-grid-part-1/#comments</comments>
		<pubDate>Sat, 10 Jul 2010 02:50:42 +0000</pubDate>
		<dc:creator>aditia rahman</dc:creator>
				<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[Extjs]]></category>
		<category><![CDATA[grid]]></category>

		<guid isPermaLink="false">http://superdit.com/?p=1406</guid>
		<description><![CDATA[In this post I want to share how to create simple CRUD (create, read, update, delete) using codeigniter ExtJS editor grid. In this first part, we will setup the database schema, codeigniter and extjs. I limited this first part, only setup fetching data from database and pagination grid in extjs grid. 1. Create Database Schema<a href="http://superdit.com/2010/07/10/crud-using-codeigniter-and-extjs-grid-part-1/" class="read-more">Continue Reading</a>]]></description>
			<content:encoded><![CDATA[<p>In this post I want to share how to create simple CRUD (create, read, update, delete) using codeigniter ExtJS editor grid. In this first part, we will setup the database schema, codeigniter and extjs. I limited this first part, only setup fetching data from database and pagination grid in extjs grid.</p>
<p><strong>1. Create Database Schema</strong></p>
<p>The table that we will use is two tables with &#8220;has one&#8221; relationship, namely users table with foreign key <em>country_id </em>and countries table that store all the countries data, so when we want to know the country name from the users we have to get from the countries table, and here the sql for creating the table.<span id="more-1406"></span></p>
<pre class="brush: sql; title: ; notranslate">
--
-- Table structure for table `countries`
--

CREATE TABLE IF NOT EXISTS `countries` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `country_name` varchar(150) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=102 ;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fullname` varchar(150) NOT NULL,
  `email` varchar(100) NOT NULL,
  `country_id` int(11) NOT NULL DEFAULT '1',
  `occupation` varchar(150) NOT NULL,
  `birthdate` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ;
</pre>
<p><strong>2. Setup Codeigniter</strong></p>
<p>Like we always do in previous tutorial, there are the files that we have to setup: <em>config.php</em>, <em>database.php</em>, <em>autoload.php</em> and <em>route.php, </em>all this files are inside the same folder in codeigniter namely <em>&#8220;application/system/config&#8221;, </em>and<em> </em>don&#8217;t forget to setup the extjs file.<br />
<em>config.php </em>file</p>
<pre class="brush: php; title: ; notranslate">
$config['base_url'] = &quot;http://localhost/ci_extjs_crud/&quot;;
</pre>
<p><em>database.php</em> file</p>
<pre class="brush: php; title: ; notranslate">
$db['default']['hostname'] = &quot;localhost&quot;;
$db['default']['username'] = &quot;root&quot;;
$db['default']['password'] = &quot;&quot;;
$db['default']['database'] = &quot;ci_extjs_crud&quot;;
$db['default']['dbdriver'] = &quot;mysql&quot;;
</pre>
<p><em>autoload.php</em> file</p>
<pre class="brush: php; title: ; notranslate">
$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');
</pre>
<p><em>route.php</em> file</p>
<pre class="brush: php; title: ; notranslate">
$route['default_controller'] = &quot;user&quot;;
</pre>
<p>we will create user class so set the default route to user and the extjs file looks on my project folder (inside codeigniter)</p>
<p style="text-align: center;"><img class="alignnone size-full wp-image-1520" title="ci-ext-folder" src="http://superdit.com/wp-content/uploads/2010/07/ci-ext-folder.png" alt="ci-ext-folder" width="242" height="254" /></p>
<p>I already remove only the used extjs file so, it much smaller than the fresh copy</p>
<p><strong>3. Create The Controller</strong></p>
<p>Create file <em>image.php </em>inside codeigniter controller folder and add this code below, this class only have 3 function. First function is to initialize the controller class, the <em>index </em>function only to render the view file and the <em>ext_get_all </em>function is to get the data from database that will displayed on the grid, you can see inside that function there are code to handle the pagination and the related table, the output from this function have to be in JSON format, so it will make easier to be displayed on Extjs grid.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

class User extends Controller {

    public function  __construct()
    {
        parent::Controller();
    }

    public function index()
    {
        $this-&gt;load-&gt;view('user/index');
    }

    public function ext_get_all()
    {
        $start = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
	$limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : 10;

        $this-&gt;db-&gt;select('users.*, countries.country_name');
        $this-&gt;db-&gt;from('users');
        $this-&gt;db-&gt;join('countries',
                'countries.id = users.country_id');

        $this-&gt;db-&gt;limit($limit, $start);

        $query = $this-&gt;db-&gt;get();
        $results = $this-&gt;db-&gt;count_all('users');
        $arr = array();
        foreach ($query-&gt;result() as $obj)
        {
            $arr[] = $obj;
        }
        echo '{success:true,results:'. $results .
                ',rows:'.json_encode($arr).'}';
    }
}
</pre>
<p><strong>4. Create The View</strong></p>
<p>Create file <em>index.php </em>inside folder <em>&#8220;application/views/user/&#8221;, </em>just include the extjs file on the header that linked to file that we already setup on the step 2, and add this code below in the javascript tag (whatever you like whether in the separate file or in the same file)</p>
<pre class="brush: jscript; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot;&gt;
var BASE_URL = '&lt;?php echo base_url(); ?&gt;' + 'index.php/';
var BASE_PATH = '&lt;?php echo base_url(); ?&gt;';
var BASE_ICONS = BASE_PATH + 'assets/icons/';
Ext.onReady(function() {
    var strUsers = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            fields: [
                'id', 'fullname', 'email', 'country_id',
                'country_name', 'occupation', 'birthdate'
            ],
            root: 'rows', totalProperty: 'results'
        }),
        proxy: new Ext.data.HttpProxy({
            url: BASE_URL + 'user/ext_get_all',
            method: 'POST'
        })
    });

    var tbUsers = new Ext.Toolbar({
        items:[{
            text: 'Add',
            icon: BASE_ICONS + 'user_add.png'
        }, '-', {
            text: 'Delete',
            icon: BASE_ICONS + 'user_delete.png'
        }]
    });

    var cbGrid = new Ext.grid.CheckboxSelectionModel();

    var gridUsers = new Ext.grid.GridPanel({
        frame: true, border: true, stripeRows: true, sm: cbGrid,
        store: strUsers, loadMask: true, title: 'Users List',
        style: 'margin:0 auto;', height: 330, width: 722,
        columns: [
            cbGrid, {
                header: &quot;Fullname&quot;,
                dataIndex: 'fullname',
                width: 180
            }, {
                header: &quot;Email&quot;,
                dataIndex: 'email',
                width: 180
            }, {
                header: &quot;Country&quot;,
                dataIndex: 'country_name',
                width: 120
            }, {
                header: &quot;Occupation&quot;,
                dataIndex: 'occupation',
                width: 120
            }, {
                header: &quot;Birth&quot;,
                dataIndex: 'birthdate',
                width: 80,
                renderer : Ext.util.Format.dateRenderer('d/m/Y')
            }
        ],
        tbar: tbUsers,
        bbar: new Ext.PagingToolbar({
            pageSize: 10,
            store: strUsers,
            displayInfo: true
        })
    });

    gridUsers.render('divgrid');
    strUsers.load();
});
&lt;/script&gt;
</pre>
<p>The first screenshot from this tutorial is something like this and you can download all the code below, i have included the sql schema and all the extjs file that needed in this post.</p>
<pre style="text-align: center;"><img class="alignnone size-full wp-image-1526" title="ExtJS CodeIgniter-CRUD_Part_1" src="http://superdit.com/wp-content/uploads/2010/07/ExtJS-CodeIgniter-CRUD_Part_1.png" alt="ExtJS CodeIgniter-CRUD_Part_1" width="500" height="238" /></pre>
<p style="text-align: center;"><a href="http://www.box.net/shared/nsdm0spb00" target="_blank">Download Source</a></p>
]]></content:encoded>
			<wfw:commentRss>http://superdit.com/2010/07/10/crud-using-codeigniter-and-extjs-grid-part-1/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
	</channel>
</rss>

