Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

Code Block
themeConfluence
languagejavascript
titlesupplyItem.js
isc.RestDataSource.create({
    "ID": "supplyItemsuppyItem",
    "fields": [
		{ name: [
        {"name":"itemID", "type": "sequence", "hidden": "true", "primaryKey": "true" },
        { "name": "itemName", "type": "text", "title": "Item", "length": "128", "required": "true" },
        { "name": "SKU", "type": "text", "title": "SKU", "length": "10", "required": "true" },
        { "name": "description", "type": "text", "title": "Description", "length": "2000" },
        { "name": "category", "type": "text", "title": "Category", "length": "128", "required": "true", foreignKey: "supplyCategory.categoryName" },
        { "name": "units", "type": "enum", "title": "Units", "length": "5",
            "valueMap": ["Roll", "Ea", "Pkt", "Set", "Tube", "Pad", "Ream", "Tin", "Bag", "Ctn", "Box"]
        },
        { "name": "unitCost", "type": "float", "title": "Unit Cost", "required": "true",
            "validators": [
                { "type": "floatRange", "min": "0", "errorMessage": "Please enter a valid (positive) cost" },
                { "type": "floatPrecision", "precision": "2", "errorMessage": "The maximum allowed precision is 2" }
            ]
        },
  
        { "name": "inStock", "type": "boolean", "title": "In Stock" },
        { "name": "nextShipment", "type": "date", "title": "Next Shipment"}
}    	],  
    "dataFormat": "json",
    criteriaPolicy:"dropOnChangeoperationBindings",: [
   operationBindings: [             { "operationType": "fetch", "dataProtocol": "postMessage", "dataURL": "fetch.php" },
            				{ "operationType": "add", "dataProtocol": "postMessage", "dataURL": "add.php" },
            { operationType				{ "operationType": "update", "dataProtocol": "postMessage", "dataURL": "update.php" },
            				{ "operationType": "remove", "dataProtocol": "postMessage", "dataURL": "remove.php" }
            ] 
}); 

Notice that this definition is almost a JSON file, with a small addendum at the beginning and the end. If the 'isc.RestDataSource.create(' part from the beginning and ');' part from the end were removed, this would give a valid JSON object which will be deserialized as a JSON object.

...

Code Block
themeEclipse
languagephp
titleDataSource.php
firstline53
linenumberstrue
public function execute($request)
{
	 switch($request->operationType)
	 {
		 case 'fetch':                    
			return $this->fetch($request);
		 case 'add':
			return $this->add($request);
		 case 'update':                                    
			return $this->update($request);
		 case 'remove':                                       
			return $this->remove($request);
	 }
}
private function add($request)
{            
	$ds = $this->data_source;
	// get the table name from data source
	$tbl_name = $ds['ID'];
	$new_data = $request->data;
	$insert_values = array();
	// make the query            
	$columns = '';
	$values = '';
	foreach($new_data as $key => $value)
	{            
	   $columns .=  $key.',';
	   $values .=  "'".$value."'?,";   
	   array_push($insert_values, $value);         	}    
	}         
	// remove the last comma
	$columns = substr($columns, 0, strlen($columns) - 1);
	$values = substr($values, 0, strlen($values) - 1);
	// result insert query
	$insert_query = 'INSERT INTO '.$tbl_name.' ('.$columns.') VALUES ('.$values.')';
	
	// Run the insert query
	R::exec($insert_query, $insert_values);
	//DSResponse
	$response = new DSResponse();      
	$response->setData($new_data);            
	$response->setStatus(0);  
	return $response;
}
private function update($request)
{
	$old_data = $request->oldValues;
	$update_data = $request->data;
	$ds = $this->data_source;
	
	// update all fields which have changed. they are defined in the data property
	if ( count($request->getDataKeys()) != 0 )
	{
		 foreach($request->data as $key => $value)
		 {
			$old_data[$key] = $value;
		 }
	}     
	
	// get the id  by primary key
	$values = array();
	
	
	// get the table name from data source
	$tbl_name = $ds['ID'];            
	$set_value = '';
	// make the update query
	foreach($old_data as $key => $value)
	{          
		
		
			$set_value .= "$key = '$value'?,"; 
			array_push($values, $value);             	} 	// remove the last comma
		$set_value = 
	}
	array_push($values, $old_data['itemID']);
	
	// remove the last comma
	$set_value = substr($set_value, 0, strlen($set_value) - 1);
	// result insert query
	$update_query = 'UPDATE '.$tbl_name.' SET '.$set_value.' WHERE itemID = '.$old_data['itemID']?';
	 R::exec($update_query, $values);
	
	// build the criteria
	//DSResponse
	$response = new DSResponse();      
	$response->setData($old_data);            
	$response->setStatus(0);  
	return $response;
}
private function remove($request)
{
	$ds = $this->data_source;            
	// get the table name from data source
	$tbl_name = $ds['ID'];            
	$new_data = $request->data;
	// make the delete query
	$itemID = $new_data['itemID'];
	$delete_query = "DELETE FROM $tbl_name WHERE itemID = $itemID?";
	// Run the insert query
	R::exec($delete_query, array($itemID));
										 
	//DSResponse
	$response = new DSResponse();      
	$response->setData($new_data);            
	$response->setStatus(0);  
	return $response;
}
private function fetch($request)
{   
	// get the DataSource
	$ds = $this->data_source;   
	$tbl_name = $ds['ID']; 	  
	$query// =check "selectthe * from $tbl_name s ";
	$query_countadvanced cretira             
   $query_result = $this->buildStandardCriteria($request); 
	
	$query = "select count(*) from $tbl_name s";
	
	// build up the query
    $query .= $this->buildStandardCriteria($request);	 
	$query_result['query'];
   
	// sort by
	if( !empty($request->sortBy) )
	{
		// set the orderBy
		$query .= " order by ";
		
		// we start to build a coma separated list of items. First item won't have coma
		// but every possible next will do
		$seperator = "";
		foreach($request->sortBy as $index => $sort)
		{ 
			
			// if column name is with -, then ordering is descending, otherwise ascending
			if ( strpos($index, '-') === 0 )
			{
				$query .= $seperator . $sort . " ASC";
			} else
			{
				$query .= $seperator . substr($sort, 1) . " DESC";
			}
			$separator  = ',';
		}
	}
	
 
	//DSResponse
convert	$response the= payload to our DRequest object    new DSResponse();        
	// get the count        
	$products_count = R::getAll($query_count);
	$count = $products_count[0]['count(*)'];
	, $query_result['value']);   
	//DSResponse
	$response = new DSResponse(); get the count        	  	$products = R::getAll($query);      	  
	$count = count($products);           
	$response->setData($products);
	$response->setStartRow($request->startRow);
	$response->setEndRow($request->endRow);
	$response->setTotalRows($count);
	$response->setStatus(0);  
	
	// sanity check, if no rows, return 0
	if ($response->getEndRow() < 0 ) 
	{
		$response->setEndRow(0);
	}
	
	return $response;
}

...

Code Block
languagephp
private function buildStandardCriteria($request)
{
	$result = array();
	$query = '';              
	$query_count$values = ''array();
	
	if ( count($request->getDataKeys()) != 0 )
	{
	   $query .= ' where ';               
		 
		foreach($request->data as $key => $value)
		{                       
			// get the field    
			$field = $this->getField($key);
			if(!empty($field))                                        
			{
				$type = $field['type'];
				
				if( $type == "text" ||
					$type == "link" ||
					$type == "enum" ||
					$type == "image" ||
					$type == "ntext" )
				{
					//$query .= "s." . $key . " like " . " '%" . $value . "%' and " ;             				} else 				{
					"s." .                     
					$query .= $key . "=" . " ' like ? and " ;                                    
					array_push($values, "%".$value."%");
				} else
				{
					"s." . $value$key . "' = ? and " ;        
				}	array_push($values, $value);                            
				}
								
			$query_count .= "s." . $key . " like " . "'%" . $value . "%' and " ;                                      
			}
		}
		
		// remove 'and' of the query                 
		$query = substr($query, 0, strrpos($query, 'and'));           
	}    
			 
	$result['query'] = $query;
	$result['value'] = $values;
	
	return $query$result;
} 
Note

In this article, the RedBean library was used to get the data from the database on the line 185 and the line 191.

...

Code Block
themeEclipse
languagejavascript
titleus.js
isc.ListGrid.create({
    "ID": "supplyItemGridsupplyItem",
    "width": 700, "height": 224, "alternateRecordStyles": true,
    "dataSource": supplyItem,
    "showFilterEditor": true,
    "autoFetchData":true,
    "dataPageSize":20,
    "canEdit":true,
    "canRemoveRecords":true
});

Next, There needs to be a method for adding new records. Add a button which, on click, will trigger a new record being available for editing in the grid. The source for this is:

Code Block
languagejavascript
titleui.js
isc.IButton.create({
    top: 250,
    title: "Edit New",
    click: "supplyItemGridsupplyItem.startEditingNew()"
});

At this point, all four operations are implemented (add, update, remove, fetch). However please note these are just plain samples,and do not contain anything other than basic type error validation.

...