Array as ExtJS baseParams

In this tutorial I’ll walk you through using the results of an array as an ExtJS baseParams, with the help of php implode and php explode. ExtJS baseParams are parameters that can be passed with all requests, parameters are encoded as standard HTTP parameter using Ext.urlEncode. A typical basepaParams usage may look like e.g. baseParams: {id: ’123′, foo: ‘bar’}, however, we’ll be using the results of an array as our baseParams instead of a single value.
I have a row editor grid we use to submit new records to be inserted into a mysql database (reason for this is beyond the
scope of this tutorial), a modified version of a CRUD (Create, Read, Update and Delete) application. I say modified because we don’t want to update or delete records from our database (this is a data entry grid), we’ll just be using the grid to insert new records into the database, although we are still able to create, read, update and delete entries from the grid itself.
Complicated ?? Well, not really. We use the grid to insert new records into a mysql database, however, I have the grid set up so all records are only inserted when the user clicks the save button, by adding this property to our grid store, autoSave: false.
Ok, so our grid has a Json reader, a Json writer, our data proxy and data store, along with our save button. We create a handler for our save button, which in turn is a function that handles all data for us.
I wanted a function to check all records coming from the grid against our database, so no duplicate records would be
created and also notify the user, this is where our array comes in. We’ve chosen to grab all item numbers
(they are our unique key in mysql) from our grid and store them in an array, then pass them along to our file that’ll check against the database for existing records, and if no records are found, we insert them, otherwise, notify the user so he/she can change the necessary entries in the grid.
Ok, too much talking, this is how we do it:
Here’s our save button, nothing special, but notice the handler:

[{
  text: '... Save',
  id: 'save_records',
  handler: this.onSave,
  scope: this
}]

Here’s the handler:

 /**
     * onSave
     */
    onSave : function(btn, ev) {
    	
// We need to check if any of the item numbers entered exist       	
// First we obtain all item numbers entered in the grid and assign 
//  them to a variable    	
    	
// Create an array
var _arrSv = new Array();
    	
// Get all records from the grid
var _rcds =  store.getModifiedRecords();
    	
// Loop through all records and add each item number to the array
for (var _i = 0; _i < _rcds.length; _i++) 
   {
   	_arrSv.push([	
        _rcds[_i].get("itemnumber") // itemnumber is the field name from our Jsonreader
              ]);
    	}
  
// Now that we have the array above, the array containing our 
// data is sent to datastore_check (the datastore used to check 
// if the itemnumber exists) using the baseparam 
    	datastore_check.baseParams = {
    			kn: Ext.encode(_arrSv)  // We'll access this baseparam (kn) from kncheck.php  			
    	};
    	
     	
    	
// We manipulate the data with kncheck.php (the file checks the 
// database for existing item numbers) and then we 
// notify the user if the item number already exists
    	datastore_check.on('load', function() {
    	
// we check if there were any results (meaning the item number was found, which 
// means it already exists)		
    		 if (this.getCount() > 0){
 // create the array
    			 var kar = new Array();
    			 
 // count how many items were found
    			 var c = this.getCount();
    			 
 // Loop through all items and add each of them to the array
    			 for (var i = 0; i < c; i++) 
    		    	{
    				 kar.push([ 
    				           this.getAt(i).get('ControlNumber') // This comes from datastore_check
    				           ]);
    		    	}
               	     			 
		    	Ext.MessageBox.show({
		    				 title: 'Duplicate Item !',
		                     msg:"One or more kn exist. Please change duplicate item: <br/>\n\
		                      <br />\n\
		                     " + kar,
		                     buttons: Ext.MessageBox.OK,
		                     animEl: 'mb4',
		                     width:450,
		                     icon: Ext.MessageBox.WARNING
		                 });
    		 
    			 
    	     }   else { 

// No items were found, that means no duplicates, so we go ahead and proceed
// Now we save the data	
	    store.save();
// We then clear our grid and form data
		store.removeAll();
	     	    	 
         		}
    	    	 
    	     }
    	     
    	});    	    	
    	
// Load the check store
    	datastore_check.load();
    	      	
    }

This is what our datastore_check looks like:

 datastore_check = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
          fields : ['ControlNumber'],
          root: 'result'
        }),
        proxy: new Ext.data.HttpProxy({
            url: 'kncheck.php'
        })
    });

These are the proxy, reader, writer and the store for our grid:

var proxy = new Ext.data.HttpProxy({
    url: 'submititem.php'  // This is the file we use to save all new items
});

var reader = new Ext.data.JsonReader({
    totalProperty: 'total',
    successProperty: 'success',
    idProperty: 'id',
    root: 'data',
    messageProperty: 'message' },
 [
  {name: 'controlnumber', mapping: 'controlnumber', allowBlank: false},
  {name: 'warrantyexp', mapping: 'warrantyexp'},
  {name: 'serialnumber', mapping: 'serialnumber'},
  ]);

// The new DataWriter component.
var writer = new Ext.data.JsonWriter({
	encode: true,
        listful: true,
        writeAllFields: true
});

// Store collecting the Proxy, Reader and Writer together.
var store = new Ext.data.Store({
	restful: true,
        proxy: proxy,
        reader: reader,
        writer: writer,
    // Property below disables the grid saving the record whenever 
    // a new one is created. We'll add all records once we are done
    // inserting them in the grid
    autoSave: false
	});

And finally, this is what our kncheck.php file looks like:

<?php


include('../Connections/connect.php'); /// Beyond the scope of this tutorial

//connection String
$erp = mysql_connect($hostname, $username, $password) or die('Could not connect: ' . mysql_error());
//select database
mysql_select_db($database, $erp);
//Select The database
$bool = mysql_select_db($database, $erp);
if ($bool === False){
	print "can't find $database";
}

  		
  	// This is were all our items are. they're passed to this form via baseparams
  	// First we assign our baseparam a variable
  	// items in this var are in the format KN123,KN456,KN789 so we need to clean them up
  	$k = $_POST['kn']; 
  
  	// Start sanitizing everything
  
  	// Here we explode the var above $k and assign each item its own var
  	$knbaseparam = explode(',', $k);
  
        // Now create the array to store all our item numbers
    $knarray = array();
    
    // We loop through all item numbers found, clean the data and assign them to the array
    for ($start=0; $start < count($knbaseparam); $start++) 
        {
	$kn = $knbaseparam[$start];
	
	// remove all weird characters from the item number, it leaves only letters and numbers
	$kn = preg_replace("/[^a-zA-Z0-9s]/", "", $kn);
	
	// Now we need to add single quotes at the begining and at the end of each item number, so when query runs
 	// the kn vars will look like this 'KN12345' instead of KN12345 (if we don't do this the query fails
	$kn = "'" . str_replace(",", "','", $kn) . "'";
	
	// insert each of our item numbers found into the array below 
	$knarray[] = $kn;			
	}
    
    // Now handle the array, we'll join all our item numbers together
    for ($t=0; $t< count($knbaseparam); $t++)
	    {
	// now we join all our kn array elements 
    $allkns = implode(',', $knarray);
    	}
    
// We're done sanitizing our item numbers, so now we run the query to find out if any of them exist
  			  			
$query = "SELECT ControlNumber FROM Inventory WHERE ControlNumber IN ( $allkns ) ";
mysql_select_db($database, $erp);

$result = mysql_query($query, $erp); 
// Test the query
if(!$result){
    die("SQL Query ERROR! " . mysql_error($erp)); 
	}

if (mysql_num_rows($result) > 0){

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
	$myknsearch[] = array(
    	  'ControlNumber' => $row['ControlNumber']
		);
	}

$myData = array('result' => $myknsearch);
echo json_encode($myData); 


	} else { 



echo '{result:0}';			


exit(); 

	}
  
?>

This is it, a long one this time, but hopefully you stuck around to read the entire post. I hope this step by step tutorial has helped you some. Thank you for stopping by and please share with others, after all, code should be free.foscode.com | because code should be free

5 thoughts on “Array as ExtJS baseParams

  1. Nice example. Just some comments, your choice of font/background colours makes it difficult to read your source code and even your blog text. In addition, your source code is getting cut off which means scrolling over to read it.

    Dont get me wrong. I know doing these types of things is time consuming so keep it up!

  2. @Khalil: Thanks for the comments, I’ll work on changing the background so it’ll make easier for others to read the site, along with my code not getting cut off. Thanks for stopping by and hopefully I was able to help you out besides not being able to view the site as well as you would have liked.

  3. @Khalil: I finally got some spare time to change some of the site (most notably the source code area). Hopefully this will help everyone and make it easier to read the code. Thanks Khalil for the suggestion.

  4. Thank you so much for this perfectly-explained tutorial. This is exactly what I’m looking for!

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>