Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
PHPConnectorDHTMLXconnectorisahelperserver-sidelibrarythatenablesaccesstoexternaldatasourcesandbackendsystems.ItsupportsallDHTMLXcomponentsoperatedondata.Thelibraryitselfprovideswideserver-sidefunctionality,suchasdataloading(staticordynamic),saving,filtration,validationetc.CooperationwithDHTMLXDataprocessorallowsyoutomanageinsert/delete/updateoperationsinaddition.
ReleasenotesGuidesCodinghow-tosReferenceSamples
newinversion1.5
Security:
ProtectionfromXSSattacks;PreventingCSRFandXSRFattacks.
Flexibility:
Newmethodsforrenderingdata(supportforstoredprocedurescalls,loadingfromdataarrays);Thepossibilitytosetuserdatawithalltypesofconnectors;Thepossibilitytorenamethequerystatusparameter'!nativeeditor_status';BetterOOPsupport(supportfordatamodelanddatabehaviorclasses);BetterTouchSupport(improveddataformats,addingextratags/sectionstodata);SupportforPHPframeworks(CodeIgniter,YII,CakePHP).
server-siderequirements
FullysupportedDataBases:MySQL,PostgreSQL,Oracle,MSSQL,FileSystemPartiallysupportedDataBases:SQLite,anyPDO|ODBCcompliant(MSAccess,Excel,SQLLite,DB2,FireBird,etc.)PHPversion:5.x
supportedfunctionality
DataloadingforGrid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,FormDatasavingforGrid,TreeGrid,Tree,Scheduler,DataView,FormServer-sidesortingandfilteringforGrid,TreegridDynamicloading(paging)forGrid,Treegrid,Tree,Scheduler,DataView,Combo
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
migrationfromolderversions
0.9→0.96
beforeFilterandbeforeSortingeventsprovideobjectasparameterinsteadofplaindataOrderofparametersforrender_*methodsofTreeGridandTreeconnectorswaschanged.
//0.9
render_table("table","id","fields","parentid")
//1.0
render_table("table","id","fields","extrafields","parentid"
0.96→1.0
beforeOutputeventhasdifferentparameters
1.0→1.5
newversionfilterouthtmlcontentbeforesaving,usethenextcodeifyouwanttorevertlogicofconnectortothepreviousbehavior
ConnectorSecurity::$xss=DHX_SECURITY_TRUSTED;
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
GUIDESPleasenote,throughouttheguidesyou'llseeexamplesthatrelatetogrid.Ifyouuseadifferentcomponentthatsupportsmentionedfunctionality,justreplaceGridConnectorwiththeappropriatetype.Seealistofconnectortypeshere.
GettingstartedGeneralideaofdhtmlxConnector+generallistofconnectorsInitializationSummarizedcomponentsfunctionality
LoadingdataBasicLoadingDynamicLoadingFilteringFormatting/ChangingDatabeforeLoadingSorting
ManagingCreate/Update/DeleteoperationsIntegrationwithdataProcessorandchangingdefaultprocessingMakingqueriesMulti-usersyncSecurityValidationSavingdatachangesmadeinform
DataexporttoExcel,PDFElementaryDBoperationswithdhtmlxConnectorErrorshandlingandloggingEventhandlingExtendingexistingfunctionalityUsingdhtmlxConnectorwiththeCodeIgniter,YII,CakePHPframeworks
GeneralideaofdhtmlxConnectordhtmlxConnectorisaserver-sidelibrarythatletsyouaccessdatasources.Itconsistsofindividualcomponent-specificconnectorsandasetofadditionalonesprovidingadvancedfunctionality.
AdhtmlxConnector'sjobistoprovidenecessarydataexchangeconditionssothatyoudonothavetodealwiththetechnicaldetailsofworkingwithvariousdatastores,systemsorservices.Assuch,eachtypeofdhtmlxConnectorisdesignedtouseaspecificAPI.
Asthelibraryisserver-sideitprovidesdifferentmanipulationsjustonserverbackend:
loadingdata(staticallyordynamically)fromdatabase,FileSystem,Excelfile.server-sidefiltration,sortingandvalidation.
Whenyouneedtodealwithclient-sideaswell,i.e.passdatabacktoserver,youshoulduseDataProcessoradditionally(formoredetailsofthistopic,seethechapter'Client-siderequirement-dataProcessor').
generallistofconnectors
Component-specific:
ChartConnector(relatestodhtmlxChart)ComboConnector(relatestodhtmlxCombo)DataViewConnector(relatestodhtmlxDataView)FormConnector(relatestodhtmlxForm)GridConnector(relatestodhtmlxGrid)SchedulerConnector(relatestodhtmlxScheduler)TreeConnector(relatestodhtmlxTree)TreeGridConnector(relatestodhtmlxTreeGrid)
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Additional(mostimportant):
JSONDataConnector/DataConnector(relatestotouch-orientedlibraries:DHTMLXTouch,DataTable,dhtmlXDataStore)KeyGridConnectorSelectOptionsConnectorTreeGroupConnector/TreeGridGroupConnectorTreeMultitableConnector
Throughoutthedocumentationyou'llseeexamplesthatuse'GridConnector'.Subjecttousingcomponent,replaceitwiththe
neededconnector.
Common
Thereare2connectorsyoucanusefortouch-orientedDHTMLXlibraries(suchasDHTMLXTouch,DataTable,DataStore):
DataConnectorJSONDataConnector
Theybothworkthesameway,butdifferintypeofreturneddata.
<?php
require_once("../../connector/data_connector.php");
require_once("../../connector/db_sqlite.php");
if(!$db=sqlite_open('db',0777,$sqliteerror)){
die($sqliteerror);
}
$data=newJSONDataConnector($db,"SQLite");
$data->render_table("users","id","name,age,city");
?>
DataConnector
DataConnectorgenerates'XML'datafeedasin:
<data>
<itemid="1"title="WarandPeace"author="LeoTolstoy"/>
<itemid="2"title="Hamlet"author="WilliamShakespeare"
<itemid="3"title="MadameBovary"author="GustaveFlaubert"
</data>
JSONDataConnector
JSONDataConnectorgenerates'JSON'datafeedasin:
[
{id:"1",title:"WarandPeace",author:"LeoTolstoy"},
{id:"2",title:"Hamlet",author:"Shakespeare"},
{id:"3",title:"MadameBovary",author:"GustaveFlaubert"}
]
Addingtags/sectionstodata
Startingfromversion1.5,thereisapossibilitytoaddthefirstchildtags,sectionstodatareturnedbytheconnector.Toaddthetag(section),usemethodadd_section.
DataConnector
Forexample,ifyoucalladd_sectionasfollows:
$data=newJSONDataConnector($db,"SQLite");
$data->add_section("config","some_data");
$data->add_section("config2","<column>data1</column><column>data2</column>"
DataConnectorproducesthenextdata:
<data>
<config>some_data</config>
<config2><column>data1</column><column>data2</column></config2
<itemid="1"attr1="qwe"attr2="asd"/>
<itemid="2"attr1="qwe"attr2="asd"/>
</data>
JSONDataConnector
Ifyoucalladd_sectionasfollows:
$data=newJSONDataConnector($db,"SQLite");
$data->add_section("config","'some_data'");
$data->add_section("config2","{column1:'data1'}");
JSONDataConnectorproducesthenextdata:
{
data:[
{'id':'1','attr1':'qwe','attr2':'asd'},
{'id':'2','attr1':'qwe','attr2':'asd'}
],
config:'some_data',
config2:{'column1':'data1'},
}
SimpleDataTransfer
JSONDataConnector/DataConnectorsupportssimplifiedprotocolforCRUDrequests.
getalldata
GETdata.php?action=get
serverresponse-collectionofjson(xml)objects
getinfoforsomespecificrecord
GETdata.php?action=get&id=123
response-json(xml)object
delete
GETdata.php?action=delete
POSTid=123
serverresponse-'true'/'false'
insert
GETdata.php?action=insert
POSTid=123&some=value&other=value
responseonsuccess
true
<new_id>
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
or
false
onfailedinsertoperation
update
GETdata.php?action=delete
POSTid=123&some=value&other=value
response-'true'/'false'
SelectOptionsConnectorSelectOptionsConnectorisusedbythedhtmlxFormcomponenttofillalistofoptionsforthe'select'item.Don'tconfuseSelectOptionsConnectorwithOptionsConnector.ThesecondoneisanauxiliaryconnectorandusedjustinthecontextofdhtmlxGridanddhtmlxSchedulercomponents.SelectOptionsConnectorisanindependentconnectorabletogenerateoutputXMLdata.
So,todefineoptionsoftheselectform'sitemyoushouldmakethefollowing:
1. Onclient-sideyoushouldspecifytheparameter'connector':
varformData=[
{type:"select",label:"Categories",
{type:"button",value:"Proceed"}
];
myForm=newdhtmlXForm("form_container",formData);
2. Onserver-sideyourcodewilllooklike:
<?php
require_once("../codebase/connector/options_connector.php"
$res=mysql_connect("localhost","root","");
mysql_select_db("tasks");
$data=newSelectOptionsConnector($res,"MySQL");
$data->render_table("categories","id","value,label")
?>
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Render_tablemethodtakesthefollowingparameters:
'categories'-thenameoftable.'id'-theidcolumn'value'-thecolumnthatwillbeusedasvaluesofoptions.'label'-thecolumnthatwillbeusedaslabelsofoptions.
InitializationTousefunctionalityofDHTMLXConnector,firstyoushouldinitializeit.Generally,bothclient-andserver-sidesareconcernedinit.
client-side
ifyouneedjustloaddatafromdatabase(withorwithoutdatapreprocessing)
1. Specifyconnectorfileinload(orloadXML)methodofacomponent.
//index.html
myGrid=newdhtmlXGridObject("someContainer");//initializesgrid
...
myGrid.load("my_connector.php");
ifyouneedtoperformanyupdateoperations
1. Includeconnector.jsfile(locatedindhtmlxConnector_php/codebase).
2. Specifyconnectorfileinload(orloadXML)methodofacomponent.
3. InitializedhtmlxDataProcessoronclient-side(readmoreaboutithere).
//index.html
<scriptsrc="codebase/connector/connector.js"></script
myGrid=newdhtmlXGridObject("someContainer");//initializesgrid
...
myGrid.load("my_connector.php");
myDP=newdataProcessor("myconnector.php");//initializesdhtmlxDataProcessor
myDP.init(myGrid);
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
server-side
1. Includeappropriateconnectorfileintothepage.2. CreateDatabaseconnection.3. Instantiateconnectorobject.Linkingvariableisamandatory
parameterinallconstructors.Thesecondparameter(databasetype)-optional.Bydefault“MySQL”.Otherpossiblevariantsseehere.
4. Thelaststepisdataconfiguration.
//my_connector.php
require("connector/grid_connector.php");//connectorfile
$res=mysql_connect("localhost","root","");//dbconnection
mysql_select_db("myDatabase");//dbconnection
$gridConn=newGridConnector($res,"MySQL");//connectorobject;parameters:dbconnectionandthetypeoftheusingdb
$gridConn->render_table("mytable","item_id","item_nm,item_cd"
Samplesofserver-sideinitializationforallcomponents
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
SummarizedcomponentsfunctionalityChartComboDataStoreDataViewFormGridTreeTreeGridScheduler
DHTXMLTouchComponents
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
CHARTFunctionalitysupportedbydhtmlxConnector:
DataloadingFormatting/changingdatabeforeloadingDynamicloadingServer-sidelogging
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
COMBOFunctionalitysupportedbydhtmlxConnector:
DynamicloadingFormatting/changingdatabeforeloadingServer-sidefiltrationServer-sideloggingServer-sidesortingStaticloadingfromdatabasetables,FileSystem,Excelfiles
FunctionalitysupportedbydhtmlConnector&dataProcessor:
Client-sideloggingClient-sidevalidationElementaryDBactionswithdhtmlxConnectorMakingcomplexqueriesMakingsimplequeriesMulti-usersyncServer-sidevalidation
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
DATASTOREFunctionalitysupportedbydhtmlxConnector:
DynamicloadingFormatting/changingdatabeforeloadingServer-sidefiltrationServer-sideloggingServer-sidesortingStaticloadingfromdatabasetables,FileSystem,Excelfiles
FunctionalitysupportedbydhtmlConnector&dataProcessor:
Client-sideloggingClient-sidevalidationElementaryDBactionswithdhtmlxConnectorMakingcomplexqueriesMakingsimplequeriesServer-sidevalidation
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
DATAVIEWFunctionalitysupportedbydhtmlxConnector:
DynamicloadingFormatting/changingdatabeforeloadingServer-sidefiltrationServer-sideloggingServer-sidesortingStaticloadingfromdatabasetables,FileSystem,Excelfiles
FunctionalitysupportedbydhtmlConnector&dataProcessor:
Client-sideloggingClient-sidevalidationElementaryDBactionswithdhtmlxConnectorMakingcomplexqueriesMakingsimplequeriesMulti-usersyncServer-sidevalidation
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
FORMFunctionalitysupportedbydhtmlxConnector:
DynamicloadingFormatting/changingdatabeforeloadingServer-sidefiltrationServer-sideloggingServer-sidesortingStaticloadingfromdatabasetables,FileSystem,Excelfiles
FunctionalitysupportedbydhtmlConnector&dataProcessor:
Client-sideloggingClient-sidevalidationElementaryDBactionswithdhtmlxConnectorMakingcomplexqueriesMakingsimplequeriesMulti-usersyncServer-sidevalidation
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
GRIDFunctionalitysupportedbydhtmlxConnector:
Defininggridstructureonserver-sideDynamicloadingFormatting/changingdatabeforeloadingLoadingfromtablesthatdon'tcontainidentityfieldSelect/comboboxcolumnsinGridServer-sidedataexporttoPDF,ExcelServer-sidefiltrationServer-sideloggingServer-sidesortingStaticloadingfromdatabasetables,FileSystem,Excelfiles
FunctionalitysupportedbydhtmlConnector&dataProcessor:
Client-sideloggingClient-sidevalidationElementaryDBactionswithdhtmlxConnectorMakingcomplexqueriesMakingsimplequeriesMulti-usersyncServer-sidevalidationTransactions
DEFININGGRIDSTRUCTUREONSERVER-SIDEAPPLICABLETO:Grid
Startingfromversion1.0,connectorscanbeusedtodefineheaderofgrid.Itcanbedonein2ways:
automaticmanual
automaticdefining
Incaseautomaticdefining,gridwillusenamesoftable'sfieldsaslabelsforthecolumns.
require("../../codebase/grid_connector.php");
$grid=newGridConnector($res);
$grid->set_config(newGridConfiguration());
$grid->render_table("grid50000","item_id","item_nm,item_cd")
Ifyouwanttoapplyautomaticserver-sidesortingandfiltrationforspecifiedcolumns,youshouldspecifytrueinsideGridConfiguration:
$grid->set_config(newGridConfiguration(true));
$grid->render_table("grid50000","item_id","item_nm,item_cd")
manualdefining
Inmanualmode,headersandtheirparametersaredefinedbyphpcommand.Namesofcommandsmimicnamesofjscommandswithsimilarfunctionality.
$config=newGridConfiguration();
$config->setHeader(array("column1","column2"));
$config->setColTypes(array("ro","ed"));
$grid->set_config($config);
$grid->render_table("grid50000","item_id","item_nm,item_cd")
availablecommands
Allcommandsbelow,getasinputparameteranarrayofvaluesorcomma-separatedstring,delimitedby'headerdelimiter'(defaultvalue-',').
//columnlabels
$config->setHeader($names);
//columntypes
$config->setColTypes($typeStr);
//columnIDs
$config->setColIds($idsStr);
//columnwidth,intvalues,willbeprocessedassizeinpixels
$config->setInitWidths($widths);
//columnwidth,intvalue,willbethreatedassizeinpercents
$config->setInitWidthsP($widths);
//columnalign
$config->setColAlign($alStr);
//columnsortingtype
$config->setColSorting($sortStr);
//columncolor
$config->setColColor($colorStr);
//visibilityofcolumn
$config->setColHidden($hidStr);//'true'ifcolumnmustbehidden,'false'otherwise.
headerandfooter
ToattachheadertothegridyoushoulduseattachHeader()method:
$config->attachHeader($values,$styles=null);
Parameters:
arrayorstringofheadernames.Incaseofstring,namesaredelimitedby'headerdelimiter'(defaultvalue-',')arrayorstringofheaderstyles.Incaseofstring,stylesaredelimitedby'headerdelimiter'(defaultvalue-',')
ToattachfootertothegridyoushoulduseattachFooter()method:
$config->attachFooter($values,$styles=null);
Parameters:
arrayorstringoffooternames.Incaseofstring,namesaredelimitedby'headerdelimiter'(defaultvalue-',')arrayorstringoffooterstyles.Incaseofstring,stylesaredelimitedby'headerdelimiter'(defaultvalue-',')
headerdelimiter
Headerdelimetersetssymbolorseveralsymbolswhichwillbeusedasdelimiterinstringarguments.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
KeyGridConnectorNormalgridconnectorexpectsthattargettablehassomeautogeneratedIDfield,but,insomecases,dataneedstobeloadedandsavedfromdatabasetablewhichdoesn'thavesuchautofilledID.Normalgridconnectorcanbeusedfordataloadingfromsuchtables,butwon'tbeabletosavedataback.KeyGridConnectorcanresolvesuchproblem(useitinsteadofGridConnector):
$grid=newKeyGridConnector($res);
$grid->render_table("mytable","name","name,address,phone");
So,therearetwodifferencesfromthenormalGridConnector:
nameofconnectorclass(GridConnector→KeyGridConnector).oneofdatafieldsisusedasID
SELECT/COMBOBOXCOLUMNSINGRIDWhenonclient-sideyouspecifyco/coro/combocolumns(combo-box/select)ingrid,gridwillautomaticallyrequestdatafortheminthesamemannerasforfiltrationoptions.
Bydefault,gridwilluseDISTINCTselectagainstrelatedfield,andfetchallpossibleoptions.Ifyouneedtodefinecustomlistofoptionsyoucanuseoneof2ways:
hardcodedlist
$grid->set_options("item_nm",array("1"=>"one","2"=>"two",
$grid->render_table("grid50","item_id","item_nm,item_cd");
listcreatedonbaseofdifferenttable
$options=newOptionsConnector($res);
$options->render_table("countries","country_id","country_id(value),country_name(label)"
$grid->set_options("item_nm",$options);
$grid->render_table("grid50","item_id","item_nm,item_cd");
co/combotype
whenusingpredefinedlistofdata,bothvaluesandlabelsneedtobeprovidedwhenusingconnector,theremustbetwofieldsselected,oneas(value),secondas(label)
corotype:
onlylabelsneedtobeprovided
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
TREEFunctionalitysupportedbydhtmlxConnector:
DynamicloadingFormatting/changingdatabeforeloadingLoadingtreedatafrommultipletablesLoadingtreedatafromtablesthatdon'tcontainrelationfieldMarkinganitemasaleaforbranchServer-sidefiltrationServer-sideloggingServer-sidesortingStaticloadingfromdatabasetables,FileSystem,Excelfiles
FunctionalitysupportedbydhtmlConnector&dataProcessor:
Client-sideloggingClient-sidevalidationElementaryDBactionswithdhtmlxConnectorMakingcomplexqueriesMakingsimplequeriesMulti-usersyncServer-sidevalidation
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
TREEGRIDFunctionalitysupportedbydhtmlxConnector:
DynamicloadingFormatting/changingdatabeforeloadingLoadingtreedatafrommultipletablesLoadingtreedatafromtablesthatdon'tcontainrelationfieldMarkinganitemasaleaforbranchServer-sidefiltrationServer-sideloggingServer-sidesortingStaticloadingfromdatabasetables,FileSystem,Excelfiles
FunctionalitysupportedbydhtmlConnector&dataProcessor:
Client-sideloggingClient-sidevalidationElementaryDBactionswithdhtmlxConnectorMakingcomplexqueriesMakingsimplequeriesMulti-usersyncServer-sidevalidation
TreeMultitableConnector/TreeGridMultitableConnector
Connectorswillworkonlyifdynamicloadingmodeonclient-sideisenabled.
Inmanycases,treeortreegridneedtobebuiltfrommultipletables(eachtablerepresentseparateleveloftree/treegrid).ForthispurposeshouldbeusedTreeMultitableConnector/TreeGridMultitableConnector(insteadofTreeConnector/TreeGridConector).
tree
require("../../codebase/treemultitable_connector.php");
$tree=newTreeMultitableConnector($res);
$tree->setMaxLevel(3);
$level=$tree->get_level();
switch($level){
case0:
$tree->render_table("projects2","project_id"
break;
case1:
$tree->render_sql("SELECTteams2.team_id,teams2.team_name,project_team2.project_idFROMteams2INNERJOINproject_team2ONteams2.team_id=project_team2.team_id"
break;
case2:
$tree->render_table("developers2","developer_id"
break;
case3:
$tree->render_table("phones2","phone_id","phone"
break;
}
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
treeGrid
require("../../codebase/treegridmultitable_connector.php");
$treegrid=newTreeGridMultitableConnector($res);
$treegrid->setMaxLevel(3);
$level=$treegrid->get_level();
...
TreeGroupConnector/TreeGridGroupConnectorDefaultconnectorforTreeandTreeGridexpectsthatdatainDBisstoredwithchild-parentkeyrelation.But,insomecases,treeortreegridneedtobeshownfromplaindata(bygroupingit).SuchtaskcanberesolvedwithhelpoftheTreeGroupConnectororTreeGridGroupConnector.
Forexample,atable'products'groupingbycategory.Asresult,thetoplevelare'categories',thesecondlevel-'products',relatedtothecategory.
//tree
require("./codebase/connector/tree_group_connector.php");
$tree=newTreeGroupConnector($res);
$tree->render_table("products2","id","product_name","","category"
//treeGrid
<codephp>
require_once('../../codebase/treegridgroup_connector.php');
$treegrid=newTreeGridGroupConnector($res,"MySQL");
$treegrid->render_table("products2","id","product_name,scales,colour"
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
SCHEDULERFunctionalitysupportedbydhtmlxConnector:
SelectboxcolumnsDynamicloadingFormatting/changingdatabeforeloadingServer-sidefiltrationServer-sideloggingServer-sidesortingStaticloadingfromdatabasetables,FileSystem,Excelfiles
FunctionalitysupportedbydhtmlConnector&dataProcessor:
Client-sideloggingClient-sidevalidationElementaryDBactionswithdhtmlxConnectorMakingcomplexqueriesMakingsimplequeriesMulti-usersyncServer-sidevalidation
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Select-boxcolumnsinschedulerWhenschedulerhasaselect-likecollectionsorunit/timelineview-it'spossibletoloadalistofrelatedoptionsfromaserver.Insuchcasethedataloadingneedtobedefinedonclient-sideas:
some_collection=scheduler.serverList("type");
Onserver-side,listofoptionscanberetrievedin2ways:
hardcodedlist//bothvaluesandlabelsneedtobeprovided
$scheduler->set_options("type",array("1"=>"one","2"=>"two"
$scheduler->render_table("events","event_id","start_date,end_date,text,type_id"
listcreatedonbaseofdifferenttable
$options=newOptionsConnector($res);
//theremustbetwofieldsselected,oneas(value),secondas(label)
$options->render_table("types","type_id","type_id(value),type_name(label)"
$scheduler->set_options("type",$options);
$scheduler->render_table("events","event_id","start_date,end_date,text,type_id"
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
DHTMLXTouchComponentsFunctionalitysupportedbydhtmlxConnector:
DynamicloadingFormatting/changingdatabeforeloadingServer-sidefiltrationServer-sideloggingServer-sidesortingStaticloadingfromdatabasetables,FileSystem,Excelfiles
FunctionalitysupportedbydhtmlConnector&TouchdataProcessor(differsfromstandarddataProcessor)seeinthe relatedchapterofDHTMLXTouchdocumentation.
BasicloadingInthischapteryou'llfindbaseinformationconcerningstaticloadingdatafrom:
databasetableFileSystemPHParrayExcelfile
Inordertodataisloadedcorrectly,your'id'fieldinthedatabasemustbeautoincrement.
loadingfromdatabasetable
APPLICABLETO:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form,DataStore,DHTMLXTouchcomponents
Loadingcharacteristicsaredefinedatstageofcomponentconfiguration.Thereare3waystospecifythedesireddata:
byrender_table()methodwhenyouworkwithonetablebyrender_sql()methodwhenyouworkwithseveraltablesbyrender_complex_sql()methodwhenyouusetocallstoredproceduresinthedatabase+toimplementcomplexqueries
workwithonetable
Whenallnecessarydataisplacedinonedatabasetableyoushouldusetherender_table()method:
$grid->render_table("grid50","item_id","item_nm,item_cd","extra1,extra2"
Parameters:
databasetablenamenameofidentityfield(optional)listoffieldswhichshouldbeusedasvaluesofcomponentitem(cellsofgrid,itemlabelintree,textofoptionincombo)listofextrafields(knowmoreaboutextrafieldshere)
IfyouwanttorenderallfieldsfromDB(exceptforthekeyfield),youcanuseasimplifiedcommand:
$grid->render_table("grid50");
That'senoughtomakeconnectorimplementselect,insert,updateanddeleteoperations.
workwithseveraltables
IfyourSQLstatementcontainsmorethanonetable,connectorwon'tbeabletogenerateinsert/update/deleteoperationscorrectlyandyouwillneedtodoonefromthenext:
1. Definesqlforeachoperationmanually2. Useserver-sideeventstodefineyourownprocessinglogic3. Definedifferentconfigsforselectandupdateoperations
The3rdapproachisshowninthecodesnippetbelow:
if($grid->is_select_mode())//codeforloadingdata
$grid->render_sql("Select*fromtableA,tableBwheretableA.id=tableB.id"
else//codeforotheroperations-i.e.update/insert/delete
$grid->render_table("tableA","id","name,price");
Withsuchinitcodegridwillbeloadedwiththreecolumnsofdatafrom2tables,butduringsavingonlydatafromthefirsttablewillbesaved.
complexqueries
YouareallowedtouseanySQLstatementstopopulateadhtmlxcomponentthroughdhtmlxConnector.ForcomplexSQLquerieswestronglyencourageyoutousetherender_complex_sql()method:
$grid->render_complex_sql("SELECTnamefromtableAWHEREdept=(SELECTdeptFROMtableBwherename='John')"
Parameters:
sqlstatementnameofidentityfield(optional)listoffieldswhichshouldbeusedasvaluesofcomponentitem(cellsforgrid,itemlabelfortree,textofoptionforcombo)listofextrafields(knowmoreaboutextrafieldshere)parentIDfieldnameforhierarchicalstructures(requiredfortreeandtreegrid)
IncaseyourSQLquerywasagainstasingletable,itisquiteprobablethatinsert/update/deleteoperationsdonotrequireanyadditionalcode.dhtmlxConnectorwillparseyourSQLandgenerateinsert/update/deletestatementsbasedonusedtableandfieldsnames.
callingstoredprocedures
Startingfromversion1.5,youcanloaddatausinginSQLstatementsstoredprocedures.Thelibraryprovidesaspecialmethodforthisneed-render_complex_sql.
$grid->render_complex_sql("execusp_findusers'John'","id",
extradata
Thelastparameterofrender_array,render_sql,render_complex_sql,render_tablemethodsallowsyoutodefinealistoffieldswhichwillbeextractedfromdatabasetablebutwon'tbesenttoclient-side.Thesefieldscanbeusedasattributesorflags,mappedtodifferentpropertiesofrecords(userdata,rowstyles,images,etc.).
$grid->render_table("tableA","id","name,price","extra1,extra2"
//or
$grid->render_sql("Select*fromtableA,tableBwheretableA.id=tableB.id"
extra1andextra2fieldswillbeavailableinallserver-sideeventsbutwon'tbesenttoclient-side,andwon'tbeincludedinupdate|insertoperations.
treeandtreegridspecificity
IncaseofTreeandTreeGrid,render_array,render_sql,render_complex_sqlandrender_tableacceptonemoreparameter-therelationID.Fordefaulttreegridhierarchy-it'sthenameofafield,whichwillbeusedtolinkparentandchildrecords.
$treeGrid->render_table("tableA","id","name,price","","parent_id"
//or
$treeGrid->render_sql("Select*fromtableA,tableBwheretableA.id=tableB.id"
aliases
TomakeusageofextracteddatahandieryoucanusealiasesforDBfieldnames(makessenseonlyifyouuseserver-sideevents):
$grid->render_table("tableA","id","name,price(product_price)"
//or
$grid->render_sql("Select*,tableA.idasaidfromtableA,tableBwheretableA.id=tableB.id"
Backtotop
loadingfromPHParray
Startingfromversion1.5,insteadofdatabaseyoucanloaddatafromaPHParraywhichcanbefilledbyanykindofexternallogic.ToloaddatafromaPHParray,usemethodrender_array.Beware,themethodcan'tbeusedforstoringdatabutyoustillcanuseeventhandlers,orcustommodeltointerceptdatasavingcommandandprocesstheminsomecustomway.
Parameters:
nameofPHParrayoraPHParrayitselfnameofidentityfield(optional)listoffieldswhichshouldbeusedasvaluesofcomponentitem(cellsforgrid,itemlabelfortree,textofoptionforcombo)listofextrafields(knowmoreaboutextrafieldshere)parentIDfieldnameforhierarchicalstructures(requiredfortreeandtreegrid)
$data=array(
array("id"=>"1","product"=>"PhoneAB12",price
array("id"=>"2","product"=>"Tabletdevice",price
);
$conn->render_array($data,"id","product,price");
Backtotop
loadingfromFileSystem
APPLICABLETO:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form
Startingfromversion1.0,dhtmlxConnectorallowstouseFileSystemasdatasource(pleasenote,tostartusethisfunctionalityyoushouldincludedb_filesystem.phpfilelocatedinconnector'spackage).
require("./codebase/connector/db_filesystem.php");
require("./codebase/connector/grid_connector.php");
$grid=newGridConnector("","FileSystem");
$grid->render_table("../","safe_name","filename,full_filename,size,name,extention,date,is_folder"
Inthecodesnippetabove,gridisfilledwithinfoaboutfileslocatedin'd:/www'folder
Parametersof'render-table'method:
folder,forwhichdatalistingisrequiredfield'sid.Leaveitemptyorusesafe_nameasIDoffilelistoffields,possiblevaluesare:
filename-nameoffilefull_filename-fullpathtofilesize-sizeoffileinbytesname-namepartoffilenameextension-extensionpartoffilenamedate-timestampoffileis_folder-file|folderflag
limitingfilesinoutput
Thereare3waystolimitfilesinoutput:
1. byextensiontype2. byregexppattern3. bymeta-type
byextensiontype:
$fileTypes=FileSystemTypes::getInstance();
$fileTypes->addExtention('png');
byregexppattern:
$fileTypes=FileSystemTypes::getInstance();
$fileTypes->addPattern('/^.+\..*$/');
bymeta-type:
Thefollowingmeta-typescanbeused:
image-imagefilesdocument-doc,xls,txt,rtfweb-php,html,js,cssaudio-mp3,wav,oggvideo-avi,mpg,mpeg,mp4only_dir-folders
$fileTypes=FileSystemTypes::getInstance();
$fileTypes->setType('web');
Backtotop
loadingfromExcelfile
APPLICABLETO:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form
Startingfromversion1.0,dhtmlxConnectorallowstouseExcelfileasdatasource.
Tostartusethisfunctionlityyoushould:
1. DownloadphpExcel.Itisn'tincludedintheconnector'spackage.Youcangrabitfrom2sources:
http://support.dhtmlx.com/x-files/connector/phpExcel.ziphttp://www.codeplex.com/PHPExcel.
2. Unziplibrarytotheconnector'sfolder.3. Includerelatedfiles:
'lib/PHPExcel.php'(phpExcelpackage)'lib/PHPExcel/IOFactory.php'(phpExcelpackage)'db_excel.php'(standardconnector'spackage)
//filesfromlibExcelpackage
require_once('lib/PHPExcel.php');
require_once('lib/PHPExcel/IOFactory.php');
//connectors
require("../../codebase/db_excel.php");
require("../../codebase/grid_connector.php");
$grid=newGridConnector("../some.xls","ExcelDBDataWrapper"
$grid->render_table("A18:F83","id","A,B,C,D,E,F");
Parameters:
constructorGridConnector()nameofexcelfile,absolutepathorpathrelatedtothephpfiledatabasetype
render_table()methodfirstparametercanbe
rangeofcellsinthespreadsheet,forexampleA18:F83$grid->render_table("A18:F83","id","A,B,C,D,E,F"
numberofthetoprow,fromwhichoutputneedtobestarted,forexampleA4$grid->render_table("A1","id","A,B,C,D,E,F");
'*',whichmeansincludeallnotemptyrows$grid->render_table("*","id","A,B,C,D,E,F");
nameofidentityfield.Youcanuse'id'valueforautoidgenerationlistoffieldswhichwillbeusedascolumnsinthegrid
loadingbothdataandheader
Applicableto:Grid
Whenyouneedtoloadbothdataandheaderfromexcelfile,youcanmakeitthroughGridConfiguration:
$grid=newGridConnector($excel_file,"Excel");
$config=newGridConfiguration();
//arrayofcells,withlabelsforgrid'sheader
$config->setHeader($grid->sql->excel_data(array("A3","B3","F13"
$grid->set_config($config);
DynamicloadingDynamicalLoadingmodeallowstoloaddatanotallatonce,butpartially,byclient-siderequest.Itdecreasesinitialloadingtimeandloadingofserver.
Toworkcorrectly,onclient-sideshouldbeenabledrelatedmode:
grid-smartrenderingandpagingmodestreegrid-dynamicbranchloadingmodetree-dynamicbranchloadingmodecombo-partialautocomplete(youdon'tneeditfornormalautocomplete)dataview-dynamiсscrollingordynamicpaging
Toactivatethemodeyoushouldusethemethoddynamic_loading():
$grid->dynamic_loading([$rowsNum]);
In'dynamicloading'modeyoucan'tuseGROUPBYwithinSQLquery
Parameters:
noneforatree,treegrid.numberofrowswhichshouldbeinitiallyloaded(thevalueshouldbemorethananumberofrowsvisibleinthegrid,oratleastanypositivenumber)foragrid.maximumnumberofoptionswhichserverwillsendtoacombointhe'autocompletemode'forasingledatarequest.
tree/treegridspecific
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Normally,connectormakesalloperationsautomatically,anddoesn'tneedcustomization.But,incaseofdynamicloadingintree/treeGrid,databasecancontainfieldindicatedleaforbranchthecurrentitemis.InbeforeRendereventhandleryouareallowedtomarkanitemasaleaforbranch(itdecreasesanumberofSQLqueriesandincreasesperfomance).
functioncustom_define($item){
if($item->get_value("is_a_branch"))
$item->set_kids(true);
else
$item->set_kids(false);
}
$tree->event->attach("beforeRender","custom_define");
Thesameapproachcanbeusedfornon-dynamicalmodeoftree/treeGridaswell.It'snotobligatorybutletsyouincreasedatagenerationperformance.
FilteringThereare3waystoimplementserver-sidefiltration:
byspecifyingadditionalparametersinURLbyusingin-headerfiltertypeswhilecomponentconfigurationbymeansofbeforeRenderevent
Beware,server-sidefiltrationofdhtmlxTreeGriddoesn'tmaintainopenstates.
URLmanipulation
APPLICABLETO:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form,DataStore,DHTMLXTouchcomponents
YoucancontrolwhichdataisloadedintocomponentbyspecifyingadditionalparametersinURL.CheckarticleExtendingfunctionalityforfullurlparametersdescription.
filtrationbyonefield
grid.load("some.php?connector=true&dhx_filter[1]=mask");
Withsuchurl-datawillbetakenwithadditionalrule.
WHEREfield_for_column_1LIKE%mask%
filtrationbymultiplefields
grid.load("some.php?connector=true&dhx_filter[1]=mask&dhx_filter[3]=another"
ForcomponentsotherthandhtmlxGridyoushouldprovideexactfieldnameinsteadofcolumnindex.
Bewarethatsuchfilteringisnot-secureandifyouneedtohidesomedata-besuretodefinesuchlimitationonserverside,notaspartofURL.
in-headerfiltertypes
APPLICABLETO:Grid,TreeGrid,Combo
Toenableserver-sidefilteringyoucanuseoneofthefollowingin-headerfiltertypeswhileconfiguringdhtmlxGrid/dhtmlxTreeGridonclient-side:
#connector_text_filter-textfilter.Retrievesvalueswhichcontainmaskdefinedthroughtextfield#connector_select_filter-selectfilter.Retrievesvalueswhichcontainmaskdefinedthroughdropdownlistofpossiblevalues
mygrid.setHeader("ColumnA,ColumnB");
mygrid.attachHeader("#connector_text_filter,#connector_select_filter"
textfilter
Textfilterusagedoesn'trequireanyadditionalconfigurationcode.Grid/TreeGridwillautomaticallysenddataaboutnewenteredtextandfilterserver-sidedatausing%mask%pattern.Ifyouneedtochangefilteringpatternorimplementmoreadvancedlogic-beforeFiltereventshouldbeused.
defaultfiltrationlogic
functioncustom_filter($filter_by){
//WHEREsome_fieldLIKE'value'
if(!sizeof($filter_by->rules))
$filter_by->add("some_field","value","LIKE"
}
$conn->event->attach("beforeFilter","custom_filter");
redefinedfiltrationlogic
functioncustom_filter($filter_by){
if(!sizeof($filter_by->rules))
$filter_by->add("some_field","value","LIKE"
//changeWHEREsome_fieldLIKE'%value%'totheWHEREsome_field>'value'
$index=$filter_by->index("some_field");
if($index!==false)//thereisclientsideinputforthefilter
$filter_by->rules[$index]["operation"]=">"
}
$conn->event->attach("beforeFilter","custom_filter");
Throughrules[$index]youcanreferto:
thenameofafield(rules[$index][“name”]=“age”)thevalueofafield(rules[$index][“value”]=“30”)thetypeofanoperation(rules[$index][“operation”]=”>”)
selectfilter
Bydefault,grid/treegridwilluseDISTINCTselectagainstrelatedfield,andfetchallpossibleoptions.Ifyouneedtodefinecustomlistofoptionsyoucanuseoneof2ways:
hardcodedlist
$grid->set_options("item_nm",array("1"=>"1","2"=>"two"
$grid->render_table("grid50","item_id","item_nm,item_cd")
listcreatedonbaseofdifferenttable
$filter1=newOptionsConnector($res);
$filter1->render_table("countries","country_id","country_name(value)"
$grid->set_options("item_nm",$filter1);
$grid->render_table("grid50","item_id","item_nm,item_cd")
Youcanusebothrender_tableandrender_sqlmethodsforOptionsConnectorobject,thesameasforanynormalconnector.
Bewarethatnameoffield,usedinselectfilterneedtohavealias(value).
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
customfilters(usingbeforeRenderevent)
APPLICABLETO:Grid,Combo
ByusingbeforeRendereventit'spossibletodefinefiltrationrulesasPHPcode(doesn'tworkfordyn.modes).
functioncustom_filter($data){
if($data->get_value("some")<0)
$data->skip();//notincludeinoutput
}
$conn->event->attach("beforeRender","custom_filter");
baseformattingmethods
APPLICABLETO:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form,DataStore,DHTMLXTouchcomponents
Whenyouneedtoupdatevalueswhichwerereturnedfromdatabasetableorsetsomespecificformattingbeforesendingdatatoclient-side,youshouldusethebeforeRendereventhandler.
commonusage
$res=mysql_connect($mysql_server,$mysql_user,$mysql_pass);
mysql_select_db($mysql_db);
require("../../codebase/grid_connector.php");
functioncolor_rows($row){
if($row->get_index()%2)
$row->set_row_color("red");
}
$grid=newGridConnector($res);
$grid->event->attach("beforeRender","color_rows");
$grid->render_table("grid50000","item_id","item_nm,item_cd")
color_rowsfunctionsetscolorsforrowssubjecttotheirindicesduringdatageneration,foreachrecordoutputedforclient-sidebeforeRendereventwillbeexecuted,i.e.color_rowsfunctionwillbecalledforeachrecord$rowisaninstanceofGridDataItemobjectrelatedtothecurrentrecord
dateformatting
APPLICABLETO:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form,DateStore,DHTMLXTouchComponents
functionformatting($row){
//renderfieldasdetailslink
$data=$row->get_value("some_field");
$row->set_value("some_field","<ahref='details.php?id={$data}'>Details</a>"
//formattingdatefield
$data=$row->get_value("other_field");
$row->set_value("other_field",date("m-d-Y"
}
$grid=newGridConnector($res);
$grid->event->attach("beforeRender","formatting");
get_valueandset_valuemethodsallowyoutogetorsetvalueofanyfieldrelatedtotherecord(itdoesn'taffectactualvaluesinDB)Ifaliaswasusedduringdataconfiguration-youneedtouseitinsteadofrealdbfieldnameasthefirstparameterofget|setcommand.
usingextrafields
APPLICABLETO:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form,DataStore,DHTMLXTouchcomponents
Morecomplexformatingrulescanbedefinedbyusingextrafieldswhileconfiguration.
functionformatting($row){
//setrowcolor
$row->set_row_color($row->get_value("color"));
//saveinuserdata
$row->set_userdata("some_data",$row->get_value("count"
}
$grid=newGridConnector($res);
$grid->event->attach("beforeRender","formatting");
$grid->render_table("some_table","id","name,price","color,count"
fieldcolorisn'toutputedtoclient-sidebutusedtodefinepropertyofrow.duringupdate|insertoperationonly'name'and'price'columnsmaybechanged,'color'willstayuntouched.'count'fieldwillbesenttoclient-sideasuserdataoftherowanditwillbepossibletoaccessitonclient-sidethroughrelateddata.
tree/treegridspecificity
APPLICABLETO:Tree,TreeGrid
treeGridprovidesTreeGridDataItemandtreeprovidesTreeDataItemasinputparameterofbeforeRendereventhandler.Bothofthemsupportbaseoperationsandfewspecificones.
functioncustom_format($item){
if($item->get_value("complete")>75)
$item->set_check_state(1);
if($item->get_value("duration")>10)
$item->set_image("true.gif");
else
$item->set_image("false.gif");
}
$tree->event->attach("beforeRender","custom_format");
set_imagemethodallowstosetimageoftreeelement(fortreegriditacceptstheonlyparameter,whilefortreeitcanbe3differentimagesfor3statesoftree'sitem)set_checkmethodexistsonlyinTreeDataItemobjectandallowstosetthestateofrelatedcheckbox(treeneedtohavecheckboxesenabledinjs.configurationcodeaswell)beforeRendereventcanbeusedindynamicTreeandTreeGridtodefinewhichelementsofhierarchyarebranchesandwhichareleafs(seedetailshere).
Whiledeletingitemsthathavechildrenyoucanfacetheproblemthattheparentitemisdeletedbutchildrenarenot.InthiscaseyoushouldusethebeforeDeleteevent:
functionbeforeDeleteFunc($data){
//customlogic
};
$conn->event->attach("beforeDelete","beforeDeleteFunc");
SortingThereare2waystoimplementserver-sidesorting:
byspecifyingadditionalparametersinURLbyusingsortingtype'connector'whilecomponentconfiguration
URLmanipulation
APPLICABLETO:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form,DataStore,DHTMXLTouchcomponents
YoucancontrolhowdatawillbesortedinsidecolumnbyspecifyingadditionalparametersinURL.CheckarticleExtendingfunctionalityforfullurlparametersdescription.
//ORDERbyfield_2ASC
grid.load("some.php?connector=true&dhx_sort[2]=asc");
//ORDERbyfield_2ASC,field_3DESC
grid.load("some.php?connector=true&dhx_sort[2]=asc&dhx_sort[3]=desc"
sortingtype'connector'
APPLICABLETO:Grid,TreeGrid
Tosortgrid/treegridcontentwithconnectorsyouneedtouse'connector'assortingtypewhilegridinitialization.
grid.setColSorting("connector,str,na");
Inthecodesnippetabove,thefirstcolumnwillbesortedonserver-sidewithconnectors,thesecondasstringonclient-side,thethirdcolumnwon'tbesortable.
Byassigningtosortingtype'connector'youjust'say'thatsortingwillbeimplementedonserver-side.Todefinetheway,'behaviour'ofsortingyoushouldusebeforeSortevent.Eventdoesn'tallowtowritecustomsortinglogic,butyoucanaffectSORTBYclauseofgeneratedSQLrequest.
defaultsortingbyonefield
functioncustom_sort($sorted_by){
//SORTBYsome_fieldASC
if(!sizeof($sorted_by->rules))
$sorted_by->add("some_field","ASC");
}
$conn->event->attach("beforeSort","custom_sort");
defaultsortingbymultiplefields
functioncustom_sort($sorted_by){
//SORTBYsome_fieldASC,some_otherASC
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
if(!sizeof($sorted_by->rules)){
$sorted_by->add("some_field","ASC");
$sorted_by->add("some_other","ASC");
}
}
$conn->event->attach("beforeSort","custom_sort");
customsortingrule
functioncustom_sort($sorted_by){
//SORTBYLENGTH(some_field)
$sorted_by->rules[0]["name"]="LENGTH(some_field)";
}
$conn->event->attach("beforeSort","custom_sort");
Client-siderequirement-dataProcessorConnectoritselfletsjustpassdatafromserver-toclient-side.Whenyouneedtopassdataback(e.g.you'veupdatedrecordandwanttosaveupdatesindatabase)youshouldusedataProcessoradditionally.
Shortly,dataexchangewithdataProcessorcanbecharacterizedasfollows:
1. Afteryoumakesomechangesclientsendsquerywithseveralparameterstoserver.Theparameterwearemostinterestedinis!nativeeditor_status(theparameternamecanbechanged.Goherefordetails).Itdefinesthestatusofoperationandcanhaveoneofthefollowingvalues:
updatedinserteddeleted
2. Servertriestoimplementtherequiredquery.Iftheoperationwasperformedsuccessfully,serverreturnsthesamestatusitgot.Otherwise-status“error”.
3. Whileexchanging,dataisundergonedefaultprocessingbothonserver-andclient-side,i.e.datawillbeupdated/inserted/deletedautomatically(justinitializedataProcessoranddhtmlxConnector),noadditionalcodeneedstobeadded.Youcanaffectonthisdefaultprocessingbymeansofevents(seedetailsbelow).
Filestoincludeonclient-side
Ifyouusethe'dhtmlxSuite'package(dhtmlx.js,dhtmlx.csscodefiles)-youneedn'ttoaddanyadditionalfiles.Butifyouusethecomponentsstandaloneyoushouldaddoneadditionalfile-dataprocessor.js.
Beware,dataprocessor.jsshouldbeincludedBEFOREconnector.js.
Initializationandlinkingtoconnector
ToinitializedataProcessoryoushouldwrite2commands:
vardp=newdataProcessor(url)
dp.init(mygrid)
TolinkdataProcessorwithconnectoryoushouldspecifyconnectorfileasaparameteroftheconstructor:
dp=newdataProcessor("myconnector.php");
dp.init(mygrid);
Client-sidelogging
Dataprocessorhasitsownclient-sidelogger,whichcanbeenabledbyincludingoneadditionaljsfile-dhtmlxdataprocessor_debug.js
Validation
client-sidevalidation
Dataprocessorallowstovalidatedatabeforesendingtoserver-side(seedetailshere).
server-sidevalidation
Detailsofserver-sidevalidationalsoseeintherelatedchapterofthisdocumentation.
Changingdefaultprocessing
Asitwasmentionedbefore,toaffectondefaultdataprocessingeitheronserver-orclient-sideyoushoulduseevents(theycanbeeitherdataProcessorordhtmlxConnectorevents).
changingdefaultdataprocessingonserver-side
Therearethefollowingwaystoaffectonserver-sideprocessing:
1. TousehandlerfunctionsofdhtmlxConnectorevents:beforeUpdateEventbeforeInsertEventbeforeDeleteEventbeforeProcessingEvent
2. Tocreatedatamodel(OOPstyle;availablefromversion1.5)
classEventModel{
functionget($request){
returnarray_of_data();
}
functionupdate($action){
//call$action->success();or$action->invalid();tomarkoperationascompletedorinvalid
}
functioninsert($action){
//call$action->success();or$action->invalid();tomarkoperationascompletedorinvalid
}
functiondelete($action){
//call$action->success();or$action->invalid();tomarkoperationascompletedorinvalid
}
}
$connector=newGridConnector($this->db);
$connector->configure("events","event_id","start_date,end_date,event_name"
$connector->useModel(newEventModel());
$connector->render();
Anyofmethodsinthemodelcanbeskipped,insuchcasetheconnectorwilltrytogenerateitsownversionoflogic.
Methodsupdate(),insert(),delete()taketheDataActionobjectasaparameter(thesameasthebeforeProcessingeventdo).Methodget()takestherequestobjectandmustreturnarrayofhash(thesameastherender_arraymethoddo).
Youcanalsocombine2variantsandusedatamodelandeventsatthesametime.Thehandlerswillbeinvokedinthefollowingorder:
'before'events(beforeProcessing,…);datamodel;'after'events(afterUpdate,…).
changingdefaultdataprocessingonclient-side
Changingdefaultdataprocessingonclient-sidecanbedoneinoneofthefollowingways:
1. Onserver-sidethroughhandlerfunctionsofdhtmlxConnectorevents:
afterUpdateEventafterInsertEventafterDeleteEventafterProcessingEvent
2. Onclient-sidethroughhandlerfunctionsofdataProcessorevents:
onBeforeUpdateonAfterUpdate
3. Onclient-sidethroughdataProcessor'smethoddefineAction().Themethodallowstodefinehandlerfunctionofthespecifiedstatus.
dp.defineAction("update",function(sid,response){
...
returntrue;//returnfalsetocanceldefaultdataprocessingatall
})
meanwhile,youcanchangestatusofserver-sideresponsethroughdhtmlxConnector'smethodset_status()andassigntheappropriateprocessingthroughdefineAction().Statuscanbechangedin2ways:
I. bysettingotherpredefinedstatus('updated','inserted','deleted').Inthiscaseyoujustchangedefaultprocessing,writesomeadditionstoit.
II. bysettingcustomstatusonserver-side.Inthiscaseyoucanceldefaultprocessingatallandshoulddefineallactionsonclient-sidebyyourself.
$data->set_status("my_status");
Formoredetailsseechapter'Customstatus'
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Renamingthequerystatusparameter
Startingfromversion1.5yougetthepossibilitytorenamethequerystatusparameternamedbydefaultas!nativeeditor_status.
Whencanyouuseit?Themostobviousexample-thecasewhenyouwanttousedhtmlxConnector+dataProcessorwiththeCodeIgniterframework.Hereyoufacethefollowingproblem-dataProcessorprotocolisincompatiblewiththeframeworkcausetheframeworkblocksthedefaultnameoftheparameter.Theproblemcanbefixedbyrenamingtheparameteronbothserverandclientsides:
Clientside:
vardp=newdataProcessor(./data);
dp.action_param="dhx_editor_status";
Serverside:
DataProcessor::$action_param="dhx_editor_status";
simplequeries
Applicable:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form,DataStore,DHTMLXTouchComponents
Bydefault,connectorgeneratesallINSERT/UPDATE/DELETEqueriesautomatically,basedonconfiguration.Formoredetailsofthistopic,seethe'BaseConcepts'chapter.
Incaseofdnd,connectorwillprocessanactionasasequenceof'insert'and'delete'operations.
complexqueries
Whenyouneedtodefineyourownlogicyoushoulduseoneoftwoways:
definingcustomSQLcodeforoperationusingserver-sideeventstocustomizeoperations
customqueriesforanaction
Applicableto:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form,DataStore,DHTXMLTouchComponents
YoucandefineyourownSQLcodeforspecificaction(INSERT,UPDATEorDELETE)asfollows:
$grid->sql->attach("Update","UpdatetableAsetname='{name}',price={price}whereid={id}"
//...
$grid->render_complex_sql("..","id","price,name");
Parameters:
actionname.Possiblevaluesare:'Update','Insert','Delete'SQLstatement.Itcanusefields(ortheiraliases)whichwerementionedinrender_sqlorrender_tablemethodwhileloadingdata.
usingserver-sideevents
Applicableto:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form,DataStore,DHTMLXTouchComponents
Tocustomizeoperationsyoucanusethefollowingserver-sideevents:
beforeUpdatebeforeInsertbeforeDeletebeforeProcessing
//datapreprocessingbeforeupdate
functionmy_update($data){
$price=$data->get_value("price");
$price=intval($price);
$data->set_value("price","10");
}
$conn->event->attach("beforeUpdate","my_update")
//includingadditionalfieldtorequest
functionmy_update($data){
$data->add_field("userId",1);//willbeincludedinupdateprocessing
}
$conn->event->attach("beforeUpdate","my_update")
//fullycustomcode
functionmy_update($data){
global$conn;
$price=$data->get_value("price");
$id=$data->get_value("id");
$conn->sql->query("UPDATEsome_tableSETprice='{$price}'whereid={$id}"
$data->success();//success()marksoperationasfinishedandstopsanyfurtheractionprocessing
}
$conn->event->attach("beforeUpdate","my_update")
transactions
APPLICABLETO:Grid
Gridallowstousetransactions,fordataINSERT/UPDATE/DELETE
operations(besurethatusedDBenginehassupportfortransactions).Theycanbeenabledin2modes:
1. global
$conn->sql->set_transaction_mode("global");
Componentusessingletransactionforallrecordsinsidesinglerequest.Ifanyoperationfails-allrecordoperationswillberolledback,allupdatedrowswillbereturnedwitherrorstatusIfcustomvalidationwasassignedandblockanyrecord-allrecordsinsiderequestwillbeblocked
2. record
$conn->sql->set_transaction_mode("record");
ComponentusesseparatetransactionsforeachrecordinrequestIfanyoperationfails,itwillnotaffectotheroperations
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
INSERToperationinOracleDB
Applicableto:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form,DataStore,DHTMLXTouchComponents
Oracledoesn'thaveautoIDgenerationfunctionality,soyouneedtoprovidesomecustomIDforeachinsertoperations.
Thereare2waystoachivethis:
1. customIDgeneration-idgeneratedbyPHPcode
functionpre_insert($data){
$new_id=time()%10000;//anyotherIDgenerationlogiccanbeusedhere
$data->add_field("EMPLOYEE_ID",$new_id);
}
$grid->event->attach("beforeInsert","pre_insert");
$grid->render_table("EMPLOYEES","EMPLOYEE_ID","FIRST_NAME,LAST_NAME"
2. usingsequenceforIDgeneration
$grid->sql->sequence("EMPLOYEES_INC.nextVal");//sequencename
$grid->render_table("EMPLOYEES","EMPLOYEE_ID","FIRST_NAME,LAST_NAME"
Multi-usersyncAPPLICABLETO:Grid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form
Startingfromversion1.0,dhtmlxConnectorcanworkinmulti-usermodethatallowsuserstoseechangesofeachotherinrealtime.
Toenablemodeyouneedtowriteadditionsbothtoclient-andserver-sides:
client-side
1. initcomponentwithdataprocessor(ifithasn'tinitializedyet)
dp=newdataProcessor("myconnector.php");
dp.init(mygrid);
2. callsetAutoUpdate()methodwhereinputparameterisdelaybetweenupdatecalls
dp.setAutoUpdate(2000);
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
server-side
1. callenable_live_update()method
require("../../codebase/grid_connector.php");
$grid=newGridConnector($res);
$grid->enable_live_update('actions_table');
actions_table-tableindatabase,whichwillbeusedforsync.datastorage.Itneedstohavethenextstructure:
CREATETABLE`actions_table`(
`id`int(11)NOTNULLAUTO_INCREMENT,
`dataId`int(11)NOTNULL,
`type`varchar(255)NOTNULL,
`user`varchar(255)NOTNULL,
PRIMARYKEY(`id`)
)ENGINE=MyISAM;
SecuritydhtmlxConnectorisopentoexternalaccessofanotherprogramsandanyexternaluserisallowedtochangedataindatabase.Thus,addingsomekindofsession-basedauthenticationisstronglyrecommended.
Basicsecurity
Built-insecuritymanagerallowsyoutolimitconnectorforcertainoperations.
$gridConn->access->deny("read");//blocksSelectaction
$gridConn->access->deny("insert");//blocksInsertaction
$gridConn->access->deny("update");//blocksUpdateaction
$gridConn->access->deny("delete");//blocksDeleteaction
Bydefault,connectorallowsalloperations.
Protectionfromcross-sitescripting(XSS)
Startingfromversion1.5,dhtmlxConnectorallowsyoutoprotectanappfromXSSattacks.
ToavoidXSSattacks,thelibrarychecksalldatainputtedbyusersandaccordingtothesetsecurityleveldoesn'tallowhtmlorjavascriptcodetobeinserted.
3securitylevelsareavailable:
DHX_SECURITY_SAFETEXT(default)-allhtmldataisremovedfromtheinputfield;DHX_SECURITY_SAFEHTML-allowshtmldata,butremovespossiblescripttagsandhandlers;DHX_SECURITY_TRUSTED-inputfieldsarenotfilteredatall(similartopreviousversionofconnectors).
Tosetthenecessarysecuritylevel,usethenextcode:
ConnectorSecurity::$xss=DHX_SECURITY_SAFETEXT;
//ConnectorSecurity::$xss=DHX_SECURITY_SAFEHTML;
//ConnectorSecurity::$xss=DHX_SECURITY_TRUSTED;
Ifyouwanttoenablethesamebehaviorasthepreviousversionsofconnectorshave,settheDHX_SECURITY_TRUSTEDmode.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
PreventingCSRFandXSRFattacks
Thefunctionalityrequires3.5orlaterversionoftheDHTMLXSuitepackage
Theprotectionisavailablestartingfromversion1.5andcanbeactivatedbythefollowingcodeline:
ConnectorSecurity::$security_key=true;
Aftercallingsuchacommand,connectorsstarttoincludeadditionalsecuritykeystoalldataloadingoperationsandprocessdataupdatingcallsonlyiftheycontainthesamekeys.Asaresultofthisprocessing,it'simpossibletotriggeradataupdatingoperationfromsomethird-partysite,evenifanattackerhasaccesstoavalidusersession.
Thetechniqueisbasedonphpsessionsandassumesthatanyphpsessionwillbepreservedbetweenseparatescriptcalls(defaultphpbehavior).
PleasebesurethatyouunderstandwhatCSRFattackis,causethestatedtechniquewon'tpreventaccesstotheconnectorfromexternalurls,itwillonlypreventexecutionactionsthroughsomeoneelsessession.
ValidationBeforesavingonserveryoucanvalidatedataandassignhandlerfunctionforanygottenresponse.
Shortly,validationcontains2keypoints:
1. valuechecking2. processingincaseofvalidationerror
common
Toimplementserver-sidevalidationofincomingdatayoucanusethefollowingevents:
beforeUpdatebeforeInsertbeforeDeletebeforeProcessing
beforeProcessingeventoccursforalltypesofoperationswhileothereventsoccursonlyforrelatedoperations,i.e.youcansetdifferentvalidationrulesfordifferentoperationsorforallofthematonce.
EventwillreceiveDataActionobjectastheparameter.Thisobjectcanbeusedtoretrieverelateddataandallow|denyoperation(pleasenote,itcontainsonlydatawhichwasreceivedfromclient-side,notthealldatarelatedtotherecord).
valuechecking
Tocheckvalueofafieldyoushouldusethemethodget_value()
functionvalidate($data){
if($data->get_value("some_field")=="")
...
}
$conn->event->attach("beforeProcessing","validate");
processingincaseofvalidationerror
Incaseoferroryoucangooneoftwoways:
1. Usepredefinedmethodsforerrorprocessingonclient-side,i.e.set:
$data→invalid()(invalidrecordwillbehighlightedinboldfont)$data→error()(invalidrecordwillbehighlightedinredboldfont)Thedifferencebetweenmethodsinquestionconsistsjustinwayofhighlighting.
functionvalidate($data){
if($data->get_value("some")=="")
$data->invalid();
}
$conn->event->attach("beforeProcessing","validate"
2. Assignyourownprocessingonclient-sidethroughdataProcessor'smethoddefineAction()(seedetailshere)
dp.defineAction("invalid",function(sid,response){
varmessage=response.getAttribute("message");
alert(message);
returntrue;//returnfalsetocanceldefaultdataprocessingatall
})
customstatus
Youcanchangereturnedstatusandsetyouownbymeansofthe
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
methodset_status().Inthiscaseanydefaultprocessing(doesn'tmatterdefineAction()willreturntrueorfalse)willbecancelledandyouwillspecifydataprocessingonclient-sidewholly.
server-side:
functionvalidate($data){
if($data->get_value("some")=="")
$data->set_status("my_status")
}
$conn->event->attach("beforeProcessing","validate");
client-side:
dp.defineAction("my_status",function(sid,response){
...
})
addingcustominformationtoresponse
Youcansendsomecustominformationtoclient-sidethroughthefollowingmethods:
set_response_textset_response_xmlset_response_attribute
SavingdatachangesmadeinformYoucanusetheconnectorsforsimpleformsaving.TheconnectorswillrecognizeandautomaticallyexecuteCRUDoperationsforthefollowingpatterns:
GetdataforsomerecordinDB,byid
GET:connector.php?action=get&id={some}
Returns:datain'json'(ifyouuseJSONDataConnector)or'xml'(ifyouuseDataConnector)format.
DeletedataforsomerecordinDB,byid
GET:connector.php?action=delete
POST:id={some}
Returns:“true”asstring,whenoperationisexecutedcorrectly.
UpdatedataforsomerecordinDB,byid
GET:connector.php?action=delete
POST:id={some}&property_name={value}
Returns:“true”asstring,whenoperationisexecutedcorrectly.
InsertdatainDB
GET:connector.php?action=insert
POST:property_name={value}
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Returns:“true\n{newid}”asstring,whenoperationisexecutedcorrectly.
Basically,forDHTMLXTouchcomponentstosavedatayoucanusethefollowingcode:
dhx.ajax().post("connector.php?action=insert",$$('form').getValues
DataexportAPPLICABLETO:grid
Externalgrid-to-pdfandgrid-to-excelservicesallowtoconvertgrid'sdatatoPDForExcelformatdirectlyonserver-side:fromanytablewithoutactuallyrenderingdatainthegrid.Shortly,youshouldperformthefollowingsteps:
preparedata.activateconversionservice.startexporting.
datapreparation
datatoexportisdefinedbyrender_table()orrender_sql()method.todefinegridstructure(header,footeretc.)onserver-side,seechapter''.
activationconversionservice
pdf$convert=newConvertService("http://dhtmlx.com/docs/products/devExchange/samples/grid2pdf_02/server/generate.php"
excel$convert=newConvertService("http://dhtmlx.com/docs/products/devExchange/samples/grid2excel_02/server/generate.php"
startexporting
pdf$convert->pdf("some.pdf",false);
excel$convert->excel("some.xls",false);
Parameters:
(optional)nameofresultfile.Thedefaultvalue-data.pdf(data.xls)(optional)thesecondparameterspecifieshowfilewillbeexported:
true-asinlinecontent(ifbrowserhasrelatedplugin-documentwillbeopenedautomatically)false-asindividualfile.Thedefaultvalue-false.
ServiceautomaticallystarttoexportdatadefinedthroughGridConnector.
samples
require("../../../codebase/grid_connector.php");
require("../../../codebase/convert.php");
//urltodataconversionservice
$convert=newConvertService("http://dhtmlx.com/docs/products/devExchange/samples/grid2pdf_02/server/generate.php"
$convert->pdf();//equaltocallingpdf("data.pdf",false)
$grid=newGridConnector($res);
$grid->set_config(newGridConfiguration()); //mandatory
$grid->render_table("grid50"); //tablenameandoptionallistoffields
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Excel
require_once("../../config.php");
$res=mysql_connect($mysql_server,$mysql_user,$mysql_pass)
mysql_select_db($mysql_db);
require("../../../codebase/grid_connector.php");
require("../../../codebase/convert.php");
//urltodataconversionservice
$convert=newConvertService("http://dhtmlx.com/docs/products/devExchange/samples/grid2excel_02/server/generate.php"
$convert->excel();//equaltocallingexcel("data.xls",false)
$grid=newGridConnector($res);
$grid->set_config(newGridConfiguration());//mandatory
$grid->render_table("grid50");//tablenameandoptionallistoffields
usefultips
IncaseofdynamicSmartRenderingyoucan'tuseexportfromclient-sideandneedtodefineheader'sdataonserver-side.Seedetailshere.
inordertotherender_sqlmethodworkscorrectly,youshouldusefullheaderinitialization(notemptyGridConfiguration()call).Otherwise,thecomponentwilltrytofetchgrid'sstructuredirectlyfromDBthatisunallowablefortherender_sqlmethod.
SQLqueries
DBWrapperobjectcanbeaccessedas:
$connector->sql
Then,itcanbeusedinqueriesinthefollowingway:
$connector->sql->query("DELETEFROMsome_tableWHEREID=1");
//or
$res=$connector->sql->query("SELECT*FROMsome_tableWHEREID=1"
$data=$connector->sql->get_next($res);
//or
$connector->sql->query("INSERTINTOsome_table(type)VALUES('simple')"
$id=$connector->sql->get_new_id();
INSERTquery
$id=$connector->insert(array(
"type"=>"simple",
...
));
Parameters:
hashofvalues
UPDATEquery
$connector->update(array(
"type_id"=>'1'
"type"=>'simple'
));
Parameters:
hashofvalues.Forsuccessfulresultitmustcontainidentityfield.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Creatinganewconnector
YoucancreateanextraconnectorobjectontheflyanduseitforDBoperations.
$temp=newConnector($db_connection);
$temp->configure("some_table");
$temp->insert(array(
"some1"=>"value1",
"some2"=>"value2"
));
$temp->delete("2");
server-sidelogging
DHTMLXpermitsloggingtobecontrolledintwoways:
BasicDetailed
basic
Ifanyerroroccursduringdataprocessing,client-sidedataprocessorobjectwillreceive“error”actioncontainingshortinfoabouttheproblem(fullinfowillbewrittentothelog).
$conn->enable_log("path");
path-absoluteorrelativepathtotextfilewherelogwillbewritten.
detailed
Whencriticalerroroccursalllogrecordsforcurrentsession(fullerrorinfo)willbesenttoclientandshowninbrowser(usefulfordebugging,notrecommendedforproduction):
$conn->enable_log("path",true);
path-absoluteorrelativepathtotextfilewherelogwillbewritten.Thesecondparameterenablesdetailedmode.
addingcustomrecordstothelog
Duringdevelopmentyoumayneedtowritesomecustomdatatothelog
(canbeusefulforcustomserver-sideevents).Toaddcustomtextordatatologfile:
Activatelogging(basicordetailed).Calllog()functionwithyourdatainside.
$conn->enable_log("temp.log");
LogMaster::log("anytexthere");
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
client-sidelogging
Dataprocessorhasitsownclient-sidelogger,whichcanbeenabledbyincludingoneadditionaljsfile-dhtmlxdataprocessor_debug.js
Eventhandling
commonuse
DHTMLXConnectoruseseventstomanageInsert/Update/Deleteoperations.
Thecodebelowshowshowtoattachevent:
$conn->event->attach(event_name,handlerFunc);
Parameters:
event_name-nameoftheevent.handlerFunc-handlerfunction.
Handlerfunctionsgetoneinputparameterandthisparameterdependsonattachingevent.Inthefollowingtableyou'llseeafulllistofeventsandtheappropriateinputparametersofhandlerfunctions.
Event InputparameterofhandlerfunctionbeforeSort SortInterfaceObjectbeforeFilter FilterInterfaceObjectbeforeRender DataItemObject
beforeProcessingafterProcessingbeforeInsertbeforeUpdatebeforeDeleteafterInsertafterUpdate
DataActionObject
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
afterDeletebeforeOutput none
databehaviormodels
Startingfromversion1.5,thelibrary'extends'OOPsupportandallowscreatingaseparateclassforeventsprocessing.Yougetthepossibilitytoworkwithoneclassthatwillcontrolallprocessinginsteadofworkingwithseparatehandlerfunctions.
classSomeBehavior{
publicfunctionbeforeRender($data){
//somelogic
}
...anyotherhandlers...
}
$conn->event->attach(newSomeBehavior());
Thehandlersofthemodelclasstakethesameparametersastheordinaryeventsdo.
protocoldetails
datafetching
POST
Commandparameters:
none
GET
Commandparameters:
connector=true-flagofconnectorbasedrequest.Theflagissetautomatically,onceyouincludetheconnector.jsfileonthepage.
dhx_colls=field1,field2…fieldN-optional,cancontainalistoffieldsforwhichcollectionswillberequested.dhtmlxGridusesuchparameterstorequestdataforcombocolumnsandselectfilters(suchrequestsareexecutedjustonce,forinitialdataloading)
some.php?connector=true&dhx_colls=2,3
dhx_sort[field]=directon-instructserver-sideconnectortosortdatasetbydefinedfield
some.php?connector=true&dhx_sort[2]=asc
dhx_filter[field]=mask-instructserver-sideconnectortofilterdatasetbydefinedfield
//filterby%test%
some.php?connector=true&dhx_filter[2]=test
gridspecific
Requstingpartofdata(DynamicSmartRenderingorDynamicPaging)
GET
posStart-positionfromwhichdataisrequestedcount-countofrequestedrows
combospecific
Requstingpartofdata
GET
pos-positionfromwhichdataisrequested
Filterbylabelfield
GET
mask-filteringmaskforlabelfield
tree/treeGridspecific
Requestingbranchoftree
GET
id-parentidforrequestedbranch
dataupdating(usingdataProcessor)
GET
editing=true-markofdataprocessor-basedcall
POST
ids-listofupdatedrecords[id]_[property]-foreachfieldinsideupdatedrecordrelatedfieldinPOSTisgenerated[id]_!nativeeditor_status-actiontype
Backtotop
portingconnectorstoanotherplatforms
whenshouldyouuseit?
Theexistingversionofconnectorssupportsalimitedsetofserverplatforms.Incasedatabase/framework/scriptinglanguageyou'dliketouseisnotsupported,youcanportexistingsolutiononyourplatform.
whenshouldn'tyouuseit?
Connectorsarejustwrappersaroundexistinggridfunctionality,that'swhyifyouneedtousethissolutiononce,youwouldbetterusegridAPIdirectly,insteadofcreatingyourownserverconnector.
implementationlevels
Connectorsupportsmanyoperationsimplementingdataprocessing.Thereisanopportunitytoprovidesupportingbasicoperationsandignorehigher-levelones,incasetheyarenotusedinyourproject.
basicsupport
Dataassignmentisbasicconnectoroperationwhichproceedsinthefollowingway:connectorconnectstodatabase,selectsdataandoutputsthisinstdoutusingXMLformatofthecurrentcomponent.
Keypoints:
1. XML-datainputmustoccuronlyaftersendingtheappropriatehttp-header
2. XMLmuststartwithXMLdeclarationcontainingtheappropriatedatacoding
3. Noneothercontentmustbesenttostdout(neitherbeforenoraftersendingdatabyconnector)
header("Content-type:text/xml");
print("<?xmlversion='1.0'encoding='utf-8'?>");
print(xml_formatted_data);
incomingparameters-therearenoany;restrictionforoutputdata-thereisnorestriction.
XMLFormatusedbyconnector
Basicimplementationallowstouseresultingscriptasinputparameterforload()/loadXML()methods.
Technically,thereisanopportunitytouseJSONoranyothersupportedbycomponentformat,butyoushouldbearinmindthat
complexscenariosareXML-orientedandyouwouldbetteruseXML
filtrationandsorting
Atthisstage,thenumberofsupportedoperationsisconsiderablyextended:youareallowedtouse#connector_text_filter,sortingtype'connector'andfilter/sortdatathroughURLmanipulations.
Keypoints:
Anobviousadvantageofthisfunctionalitycanbeestimatedonlyforoperatingwithgrid,forothercomponentssuchfunctionalitydoesn'tseemtobenecessary(itcanbeusedonlytofilter/sortdatathroughURLmanipulations).Thelevel'uses'codefromthepreviousone.Beware,thatnow,beforeusingXML,dataissorted/filteredaccordingtoincomingdata.
GET
Commandparameters:
dhx_filter-hashoffilteringrulesfiltrationpattern-anyentry(like%x%)incaseyouhaveafewparameters,youshouldlinkthembyANDlogicparameterisavailableonlyforfieldswithactivefilteremptyfiltervaluemeansthatfilterwasn'tsetanditmustbeignored
//wherefield1like%some%ANDfield2like%other%
dhx_filter[1]=some&dhx_filter[2]=other
dhx_sort-hashofsortingrulespossiblevaluesforascanddscparametersincaseyouhaveafewparameters,youshouldlinkthembyANDlogicorderoffilteringimplementation-notdefined,atthemomentnoonecomponentisabletocreatemulti-fieldsorting
//orderbyfield1ASC,field2DESC
dhx_sort[1]=asc&dhx_filter[2]=dsc
Hashesofrulesinquestionusenameoffields(wherefiltrationisenabled)orcolumns'indices(incaseofgrid).
Restrictionforoutputdata:orderandstructurearedefinedthroughfiltering/sortingparameters.
combospecific:dhtmlxCombohasanadditionalfilteringGETparameter:
mask-setsfiltrationintextlabelcolumnsusing“likex%”rule.
some.php?mask=abc
dynamicloading
Afterdataoutputimplementationgoesdynamicalloading.Dynamicalloadinghassomeparticularfeatureswhileworkingwithhierarchical(tree/treegrid)andsimple(grid/combo)components.
Forhierarchicalcomponents,loadingofdatabranchoccursatonce.
some.php?id=123
Commandparameters:
id-'parentid'whichdefinestheappropriatebranch(beware,allfiltration/sortingrulessetwhilethepreviousstageareappliedtocomponent).
Forothercomponents,datawillbeoutputtedaccordingtoincomingparameters.
//grid
some.php?posStart=20&count=50
//combo
some.php?pos=50
Commandparameters:
grid:
posStart-indexofinitialstringcount-numberofstringstooutput
combo:
pos-indexofinitialstring
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
numberofstringsisdefinedbyserversettings
Whileworkingwithgrid,initialrequest(griddoesn'tknowyethowmanystringsareexpected)doesn'tcontainanyadditional
parameters('posStart'and'count'arenotdefined)
Backtotop
Grid
<rows>
<rowid="some1"><cell>value1,1</cell><cell>value1,2
<rowid="some2"><cell>value2,1</cell><cell>value2,2
</rows>
row-thetagrepresentsrowinthegridcell-thetagrepresentscellinthegrid
row@id-themandatoryattribute,mustbeuniqueforeachrow;rowandcelltagsmaycontainadditionalattributeswhichwillbeprocessedindefaultway.
Indynamicloadingmode
<rowstotal_count="50000"pos="1230">
<rowid="some1230"><cell>value1,1</cell><cell>value1,2
<rowid="some1231"><cell>value2,1</cell><cell>value2,2
</rows>
rows@total_count-countofrowsingrid,needstobesentonlyforthefirstdatarequest(whenposStartparameterisnotdefined)rows@pos-equaltoposStartparameters,defineswheregriddatawillbeadded
TreeGrid
<rows>
<rowid="some1">
<cellimage="some.gif">value1,1</cell><cell>value1,2
<rowid="some11"><cell>childvalue1</cell><cell
</row>
<rowid="some2"><cell>value2,1</cell><cell>value2,2
</rows>
row-thetagrepresentsrowinthegrid,onerowtagcancontainotherrowtagsinside(parent-childrelationinthehierarchy)cell-thetagrepresentscellinthegridrow@id-themandatoryattribute,mustbeuniqueforeachrowcell@image-candefineimagefortreecellingrid(optional)
Dyn.loading
<rowsparent="id">
<rowid="some1"xmlkids="1">
<cellimage="some.gif">value1,1</cell><cell>value1,2
</row>
<rowid="some2"><cell>value2,1</cell><cell>value2,2
</rows>
row@xmlkids-definesthatrowcancontainchildnodesrows@parent-thenameofparentID(equaltoincoming“id”parameter),IDofvirtualroot-0
Tree
<tree>
<itemid="some"text="name">
<itemid="child1"text="name1"/>
<itemid="child2"text="name2"/>
</item>
</tree>
itemtag-iteminatree,cannestotheritemtagstorepresentparent-childrelationitem@id-ID,uniqueforeachitemitem@text-label
Incaseofdyn.loading
<treeid="id">
<itemid="some"text="name"childs="1">
</item>
</tree>
item@childs-definesthatrowcancontainchildnodestree@id-thenameofparentID(equaltoincoming“id”parameter),IDofvirtualroot-0
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Combo
<data>
<optionvalue="some">Somelabel</option>
<optionvalue="other">Otherlabel</option>
</data>
option-representsoptionincombo
Incaseofdyn.loading:
<dataadd="true">
<optionvalue="some">Somelabel</option>
<optionvalue="other">Otherlabel</option>
</data>
If“pos”parameterwasprovided,responsemustcontaindata@addattribute,tomarkthatitisnotanewsetofvalues,butadditiontoexistingone.
UsingdhtmlxConnectorwithCodeIgniter,YII,CakePHPframeworksStartingfromversion1.5dhtmlxConnectorcanbeusedwithpopularPHPframeworks.YoucanbuiltwebapplicationswithyourfavoriteframeworksandstillusedhtmlxConnector.
Inthisarticlewewillgiveyouthebrieftipsreferringtosuchuse-caseofdhtmlxConnector.Thedetailinformationyoucangetintherelatedtutorials:
1. UsingdhtmlxConnectorwiththeCodeIgniterframework;2. UsingdhtmlxConnectorwiththeYIIframework;3. UsingdhtmlxConnectorwiththeCakePHPframework.
Asanexample,let'stakecreatinganappthatpresentsgridloadeddatafromdb.TheappisbuiltwithoneoftheframeworksandusedhtmlxConnectortoloaddatain.
Tipscommonforallframeworks
Model:Doesn'thaveanyspecificityandcreatedasusual.
View:
ViewcontainsastandardJavaScriptcodeofthecomponentanddefinestheclientsidelogic;Toloaddatausestandard'loading'methodsofthecomponentsbutastheURLparameterspecifytherelativepathtoanactionthatanswersforloadinglogic.IfyouusedataProcessor,specifyinitsconstructorthisrelativepathtotheactionaswell;
mygrid=newdhtmlXGridObject('grid_here');
...
mygrid.init();
mygrid.loadXML("./data");//referstothe'data'action
vardp=newdataProcessor("./data");//referstothe'data'actionaswell
dp.init(mygrid);
Controller:
Controllerdefinestheserversidelogicandcontainsatleast2actions:theoneloadstheview,theotherloadsthedata;Tohandleanevent,addafunctionofthecorrespondingeventname(e.g.tohandlebeforeRenderevent,addpublicfunctionbeforeRender($action){…})anddefinethehandlinglogicasusual.Thefunctionswilltakethesameparametersastheordinaryeventsdo;SQLquerytodatabaseisconfiguredwiththehelpofconfigure()methodthattakesasparameters:
$sql-anysqlcodethatwillbeusedasthebasefordataselection(fortheYiiframeworkthehardcodedvalue-'-');$id-thenameoftheidfield;$text-acommaseparatedlistofrendereddatafields;
$extra-(optional)acommaseparatedlistofextrafields;relation_id-(optional)usedforbuildinghierarchyincaseofTreeandTreeGrid.
GridConnector(oranyotherconnector)takesasparameters:theDBconnectionvariablethatreferstothemodelusedintheapp)thehardcodedvaluespecifiedtheframework(“phpCI”,“PHPYii”or“PHPCake”).
//samplecodefortheYIIframework
<?php
require_once(dirname(__FILE__)."/../../../dhtmlx/connector/grid_connector.php"
require_once(dirname(__FILE__)."/../../../dhtmlx/connector/db_phpyii.php"
classEventControllerextendsController
{
publicfunctionactionIndex(){$this->render('index'
publicfunctionactionGrid(){$this->render('grid')
publicfunctionactionGrid_data()
{
$grid=newGridConnector(Events::model(),"PHPYii"
$grid->configure("-","event_id","start_date,end_date,event_name"
$grid->render();
}
publicfunctionbeforeProcessing($action){
//validationbeforesaving
if($action->get_value("event_name")==""){
$action->invalid();//ifdataisn'tvalidate-call$action->invalid();
$action->set_response_attribute("details"
}
}
}
Framework-specifictips
CodeIgniter
View
WhileworkingwithCodeIgniteryoushouldrenamethequerystatusparameter!nativeeditor_statuscausethedefaultnameoftheparameterisblockedbytheframework.Renamingmustberepeatedontheserverside.
vardp=newdataProcessor("./data");//referstothe'data'action
dp.action_param="dhx_editor_status";
dp.init(mygrid);
Controller
Requiredconnectorfile-db_phpci.php(andofcourse,youshouldalsoincludeconnectorfilesrelatedtocomponentsusedintheapp,e.g.ifyouusedhtmlxGrid-youalsoincludegrid_connector.php);Thequerystatusparameter!nativeeditor_statusmustberenamedontheserversideaswell.
require_once("./dhtmlx/connector/grid_connector.php");
require_once("./dhtmlx/connector/db_phpci.php");
DataProcessor::$action_param="dhx_editor_status";
classGridextendsCI_Controller{
publicfunctionindex()
{
$this->load->view('grid');//grid'sview
}
publicfunctiondata()
{
$this->load->database();
$connector=newGridConnector($this->db,"phpCI"
$connector->configure("events","event_id",
$connector->render();
}
}
YII
Controller
Requiredconnectorfile-db_phpyii.php.
<?php
require_once(dirname(__FILE__)."/../../../dhtmlx/connector/grid_connector.php"
require_once(dirname(__FILE__)."/../../../dhtmlx/connector/db_phpyii.php"
classEventControllerextendsController{
publicfunctionactionIndex(){$this->render(
publicfunctionactionGrid(){$this->render(
publicfunctionactionGrid_data()
{
$grid=newGridConnector(Events::model()
$grid->configure("-","event_id","start_date,end_date,event_name"
$grid->render();
}
}
?>
CakePHP
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Controller
Requiredconnectorfile-db_phpyii.php.
<?php
require_once("../Vendor/connector/grid_connector.php");
require_once("../Vendor/connector/db_phpcake.php");
classEventControllerextendsAppController{
publicfunctiongrid(){}
publicfunctionindex(){}
publicfunctiongrid_data()
{
$this->autoRender=false;
$connector=newGridConnector($this->Event
$connector->configure("events","event_id"
$connector->render();
}
}
?>
HowcanI:General:
…assignaliasestoDBfields?…attachevent?…checkvalueofanitem?…createcustomdatabaseerrormessage?…customizecontentofacell?…denyaccesstoacertainoperation?…filterdataonserver-side?…handleerrorsandlogthem?…setvalueofanitem?…sortdataonserver-side?…validatedataonclient-side?…validatedataonserver-side?
Loadingdata:
…enabledynamicloading?…format/changedatabeforeloading?…loaddatafromdatabasetable?…loaddatafromExcelfile?…loaddatafromFileSystem?…sendadditionalinformationtoclient-side?
Updatingdata:
…alterthedefaultstylessetforresponses?…avoidupdatingcertainfield(s)onserver-side?
Components-specific:
Combo:…populatecombowithdatafromdb?
Form:…populate'select'itemwithdatafromdb?…populate'combo'itemwithdatafromdb?…loaddatafromdb?…savechangesmadeinaformtodb?
Grid:…definegridconfigurationonserver-side?…exportgrid'sdatafromservertoExcelfile?…exportgrid'sdatafromservertopdffile?…loaddatafromatablethatdoesn'tcontainidentityfield?…populateselect/combocolumnswithdata?…setacustomstyleforaroworacell?
TreeandTreeGrid:…loaddatafrommultipletables?…loaddatafromtablethatdoesn'tcontainrelationfield?…markanitemasaleaforbranch?
DataStore:…useconnectorfunctionalityfordhtmlXDataStoreobjects?
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
…changedefaultdataprocessingwhileupdating?…setcustomstatusofoperation?…terminateanyfurtherprocessing?…changevaluesbeforesaving?…implementtransactions?…linkdataProcessorwithconnector?…realizemulti-usersync?…savedatachangesmadeinform?…updatedataonserver-side?
Generalhow-tos
HowcanIassignaliasestoDBcolumns?
Usingrender_sql()orrender_table()youcanassignaliasestorequiredtablesorcolumns.Todothis,insqlstatementyoushoulduseword'as'(asinanyusualsqlstatement),inotherparameters-parentheses.
$grid->render_table("tableA","id","name,price(product_price)"
//or
$grid->render_sql("Select*,tableA.idasaidfromtableA,tableBwheretableA.id=tableB.id"
HowcanIattachevent?
Toattacheventyoushoulduseevent→attach().Formoredetailsofthistopic,see'Eventhandling'quide.
$conn->event->attach(event_name,handlerFunc);
HowcanIcheckvalueofanitem?
Usingget_value()methodyoucancheckvalueofanyitem.
$grid->get_value($name);
HowcanIcreatecustomdatabaseerror
message?
ToaddacustomerrormessageyoucanusetheeventonDBErrorandwritethedesiredmessageintheappropriatehandler.
functiondoOnDBError($action,$exception){
$action->set_response_text("Somedetailsabouterror"
}
$conn->event->attach("onDBError",doOnDBError);
HowcanIdenyaccesstoacertainoperation?
Bydefault,connectorallowsalloperations.Todenysomeoperationusedeny(name_of_operation)methodthatcangetoneofthefollowing:read/update/insert/delete.Formoredetailssee'Security'guide.
$conn->access->deny("update");
HowcanIcustomizecontentofacell?
YoucanusebeforeRendereventtodefinehowcontentofacellmustbeformatted.
functioncustom_data($row){
$data=$row_get_value("some_column");
$row->set_value("some_column","$data<inputtype='text'/>"
}
$grid->event->attach("beforeRender","custom_data");
Inthesampleabove,thegridwillhavecustomcontent-htmlinput'text'.
HowcanIfilterdataonserver-side?
Youhave3waystofilterdataonserverbackend:
byspecifyingadditionalparametersinURL(onclient-side)
grid.load("some.php?connector=true&dhx_filter[1]=mask");
byusingin-headerfiltertypeswhilecomponentconfiguration(onclient-side)
mygrid.setHeader("ColumnA,ColumnB");
mygrid.attachHeader("#connector_text_filter,#connector_select_filter"
bymeansofbeforeRenderevent(onserver-side)
functioncustom_filter($data){
...
}
$conn->event->attach("beforeRender","custom_filter");
Seetheguide'Filtration'formoreinformation.
HowcanIhandleerrorsandlogthem?
Youcanenableloggingusingenable_log()method.Formoredetailssee'Errorhandlingandlogging'guide.
$conn->enable_log("pathtologfile");//toshowshortinfoonclient-side
//or
$conn->enable_log("pathtologfile",true);//toshowfullinfoonclient-side
HowcanIsetvaluetoanitem?
Usingset_value()method,youcansetvaluetoanyitemofcomponent.
$dataItem->set_value($name,$value)
HowcanIsortdataonserver-side?
Youhave2waystosortdataonserverbackend:
byspecifyingadditionalparametersinURL(onclient-side)
grid.load("some.php?connector=true&dhx_sort[2]=asc");
byusingsortingtype'connector'whilecomponentconfiguration(onclient-side)
grid.setColSorting("connector,str,na);
Seetheguide'Sorting'formoreinformation.
HowcanIvalidatedataonclient-side
dataProcessorletsyouvalidatedataonclient-side.UsesetVerificator(index,method)methodtodefinetheappropriatecolumns
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
andvalidators.SeedetailsintherelatedchapterofdataProcessor'documentation.
dp.setVerificator(column_index,verification_func)
HowcanIvalidatedataonserver-side
Toperformserver-sidevalidationyoushoulduseoneofthedhtmlxConnectoreventsstatedbelowandspecifytheneededvalidationrulesintheappropriateevents'handlersfunctions:
beforeUpdatebeforeInsertbeforeDeletebeforeProcessing
functionvalidate($data){
...
}
$conn->event->attach("beforeProcessing","validate");
Formoredetailsofserver-sidevalidation,seeguide'Validation'.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
ThistopicdoesnotexistyetYou'vefollowedalinktoatopicthatdoesn'texistyet.Ifpermissionsallow,youmaycreateitbyusingtheCreatethispagebutton.
Createthispage
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
ThistopicdoesnotexistyetYou'vefollowedalinktoatopicthatdoesn'texistyet.Ifpermissionsallow,youmaycreateitbyusingtheCreatethispagebutton.
Createthispage
HowcanIenabledynamicloading?
Toenabledynamicloadingyoushould:
onclient-sideenabletherelatedmode(e.g.smartrenderingorpagingforgrid)
grid.enableSmartRendering(mode,buffer);
onserver-sidecallmethoddynamic_loading()
$grid->dynamic_loading([$rowsNum]);
Seetheguide'Dynamicloading'formoreinformation.
HowcanIformat/changedatabeforeloading?
Tosetsomespecificformattingorchangedatabeforesendingtoclient-side,youshouldusethebeforeRendereventhandler.Formoredetailsofthistopic,see'Formatting/ChangingDatabeforeLoading'
functioncolor_rows($row){
if($row->get_index()%2)
$row->set_row_color("red");
}
$grid->event->attach("beforeRender","color_rows");
HowcanIloaddatafromdatabasetable?
Toloaddatafromdatabasetableyoushoulduseoneoftwomethods:
render_table()(forloadingfromsingletable)
$grid->render_table("tableA","item_id","column1,column2",
render_sql()(forloadingfromseveraltables)
$grid->render_sql("Select*fromtableA,tableBwheretableA.id=tableB.id"
HowcanIloaddatafromExcelfile?
ToloaddatafromExcelfileyoushoulddownloadphpExcellibraryfromhttp://support.dhtmlx.com/x-files/connector/phpExcel.zipandinclude
additionalfiles:
'lib/PHPExcel.php'(phpExcelpackage)'lib/PHPExcel/IOFactory.php'(phpExcelpackage)'db_excel.php'(standardconnector'spackage)
Then,callrender_table())methodwhereasparametersyoushouldspecifycellrangeandExcelcolumns.Setthesecondparameterto'id'forautoidgeneration.
//filesfromphpExcelpackage
require_once('lib/PHPExcel.php');
require_once('lib/PHPExcel/IOFactory.php');
//connectors
require("../../codebase/db_excel.php");
require("../../codebase/grid_connector.php");
$grid=newGridConnector("../some.xls","ExcelDBDataWrapper"
$grid->render_table("A18:F83","id","A,B,C,D,E,F");
Formoredetails,seetheguidechapter'loadingfromExcelfile'in'Baseconcepts'guide.
HowcanIloaddatafromFileSystem?
ToloaddatafromFileSystemyoushouldincludeoneadditionalfiledb_filesystem.phpandcallrender_table()methodwhereasparametersyoushouldspecifyfolder(thatrequiresdatalisting),field'sid(leaveitemptyorusesafe_nameasIDoffile)andlistsoffields.
require("./codebase/connector/db_filesystem.php");
require("./codebase/connector/grid_connector.php");
$grid=newGridConnector("","FileSystem");
$grid->render_table("../","safe_name","filename,full_filename,size,name,extention,date,is_folder"
Formoredetails,seetheguidechapter'loadingfromFileSystem'in'Baseconcepts'guide.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
HowcanIsendadditionalinformationtoclient-side?
Tosendadditionalinformationtoclient-sidethatwon'tbeoutputedbutyou'llhaveaccesstoit,usethefourth(optional)parameterofrender_table()method.Thereyoushouldspecifycolumnsthatcontaindesiredadditionalinformation.
$grid->render_table("some_table","id","name,price","color,count"
Formoreinoformation,seethechapter'Usingextrafields'in'Formatting/ChangingDatabeforeLoading'guide.
Datamanagementhow-tos(updatingdata)
HowcanIalterthedefaultstylessetforresponses?
Youcanalterthedefaultstylesforeachstate,like:
dp.styles.error="";//avoidsaspecialstyleforthe'error'response
//youshouldwriteitontheclient-side(inyourHTMLfile)
//dp-dataProcessorobject
HowcanIavoidupdatingcertainfield(s)?
Toremovesomefieldfromupdating,youcanusethefollowingtechnique:
//writeitbefore'$grid->render_table'
functionfilter_set($action){
$action->remove_field("id");//thenamedfieldwon'tbeincludedinCRUDoperations
}
$grid->event->attach("beforeProcessing",filter_set);
HowcanIchangedefaultdataprocessingwhileupdating?
Toaffectondefaultdataprocessingeitheronserver-orclient-sideyoushoulduseeventseitherofdataProcessorordhtmlxConnector.Formoredetails,seethechapter'changingdefaultprecessing'in'Client-side
requirement-dataProcessor'.
HowcanIsetcustomstatusofoperation?
Usingset_status()methodyoucansetstatus(customoranotherpredefined)ofoperation.UsingdefineAction()methodofdataProcessoryoucanassigntheappropriateprocessingforthisstatus.
//server-side
$data->set_status("my_status");
//client-side
dp.defineAction("my_status",function(sid,response){
...
returntrue;//returnfalsetocanceldefaultdataprocessingatall
})
HowcanIterminateanyfurtherprocessing?
Callingsuccess()methodyouterminateanyfurtheractionprocessing,i.e.dataupdatingwillbestoppedandconsideredasfinished.
functionmy_update($data){
...
$data->success();//marksoperationasfinished
}
$conn->event->attach("beforeUpdate","my_update")
HowcanIchangevaluesbeforesaving?
Tocustomizevaluesbeforesavingyoushoulduseserver-sideeventsstatedbelow:
beforeUpdatebeforeInsertbeforeDeletebeforeProcessing
functionmy_update($data){
...
}
$conn->event->attach("beforeUpdate","my_update")
Formoreinformation,see'Usingserver-sideevents'in'Makingqueries'guide.
HowcanIimplementtransactions?
ConnectorallowstousetransactionsforINSERT/UPDATE/DELETEoperations(besurethatusedDBenginehassupportfortransactions).Toactivatetransactionmode-useset_transaction_mode()method.Formoredetailsseethechapter'Transactions'in'Makingqueries'guide.
$conn->sql->set_transaction_mode("global");//forallrecordsinsidesinglerequest
//or
$conn->sql->set_transaction_mode("record");//foreachrecordinrequest
HowcanIlinkdataProcessorwithconnector?
TolinkdataProcessorwithconnectoryoushouldspecifyconnectorfileasaparameterofdataProcessorconstructor:
dp=newdataProcessor("myconnector.php");
dp.init("mygrid");
HowcanIrealizemulti-userssync?
Toactivatemulti-usermodethatwillallowuserstoseechangesofeachotherinreal-time,youmustaddcodebothonclient-andserver-side.Onserver-side,tobasicinitializationconnectorcodeyoushouldadd:
$conn->enable_live_update('actions_table');//actions_tableisusedforsyncdatastorage
Onclient-side,youshouldinitializedataprocessorandcallsetAutoUpdate():
dp.setAutoUpdate(2000);//inputparameterisdelaybetweenupdatecalls
SeeMulti-usersyncformoreinformation.
HowcanIupdatedataonserver-side?
Toupdatedataonserver-side,onclient-sideyoushouldinitializedataProcessorandlinkdhtmlxConnectortoit.Defaultupdatingwillbedoneautomatically.Formoredetails,seetheguide'Client-siderequirement-dataProcessor'.
HowcanIsavedatachangesmadeinform(simpleway)?
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
dhtmlxConnectorautomaticallyexecCRUDoperationsfornextpatterns:
//togetdataofaDBrecord
GET:connector.php?action=get&id={some}
//todeletedataofaDBrecord
GET:connector.php?action=delete
//toupdatedataofaDBrecord
GET:connector.php?action=delete
POST:id={some}&property_name={value}
//toinsertanewrecordtoDB
GET:connector.php?action=insert
POST:property_name={value}
Formoredetails,seetheguide'Savingdatachangesmadeinform'.
Component-specifichow-tos(combo)
HowcanIpopulatecombowithdatafromdb?
TodefineoptionsofcomboyoushoulduseComboConnectorontheserver-sideandspecifytheconnectorfileintheloadXML(url)methodonclient-side:
client-side:
varcombo=newdhtmlXCombo("combo_zone2","alfa2",200);
combo.loadXML("connector.php");
server-side:
<?php
require_once("../codebase/connector/combo_connector.php");
$res=mysql_connect("localhost","root","");
mysql_select_db("mydb");
$data=newComboConnector($res,"MySQL");
$data->render_table("categories","id","valueColumn,labelColumn"
?>
Namesofthefieldscanhavealiases(valueorlabel)toidentifytheappropriateattribute.
$data->render_sql("SELECT*,CONCAT(FirstName,LastName)aslabelFROMtable1"
Note,inthefilteringmodeacombofiltersdatabythe“label”field.
Component-specifichow-tos(form)
HowcanIpopulate'select'itemwithdatafromdb?
TodefineoptionsoftheselectitemyoushoulduseSelectOptionsConnectorontheserver-sideandspecifytheconnectorparameterfortheappropriateitemonclient-side:
client-side:
varformData=[{type:"select",label:"Categories",connector
server-side:
<?php
require_once("../codebase/connector/options_connector.php");
$res=mysql_connect("localhost","root","");
mysql_select_db("myDB");
$data=newSelectOptionsConnector($res,"MySQL");
$data->render_table("categories","id","valueColumn,labelColumn"
?>
Formoreinformationofthistopic,see'SelectOptionsConnector'article.
HowcanIpopulate'combo'itemwithdatafromdb?
Todefineoptionsofthe'combo'itemyoushoulduseComboConnectorontheserver-sideandspecifytheconnectorparameterfortheappropriateitemonclient-side:
client-side:
varformData=[{type:"combo",name:"myCombo",label:"Selecttype"
server-side:
<?php
require_once("../codebase/connector/combo_connector.php");
$res=mysql_connect("localhost","root","");
mysql_select_db("myDB");
$data=newComboConnector($res,"MySQL");
$data->render_table("categories","id","valueColumn,labelColumn"
?>
Namesofthefieldscanhavealiases(valueorlabel)toidentifytheappropriateattribute.
$data->render_sql("SELECT*,CONCAT(FirstName,LastName)aslabelFROMtable1"
Note,inthefilteringmodeacombofiltersdatabythe“label”field.
HowcanIloaddatafromdb?
ToloaddatatoaformyoushoulduseFormConnectoronserver-sideandthemethodload(id)onclient_side:
client-side
myForm.load('formdata.php?id=1');
whereastheparametermustbespecifiedaconnectorfilewiththeidofloadingrecord.Valuesofrecord'scolumnswillbeusedasvaluesofform'scontrols.
server-side
<?php
require_once("../codebase/connector/form_connector.php");//includestheappropriateconnector
$res=mysql_connect("localhost","root","");//connectstoaserverthatcontainsthedesiredDB
mysql_select_db("tasks");//connectstotheDB.'tasks'isthenameofourDB
$conn=newFormConnector($res,"MySQL");//connectorinitialization
$conn->render_table("customers","id","name,address,email")
?>
Formoreinformationofthistopic,see'dhtmlxForm:easydealingwithserver-side'tutorial.
HowcanIsavechangesmadeinaformtodb?
TosaveformchangestoDB,youshouldusethemethodsave()onclient-side.Youcancallthismethod,forexample,onclicksofsomebutton.
myForm.attachEvent("onButtonClick",function(id){
if(id=='saveButton'){
myForm.save();
}
}
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Formoreinformationofthistopic,see'dhtmlxForm:easydealingwithserver-side'tutorial.
Component-specifichow-tos(grid)
HowcanIdefinegridstructureonserver-side?
Todefinegridstructureonserver-sideyoucanuseoneoftwomodes:
automaticmanual
Inbothmodesyoushoulduseset_config()methodwhereasinputparameterGridConfigurationobjectmustbespecified.
Inautomaticmode,gridwillusenamesoftable'sfieldsaslabelsforthecolumns.
$config=newGridConfiguration();
$grid->set_config($config);
$grid->render_table("grid50000","item_id","item_nm,item_cd")
Inmanualmode,structureisdefinedbyphpcommand.Namesofcommandsmimicnamesofjscommandswithsimilarfunctionality.
$config=newGridConfiguration();
$config->setHeader(array("column1","column2"));
$config->setColTypes(array("ro","ed"));
$grid->set_config($config);
$grid->render_table("grid50000","item_id","item_nm,item_cd")
Formoreinformationofthetopicscoveredhere,see'defininggridstructureonserver-side'guide.
HowcanIexportgrid'sdatafromservertoExcelfile?
ToexportdatatoExcelfileyoushould:
1. Includeoneadditionalfile
require("../../../codebase/convert.php");
2. Activateconversionservice
$convert=newConvertService("http://dhtmlx.com/docs/products/devExchange/samples/grid2excel_02/server/generate.php"
3. Startexporting
$convert->excel("some.xls",false);
Bothmethod'sparametersareoptional.Thefirstparameterisanameofoutputfile.Thesecondparameterspecifieshowfilewillbeexported:true-asinlinecontent,false-asindividualfile.
Afteryoucallthemethodexcel(),serviceautomaticallywillstarttoexportdatadefinedthroughGridConnector.
Formoreinformationofthistopic,see'Dataexport'guide.
HowcanIexportgrid'sdatafromservertopdf
file?
Toexportdatatopdffileyoushould:
1. Includeoneadditionalfile
require("../../../codebase/convert.php");
2. Activateconversionservice
$convert=newConvertService("http://dhtmlx.com/docs/products/devExchange/samples/grid2pdf_02/server/generate.php"
3. Startexporting
$convert->pdf("some.pdf",false);
Bothmethod'sparametersareoptional.Thefirstparameterisanameofoutputfile.Thesecondparameterspecifieshowfilewillbeexported:true-asinlinecontent,false-asindividualfile.
Afteryoucallthemethodpdf(),serviceautomaticallywillstarttoexportdatadefinedthroughGridConnector.
Formoreinformationofthistopic,see'Dataexport'guide.
HowcanIpopulateselect/combocolumnswithdata?
Todefineoptionsofselect/combocolumnsyouhave2ways:
1. toloaddatafromthesametablethegridispopulatedwithdatafrom
$grid->set_options("item_nm",array("1"=>"one","2"=>
$grid->render_table("grid50","item_id","item_nm,item_cd"
2. toloaddatafromanothertable
$options=newOptionsConnector($res);
$options->render_table("countries","country_id","country_id(value),country_name(label)"
$grid->set_options("item_nm",$options);
$grid->render_table("grid50","item_id","item_nm,item_cd"
Formoreinformationofthistopic,see'Select/comboboxcolumnsingrid'article.
HowcanIloaddatafromatablethatdoesn'tcontainidentityfield?
UsingKeyGridConnectorinsteadofGridConnector,youcanloaddatafromatablewithoutidentityfield.Inthiscase,anydatafieldwillserveasidentity.
$grid=newKeyGridConnector($res);
$grid->render_table("mytable","name","name,address,phone");
Formoredetails,see'KeyGridConnector'guide.
HowcanIsetacustomstyleforaroworacell?
dhtmlxConnectorcontainsabitofmethodsthatallowtosettheappearanceofagrid.Thesemethodscanbedividedinto2groups:
foracellcustomization:
set_cell_attributeset_cell_classset_cell_style
forarowcustomization:
set_row_attributeset_row_colorset_row_style
functioncolor_rows($row){
if($row->get_index()%2)
$row->set_row_color("red");
}
$grid=newGridConnector($res);
$grid->event->attach("beforeRender","color_rows");
$grid->render_table("records","item_id","item_nm,item_cd");
Tips:
tooverwritebackgroundyoushoulduse'background'not'background-color'attribute.skin'scsscanoverwriteanumberofcssattributes.Toavoidit-usethe!importantflag.
$row->set_row_attribute("class","backrgroundclass");
.backrgroundclass{
background:red!important;
}
HowcanIloaddatafrommultipletables?
UsingTreeMultitableConnector/TreeGridMultitableConnectorinsteadofTreeConnector/TreeGridConectoryoucanloaddatafrommultipletables.
require("../../codebase/treemultitable_connector.php");
$tree=newTreeMultitableConnector($res);
$tree->setMaxLevel(3);
$level=$tree->get_level();
Formoredetails,see'TreeMultitableConnector/TreeGridMultitableConnector'guide.
HowcanIloaddatafromtablethatdoesn'tcontainrelationfield?
UsingTreeGroupConnector/TreeGridGroupConnectorinsteadofTreeConnector/TreeGridConectoryoucanloaddatafromtablethatdoesn'tcontainrelationfield.
require("./codebase/connector/tree_group_connector.php");
$tree=newTreeGroupConnector($res);
$tree->render_table("products2","id","product_name","","category"
Formoredetails,see'TreeGroupConnector/TreeGridGroupConnector'guide.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
HowcanImarkanitemasaleaforbranchoftree?
InbeforeRendereventhandleryouareallowedtomarkanitemasaleaforbranch.Forthispurpose,youshoulduseset_kids()method.Asinputparametertrueorfalsemustbespecified.truemarksanitemasabranch,false-asaleaf.
$item->set_kids(false);
Formoredetailssee'tree/treeGridspecific'chapterin'Dynamicloading'guide.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
HowcanIuseconnectorfunctionalityfordhtmlXDataStoreobjects?
Thereare2connectortypesyoucanusefordhtmlXDataStoreobjects:
JSONDataConnectorDataConnectorFormoredetails,seetherelatedchapterofthisdocumentation.
HowcanIuseconnectorfunctionalityforDHTMLXTouchcomponents?
Thereare2connectortypesyoucanusefortouchcomponents:
JSONDataConnectorDataConnectorFormoredetails,seetherelatedchapterofthisdocumentation.
ToimplementCRUDoperationyoushoulduseconnectorsmentionedabovetogetherwithTouchdataProcessor.Formoredetails,seeDHTMLXTouchdocumentation.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
HowcanIsavedatachangesmadeinform(simpleway)?
Basically,tosavedatachangesyoucanusecodelike:
dhx.ajax().post("connector.php?action=insert",$$('form').getValues
Formoredetails,seetheguide'Savingdatachangesmadeinform'.
APImethodsAllthemethodscanbedividedintomain2categories:
Connectormethods-methodsofdhtmlxConnectorinstance.Availablethroughouttheprogram.
ConnectorObject-relatestodhtmlxConnectorinstance.Eventmethods-methodsavailablejustinsideevents'handlerfunctions(differenteventsprovidedifferentmethods.Theappropriateonesdependoninputobject).
DataActionObject-relatestoactionqueries.Inputobjectof:beforeInsert,beforeUpdate,beforeDelete,beforeProcessing,afterProcessing,afterDelete,afterUpdate,afterInsertevents.DataItemObject-relatestouseddhtmlxcomponent.Inputobjectof:beforeRenderevent.SortInterfaceObject-relatestocollectionofsortingrules.Inputobjectof:beforeSortevent.FilterInterfaceObject-relatestocollectionoffiltrationrules.Inputobjectof:beforeFilterevent.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
Orderofexecution
ConnectorObject-methodsofthemainobjectrender_tablerender_sqlset_encodingdynamic_loadingenable_logis_select_mode
Eventsobjects-objectsthatarepassedasinputparameterstoevents.Mentionedheremethodscanbeusedonlyinsidehandlers'functionsoftheappropriateevents.
DataActionObjectDataItemObjectSortInterfaceObjectFilterInterfaceObject
add_section
(availablefromversion1.5andapplicablejusttoDataConnector/JSONDataConnector)addsthefirstchildtag(section)todata
$conn->add_section($name,$value);
Parameters:
$name-thesectionname$value-thesectionvalue
Seealso:
JSONDataConnector/DataConnector
dynamic_loading
enablesthedynamicalloadingmodeforconnector.
$conn->dynamic_loading([$rowsNum]);
Parameters:
tree,treegrid-noparametersgrid-numberofrowswhichshouldbeinitiallyloaded(thevalueshouldbemorethannumberofrowsvisibleingrid,oratleastanypositivenumber)combo-maximumnumberofoptionswhichserverwillsendforasingledatarequestinautocompletemode
Seealso:
Dynamicloading
enable_log
enablesloggingforconnector.
$conn->enable_log("pathtologfile");
Parameters:
path-absoluteorrelativepathtotextfilewherelogwillbewritten.
Seealso:
Errorshandlingandlogging
is_select_mode
returnscurrentactivemode.
$conn->is_select_mode();
Parameters:
none.
Returns:
true,ifselectmodeisactive.false,ifupdatemodeisactive.
render_array
configuresconnectortotakedatafromaPHParraywhichcanbefilledbyanykindofexternallogic.
$conn->render_array($data,$id,$text,$extra,$relation_id);
Parameters:
$data-nameofPHParray.$id-nameofidfield.$text-commaseparatedlistofdatafields.$extra-commaseparatedlistofextrafields,optional.$relation_id-usedforbuildinghierarchyincaseofTreeandTreeGrid.
SeeAlso:
render_sqlrender_complex_sqlBasicconcepts
render_sql
configuresconnectortotakedatabasedonprovidedSQLtext.
$conn->render_sql($sql,$id,$text,$extra,$relation_id);
Parameters:
$sql-anysqlcode,whichwillbeusedasabasefordataselection.$id-nameofidfield.$text-commaseparatedlistofdatafields.$extra-commaseparatedlistofextrafields,optional.$relation_id-usedforbuildinghierarchyincaseofTreeandTreeGrid.
SeeAlso:
render_tableBasicconcepts
render_complex_sql
configuresconnectortotakedatabasedonprovidedSQLtext.Workssimilartorender_sql,buthave2differences:
1. Usesprovidedsqlexactlyasitis;2. Canbeusedonlyfordataloading(fordatasavingyoucanuse
separateconnector,eventhandlers,orcustommodel).
Themethodcanbeusedtocallstoredproceduresinthedatabase.
$conn->render_complex_sql($sql,$id,$text,$extra,$relation_id
Parameters:
$sql-anysqlcode,whichwillbeusedasabasefordataselectionorthenameofastoredprocedure.$id-nameofidfield.$text-commaseparatedlistofdatafields.$extra-commaseparatedlistofextrafields,optional.$relation_id-usedforbuildinghierarchyincaseofTreeandTreeGrid.
SeeAlso:
render_sqlrender_tableBasicconcepts
render_table
configuresconnectortotakedatafromsingletable.
$conn->render_table($table,$id,$text,$extra,$relation);
Parameters:
$table-nameoftable.$id-nameofidfield.$text-commaseparatedlistofdatafields.$extra-commaseparatedlistofextrafields,optional.$relation_id-usedforbuildinghierarchyincaseofTreeandTreeGrid.
Description:
IfyouwanttorenderallfieldsfromDB(exceptofidentityfield),youcanusesimplifiedcommand:
$conn->render_table($table);
SeeAlso:
render_sqlrender_complex_sqlBasicconcepts
set_encoding
allowsyoutosetencodingthatwillbeappliedtogeneratedXML(defaultencodingisUTF-8).
$conn->set_encoding("iso-8859-1");
Parameters:
encodingname.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
set_limit
limitsthenumberofdataitemsthatwillbeloadedtoacomponent.
$conn->set_limit([$rowsNum]);
Parameters:
numberofdataitemswhichshouldbeloaded
add_field()
allowsyoutoregisterfieldforusagewhileINSERT/UPDATE/DELETEoperation.
$action->add_field($name,$value);
Parameters:
$name-nameoraliasofthefield$value-valueofthefieldinquestion
Seealso:
remove_fieldMakingqueries
error()
marksprovideddataasinvalidandcancelsdefaultUPDATEprocessing(invalidrecordwillbehighlightedinredboldfont).
$action->error()
Parameters:
none
SeeAlso:
invalidValidation
get_data()
returnshashofdatavaluesthatwilltakepartinINSERT/UPDATE/DELETEoperations.
$action->get_data();
Parameters:
none.
get_new_id()
returnstheIDreceivedafterINSERToperation(validforafterProcessingeventonly).
$action->get_new_id()
Parameters:
none.
get_status()
returnsactiontypeoftheitem.
$action->get_status()
Returns:
update,insert,delete,errororcustomstatussetthroughset_status()method
Parameters:
none.
SeeAlso:
set_status
get_value()
returnsvalueofafield.
$action->get_value($name);
Parameters:
$name-nameofcolumnoralias.
SeeAlso:
set_valueValidation
invalid()
marksprovideddataasinvalidandcancelsdefaultUPDATEprocessing(invalidrecordwillbehighlightedinboldfont).
$action->invalid()
Parameters:
none.
SeeAlso:
errorValidation
remove_field()
allowstoremoveoneofdefaultfieldsfromINSERT/UPDATE/DELETEoperation.
$action->remove_field($name,$value);
Parameters:
$name-nameoraliasofthefield.$value-valueofthefieldinquestion.
SeeAlso:
add_field
set_response_attribute()
allowsyoutodefinecustomattributewhichwillbeaddedtotherelatedactiontaginXMLresponse.
$action->set_response_attribute($name,$value);
Parameters:
$name-nameoftheattribute.$value-valueoftheattributeinquestion.
SeeAlso:
set_response_textset_response_xml
set_response_text()
allowsyoutosetstringthatwillbeincludedinresponse
$action->set_response_text($text);
Parameters:
$text-anytextvaluethatwillbereturnedonclient-sidewithrelatedaction.
SeeAlso:
set_response_xmlset_response_attribute
set_response_xml()
allowsyoutosetxml-stringthatwillbeincludedinresponse(ifyouneedtoprovidejustatext-useset_response_text()method).
$action->set_response_xml($text);
Parameters:
$text-anytextvaluethatwillbereturnedonclient-sidewithrelatedaction.
SeeAlso:
set_response_textset_response_attribute
set_status()
setsthestatusofoperation.
$action->set_status($value)
Parameters:
$value-statusofoperation.Itcanbeeithersomepredefinedvalue(updated,inserted,deleted,error)oranycustomstatus.Beware,whenyousetcustomstatusyoucanceldefaultdataprocessing.
SeeAlso:
get_statusValidation
set_value()
setsvalueofafield.
$action->set_value($name,$value)
Parameters:
$name-nameoraliasofthefield$value-valueofthefieldinquestion
SeeAlso:
get_value
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
success()
confirmsthatoperationhasbeenexecutedcorrectlyandcancelsanydefaultdataprocessing.
$action->success()
Parameters:
incaseINSERToperation:anewIDofelement(whichwillbeupdatedonclient-side)
Seealso:
Makingqueries
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
DataItemObjectDifferentcomponentshavedifferentsetsofmethods.Followthelinkofcomponentyouuse.
dhtmlxChartdhtmlxCombodhtmlxDataViewdhtmlxFormdhtmlxGriddhtmlxTreedhtmlxTreeGriddhtmlxScheduler
get_index
returnstheindexofthecurrentlyselecteditem(forexample,ingrid,itwillbetheindexofarow)
$dataItem->get_index();
Parameters:
none.
get_value
returnsthevalueofafield.
$dataItem->get_value($name);
Parameters:
$name-nameoraliasofthefield.
SeeAlso:
set_value
set_id
setstheidofanitem.
$dataItem->set_id($value);
Parameters:
$value-idoftheitem.
Seealso:
get_id
skip
ignoresthecurrentitemwhilerenderingoutput.Allowsyoutodefinecustomfiltrationrules.
$dataItem->skip()
Parameters:
none.
set_value
setsthevalueofafield.
$dataItem->set_value($name,$value)
Parameters:
$name-nameoraliasofthefield$value-valueoftheiteminquestion
SeeAlso:
get_value
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
set_userdata
(availablefromversion1.5)setsuserdatafortheitem.
$dataItem->set_userdata($name,$value)
Parameters:
$name-theuserdataname$value-userdatastring
Seealso:
Formatting/changingdatabeforeloading
get_index
returnstheindexofthecurrentlyselecteditem(forexample,ingrid,itwillbetheindexofarow)
$dataItem->get_index();
Parameters:
none.
get_value
returnsthevalueofafield.
$dataItem->get_value($name);
Parameters:
$name-nameoraliasofthefield.
SeeAlso:
set_value
set_id
setstheidofanitem.
$dataItem->set_id($value);
Parameters:
$value-idoftheitem.
Seealso:
get_id
skip
ignoresthecurrentitemwhilerenderingoutput.Allowsyoutodefinecustomfiltrationrules.
$dataItem->skip()
Parameters:
none
set_value
setsthevalueofafield.
$dataItem->set_value($name,$value)
Parameters:
$name-nameoraliasofthefield$value-valueofthefieldinquestion
SeeAlso:
get_value
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
set_userdata
(availablefromversion1.5)setsuserdatafortheitem.
$dataItem->set_userdata($name,$value)
Parameters:
$name-theuserdataname$value-userdatastring
Seealso:
Formatting/changingdatabeforeloading
get_index
returnstheindexofthecurrentlyselecteditem(forexample,ingrid,itwillbetheindexofarow)
$dataItem->get_index();
Parameters:
none.
get_value
returnsthevalueofafield.
$dataItem->get_value($name);
Parameters:
$name-nameoraliasofthefield.
SeeAlso:
set_value
set_id
setstheidofanitem.
$dataItem->set_id($value);
Parameters:
$value-idoftheitem.
Seealso:
get_id
skip
ignoresthecurrentitemwhilerenderingoutput.Allowsyoutodefinecustomfiltrationrules.
$dataItem->skip()
Parameters:
none
set_value
setsthevalueofafield.
$dataItem->set_value($name,$value)
Parameters:
$name-nameoraliasofthefield$value-valueofthefieldinquestion
SeeAlso:
get_value
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
set_userdata
(availablefromversion1.5)setsuserdatafortheitem.
$dataItem->set_userdata($name,$value)
Parameters:
$name-theuserdataname$value-userdatastring
Seealso:
Formatting/changingdatabeforeloading
get_index
returnstheindexofthecurrentlyselecteditem(forexample,ingrid,itwillbetheindexofarow)
$dataItem->get_index();
Parameters:
none.
get_value
returnsthevalueofafield.
$dataItem->get_value($name);
Parameters:
$name-nameoraliasofthefield.
SeeAlso:
set_value
set_id
setstheidofanitem.
$dataItem->set_id($value);
Parameters:
$value-idoftheitem.
Seealso:
get_id
skip
ignoresthecurrentitemwhilerenderingoutput.Allowsyoutodefinecustomfiltrationrules.
$dataItem->skip()
Parameters:
none
set_value
setsthevalueofafield.
$dataItem->set_value($name,$value)
Parameters:
$name-nameoraliasofthefield$value-valueofthefieldinquestion
SeeAlso:
get_value
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
set_userdata
(availablefromversion1.5)setsuserdatafortheitem.
$dataItem->set_userdata($name,$value)
Parameters:
$name-theuserdataname$value-userdatastring
Seealso:
Formatting/changingdatabeforeloading
get_index
returnstheindexofthecurrentlyselecteditem(forexample,ingrid,itwillbetheindexofarow)
$dataItem->get_index();
Parameters:
none.
get_value
returnsthevalueofafield.
$dataItem->get_value($name);
Parameters:
$name-nameoraliasofthefield.
SeeAlso:
set_value
set_cell_attribute
setsanattributeforacellofitem.
$dataItem->set_cell_attribute($name,$attr,$value)
Parameters:
$name-nameofaliasofthecell$attr-nameofattribute$value-valueofattribute
SeeAlso:
set_cell_styleset_cell_class
set_cell_class
setsacssclassforacellofitem.
$dataItem->set_cell_class($name,$value);
Parameters:
$name-nameoraliasofthecell$value-cssclassforthecell
SeeAlso:
set_cell_styleset_cell_attribute
set_cell_style
setsthestyleforacellofitem.
$dataItem->set_cell_style($style);
Parameters:
$style-HTMLstyleattributes.
SeeAlso:
set_cell_classset_cell_attribute
set_id
setstheidofanitem.
$dataItem->set_id($value);
Parameters:
$value-idoftheitem.
Seealso:
get_id
set_options
assignsoptionscollectiontoacolumn.
$dataItem->set_options($name,$options);
Parameters:
$name-thenameofthecolumn$options-anarrayofoptionsoraconnectorobject
Sample:
$grid->set_options("column_id",array("1"=>"one","2"=>"two"
//or
$filter1=newOptionsConnector($res);
$filter1->render_table("countries","country_id","country_name(value)"
$grid->set_options("column_id",$filter1);
skip
ignoresthecurrentitemwhilerenderingoutput.Allowstodefinecustomfiltrationrules.
$dataItem->skip()
Parameters:
none
set_row_attribute
setsattributeforanyrowinthecomponent.
$dataItem->set_row_attribute($attr,$value);
Parameters:
$attr-nameofattribute$value-valueofattribute
SeeAlso:
set_row_styleset_row_attribute
set_row_color
setscolorforanyrowinthecomponent.
$dataItem->set_row_color($color)
Parameters:
$color-colorofarow
SeeAlso:
set_row_styleset_row_attribute
set_row_style
setsstyleforanyrowofthecomponent.
$dataItem->set_row_style($style);
Parameters:
$style-HTMLstyleattributes
SeeAlso:
set_row_colorset_row_attribute
set_value
setsvalueofafield.
$dataItem->set_value($name,$value)
Parameters:
$name-nameoraliasofthefield$value-valueofthefieldinquestion
SeeAlso:
get_value
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
set_userdata
(availablefromversion1.5)setsuserdatafortheitem.
$dataItem->set_userdata($name,$value)
Parameters:
$name-theuserdataname$value-userdatastring
Seealso:
Formatting/changingdatabeforeloading
get_check_state
returnsthestateoftheselecteditem.
$dataItem->get_check_state();
Returns:
stateofcheckboxrelatedtotheitem:'0'-unchecked'1'-checked.'-1'-third(custom)state.
Seealso:
set_check_state
get_index
returnstheindexofthecurrentlyselecteditem(forexample,ingrid,itwillbetheindexofarow)
$dataItem->get_index();
Parameters:
none.
get_value
returnsthevalueofafield.
$dataItem->get_value($name);
Parameters:
$name-nameoraliasofthefield.
SeeAlso:
set_value
set_attribute
allowsyoutosetsomeattributeforaitem.
$dataItem->set_attribute($name,$value);
Parameters:
$name-thenameofanattribute.$value-thevaluethatanattributeissetto.
set_check_state
allowsyoutosetthestateofthecheckboxrelatedtoanitem.
$dataItem->set_check_state($value);
Parameters:
$value-stateoftheitem.Validvaluesare:
'0'-unchecked.'1'-checked.'-1'-thirdcustomstate.
Seealso:
get_check_state
set_id
setstheidofanitem.
$dataItem->set_id($value);
Parameters:
$value-idoftheitem.
Seealso:
get_id
set_image
allowsyoutosetimageforanyitemintree.
$dataItem->set_image($img);
Parameters:
$img-relativepathtoimagewhichwillbesetforaitem.
Description:
Canbeusedwithvariablenumberofparameters.
$dataItem->set_image($img1,$img2,$img3)
$img1-imageoffolderinopenedstate$img2-imageoffolderinclosedstate$img3-imageofleafitem
set_kids
allowsyoutomarkanitemasaleaforbranchoftree.
$dataItem->set_kids($is_enabled);
Parameters:
$is_enabled-(boolean)specifieswhetheranitemmustbemarkedasabranch.
true-itemwillbemarkedasabranch.false-itemwillbemarkedasaleaf.
Seealso:
Dynamicloading
skip
ignoresthecurrentitemwhilerenderingoutput.Allowsyoutodefinecustomfiltrationrules.
$dataItem->skip()
Parameters:
none
set_value
setsthevalueofafield.
$dataItem->set_value($name,$value)
Parameters:
$name-nameoraliasofthefield$value-valueofthefieldinquestion
SeeAlso:
get_value
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
set_userdata
(availablefromversion1.5)setsuserdatafortheitem.
$dataItem->set_userdata($name,$value)
Parameters:
$name-theuserdataname$value-userdatastring
Seealso:
Formatting/changingdatabeforeloading
get_index
returnstheindexofthecurrentlyselecteditem(forexample,ingrid,itwillbetheindexofarow)
$dataItem->get_index();
Parameters:
none.
get_value
returnsthevalueofafield.
$dataItem->get_value($name);
Parameters:
$name-nameoraliasofthefield.
SeeAlso:
set_value
set_cell_attribute
setsanattributeforacellofitem.
$dataItem->set_cell_attribute($name,$attr,$value)
Parameters:
$name-nameofaliasofthecell$attr-nameofattribute$value-valueofattribute
SeeAlso:
set_cell_styleset_cell_class
set_cell_class
setsthecssclassforacellofitem.
$dataItem->set_cell_class($name,$value);
Parameters:
$name-nameoraliasofthecell$value-cssclassforthecell
SeeAlso:
set_cell_styleset_cell_attribute
set_cell_style
setsthestyleforacellofitem.
$dataItem->set_cell_style($style);
Parameters:
$style-HTMLstyleattributes.
SeeAlso:
set_cell_classset_cell_attribute
set_id
setstheidoftheitem.
$dataItem->set_id($value);
Parameters:
$value-idoftheitem.
Seealso:
get_id
set_image
setsimageforallcheckstatesofthenodeintree.
$dataItem->set_image($img);
Parameters:
$img-relativepathtoimagewhichwillbesetfortheitemoftree(relativetothefolderwithtree'sicons).
skip
ignoresthecurrentitemwhilerenderingoutput.Allowsyoutodefinecustomfiltrationrules.
$dataItem->skip()
Parameters:
none
set_row_attribute
setsanattributeforanyrowinthecomponent.
$dataItem->set_row_attribute($attr,$value);
Parameters:
$attr-nameofattribute$value-valueofattribute
SeeAlso:
set_row_styleset_row_attribute
set_row_color
setscolorforanyrowinthecomponent.
$dataItem->set_row_color($color)
Parameters:
$color-colorofarow
SeeAlso:
set_row_styleset_row_attribute
set_row_style
setsthestyleforanyrowofthecomponent.
$dataItem->set_row_style($style);
Parameters:
$style-HTMLstyleattributes
SeeAlso:
set_row_colorset_row_attribute
set_value
setsthevalueofafield.
$dataItem->set_value($name,$value)
Parameters:
$name-nameoraliasofthefield$value-valueofthefieldinquestion
SeeAlso:
get_value
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
set_userdata
(availablefromversion1.5)setsuserdatafortheitem.
$dataItem->set_userdata($name,$value)
Parameters:
$name-theuserdataname$value-userdatastring
Seealso:
Formatting/changingdatabeforeloading
get_index
returnstheindexofthecurrentlyselecteditem(forexample,ingrid,itwillbetheindexofarow).
$dataItem->get_index();
Parameters:
none.
get_value
returnsthevalueofafield.
$dataItem->get_value($name);
Parameters:
$name-nameoraliasofthefield.
SeeAlso:
set_value
set_id
setstheidofanitem.
$dataItem->set_id($value);
Parameters:
$value-idoftheitem.
Seealso:
get_id
skip
ignoresthecurrentitemwhilerenderingoutput.Allowsyoutodefinecustomfiltrationrules.
$dataItem->skip()
Parameters:
none
set_options
assignsoptionscollectiontoacolumn.
$dataItem->set_options($name,$options);
Parameters:
$name-thenameofthecolumn$options-anarrayofoptionsoraconnectorobject
Sample:
$scheduler->set_options("type",array("1"=>"one","2"=>"two"
//or
$options=newOptionsConnector($res);
$options->render_table("types","type_id","type_id(value),type_name(label)"
$scheduler->set_options("type",$options);
set_value
setsthevalueofafield.
$dataItem->set_value($name,$value)
Parameters:
$name-nameoraliasofthefield$value-valueofthefieldinquestion
SeeAlso:
get_value
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
set_userdata
(availablefromversion1.5)setsuserdatafortheitem.
$dataItem->set_userdata($name,$value)
Parameters:
$name-theuserdataname$value-userdatastring
Seealso:
Formatting/changingdatabeforeloading
add
addsanewsortingruletocollection
$coll->add("name","type");
Parameters:
name-nameofthefield.type-sortingtype:ASCorDESC
Seealso:
Sorting
index
checksiftherearesomerulesincollectionforthespecifiedfieldandreturnstherelatedhash.
$index=$coll->index("name");
Parameters:
name-nameofthefield
Returns:
true-ifcollectioncontainsrule(s)forthespecifiedfield.false-ifcollectiondoesn'tcontainanyrulesforthefield.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
rules
arrayofallspecifiedsortingrules.
$name=$coll->rules[0]["name"];
$coll->rules[0]["direction"]="DESC";
Properties:
name-nameofrelatedfielddirection-directionofsorting
Seealso:
Sorting
add
addsanewfiltrationruletocollection.
$coll->add("name","value");//$nameLIKE$value
//or
$coll->add("name","value","comp_oper");//name<value
Parameters:
name-nameofthefield.value-comporisonvalue(filtrationcriteria).comp_oper-comparisonoperator:'>'or'<'.
Seealso:
Filtering
index
checksiftherearesomerulesincollectionforthespecifiedfieldandreturnsrelatedhash.
$index=$coll->index("name");
Parameters:
name-nameofthefield
Returns:
true-ifcollectioncontainsrule(s)forthespecifiedfield.false-ifcollectiondoesn'tcontainanyrulesforthefield.
Seealso:
Filtering
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
rules
arrayofallspecifiedsortingrules.
$name=$coll->rules[0]["name"]
$coll->rules[0]["value"]="cde";
Properties:
name-nameofrelatedfield.value-comporisonvalue(filtrationcriteria).operation-comporisonoperator.Ifempty-defaultLIKEinstructionisused.
Seealso:
Filtering
Events
eventslist
beforeSortEventbeforeFilterEventbeforeRenderEventbeforeOutputEvent
beforeUpdateEventbeforeInsertEventbeforeDeleteEvent
afterUpdateEventafterInsertEventafterDeleteEvent
beforeProcessingEventafterProcessingEvent
onDBErrorEvent
orderofexecution
dataloading
-incomingrequestparsedbeforeSortbeforeFilter-sqlselectexecuted-foreachselectedrecord
beforeRender-generatexmlforrecord
-outputdatatoclient
dataupdating
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
-incomingrequestparsed-globaltransactionstarted(ifenabled)beforeProcessingforeachrecord
-recordleveltransactionifstarted(ifenabled)beforeInsert|beforeDelete|beforeUpdate-recordleveltransactioncommited(ifenabled)
afterProcessing-globaltransactioncommited(ifenabled)
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
beforeSortTheeventoccursbeforedataloadingandallowstocustomizesortingofdataset
$conn->event->attach("beforeSort",handlerFunc);
ParametershandlerFunc:
$sort_by-SortInterfaceobject
Availability:
AvailableforGrid,Treegrid
Sample:
functioncustom_sort($sorted_by){
$sorted_by->rules[0]["name"]="LENGTH(some_field)";//SORTBYLENGTH(some_field)
}
$conn->attach->event("beforeSort","custom_sort");
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
beforeFilterTheeventoccursbeforedataloadingandallowstocustomizefilteringofdataset.
$conn->event->attach("beforeFilter",handlerFunc);
ParametershandlerFunc:
$filter_by-FilterInterfaceobject
Availability:
AvailableforGrid,Combo
Sample:
functioncustom_filter($filter_by){
if(!sizeof($filter_by->rules))
$filter_by->add("some_field","value","LIKE");
//changeWHEREsome_fieldLIKE'%value%'totheWHEREsome_field>'value'
$index=$filter_by->index("some_field");
if($index!==false)//thereisclientsideinputforthefilter
$filter_by->rules[$index]["operation"]=">";
}
$conn->event->attach("beforeFilter","custom_filter");
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
beforeRenderTheeventoccurseventoccursafterdatahasbeenselectedfromthedatabasebutbeforeitsoutputtingtoclient.
$conn->event->attach("beforeRender",handlerFunc);
ParametershandlerFunc:
$dataItem-DataItemObject
Availability:
AvailableforGrid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form
Sample:
functioncolor_rows($row){
if($row->get_index()%2)
$row->set_row_color("red");
}
$conn->event->attach("beforeRender","color_rows");
beforeOutputTheeventoccurseventoccursafterdatahasbeenselectedfromthedatabaseandreadytobesenttoclientside.EventcanbeusedtomixsomecustomdatainXMLoutput.Themostcommonuse-case-headerstructureforthegrid.
$conn->event->attach("beforeOutput",handlerFunc);
ParametershandlerFunc:
Doesn'tgetanyparameters
Availability:
AvailableforGrid,TreeGrid,Tree,Combo,Scheduler,DataView,Chart,Form
Sample:
functiongrid_header(){
echo'<head>
<columnwidth="50"type="dyn"align="right"color="white"sort="str">Sales</column>
<columnwidth="150"type="ed"align="left"color="#d5f1ff"sort="str">BookTitle</column>
</head>';
}
$conn->event->attach("beforeOutput","grid_header");
//Incaseofdyn.loadingmode,onemorecheckneedtobeadded,topreventdataoutputforadditionaldatacalls.
functiongrid_header(){
if(!isset($_GET["posStart"]))
echo'<head>
<columnwidth="50"type="dyn"align="right"color="white"sort="str">Sales</column>
<columnwidth="150"type="ed"align="left"color="#d5f1ff"sort="str">BookTitle</column>
</head>';
}
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
$conn->event->attach("beforeOutput","grid_header");
$conn->dynamic_loading(100);
beforeUpdateTheeventoccursbeforeupdatingvaluesindatabaseandcancanceldefaultupdatestatementorvalidateincomingvalues.
$conn->event->attach("beforeUpdate",handlerFunc);
ParametershandlerFunc:
$action-DataActionObject
Availability:
AvailableforGrid,TreeGrid,Tree,Scheduler,DataView,Form
Sample:
//createsandrunsownupdatestatementusingvaluescameinrequest,cancelsdefaultupdate
functionmyUpdate($action){
mysql_query("UPDATECountriesSETitem_nm='{$action->get_value('name')}'WHEREitem_id='{$action->get_id()}'"
$action->success();
}
//or____________________________________________________________________________________________
//checksifvalueofnameisempty,thencancelupdate.Otherwise,proceedswithdefaultupdate.
functionmyUpdate($action){
if($action->get_value("name")=="")
$action->invalid();
}
//or____________________________________________________________________________________________
//setsnewvaluefornameandproceedswithdefaultupdate.
functionmyUpdate($action){
$new_value=rand(0,100);
$action->set_value("name",$new_value);
}
$conn->event->attach("beforeUpdate","myUpdate");
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
beforeInsertTheeventoccursbeforeinsertingvaluesintodatabaseandcancanceldefaultinsertstatementorvalidateincomingvalues.
$conn->event->attach("beforeInsert",handlerFunc);
ParametershandlerFunc:
$action-DataActionObject
Availability:
AvailableforGrid,TreeGrid,Tree,Scheduler,DataView,Form
Sample:
SeerelatedbeforeUpdatesample.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
beforeDeleteTheeventoccursbeforedeletingrecordindatabaseandcancanceldefaultdeletestatementorvalidateincomingvalues.
$conn->event->attach("beforeDelete",handlerFunc);
ParametershandlerFunc:
$action-DataActionObject
Availability:
AvailableforGrid,TreeGrid,Tree,Scheduler,DataView,Form
Sample:
SeerelatedbeforeUpdatesample.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
afterUpdateTheeventoccursafterupdatingvaluesindatabaseandcancanbeusedtopassadditionalvaluestoclient-side.
$conn->event->attach("afterUpdate",handlerFunc);
ParametershandlerFunc:
$action-DataActionObject
Availability:
AvailableforGrid,TreeGrid,Tree,Scheduler,DataView,Form
Sample:
SeerelatedafterProcessingsample.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
afterInsertTheeventoccursafterinsertingvaluesintodatabaseandcancanbeusedtopassadditionalvaluestoclient-side.
$conn->event->attach("afterInsert",handlerFunc);
ParametershandlerFunc:
$action-DataActionObject
Availability:
AvailableforGrid,TreeGrid,Tree,Scheduler,DataView,Form
Sample:
SeerelatedafterProcessingsample.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
afterDeleteTheeventoccursafterdeletingrecordindatabaseandcanbeusedtopassadditionalvaluestoclient-side.
$conn->event->attach("afterDelete",handlerFunc);
ParametershandlerFunc:
$action-DataActionObject
Availability:
AvailableforGrid,TreeGrid,Tree,Scheduler,DataView,Form
Sample:SeerelatedafterProcessingsample.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
beforeProcessingTheeventoccursbeforebeforeInsert,beforeUpdate,beforeDeleteeventsoccurandrelatestoalloperations:Insert,UpdateandDelete.Itcanbecancelledinthesamewayastheaforementionedevents.
$conn->event->attach("beforeProcessing",handlerFunc);
ParametershandlerFunc:
$action-DataActionObject
Availability:
AvailableforGrid,TreeGrid,Tree,Scheduler,DataView,Form
Sample:SeerelatedbeforeUpdatesample.
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
afterProcessingTheeventoccursafterbeforeInsert,beforeUpdate,beforeDeleteeventsoccurandrelatestoalloperations:Insert,UpdateandDelete.Itcanbeusedtopassadditionalvaluestoclientside.
$conn->event->attach("afterProcessing",handlerFunc);
ParametershandlerFunc:
$action-DataActionObject
Availability:
AvailableforGrid,TreeGrid,Tree,Scheduler,DataView,Form
Sample:
//addsnewxmlasachildofdefault<action>tagwhichispassedtoclientsideasresponse
functiondoAfterProcessing($action){
$action->set_response_xml("<guid>somevalue</guid>")
}
$conn->event->attach("afterProcessing",doAfterProcessing);
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
onDBErrorTheeventoccurswhensomeDBlevelerroroccurs,duringdatasavingoperations.Itisrelatestoalloperations:Insert,UpdateandDelete.Itcanbeusedtopasserrorinfototheclientside.
$conn->event->attach("onDBError",handlerFunc);
ParametershandlerFunc:
$action-DataActionObject$exception-SQLrelatedexceptionobject
Availability:
AvailableforGrid,TreeGrid,Tree,Scheduler,DataView,Form
Sample:
//addsnewxmlasachildofdefault<action>tagwhichispassedtoclientsideasresponse
functiondoOnDBError($action,$exception){
$action->set_response_xml("<errorinfo>".((String)$exception
}
$conn->event->attach("onDBError",doOnDBError);
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
SamplesClient-sideinitializationofcomponentsServer-sideinitializationofcomponentsDefininggridstructureonserver-sidedhtmlxConnectorforgrid(includingfiltration,sorting,formatting)dhtmlxConnectorforform
grid
myGrid=newdhtmlXGridObject("myContainer");
//...gridconfigurationcommands
myGrid.load("myconnector.php");
treeGrid
staticmode
myGrid=newdhtmlXGridObject("myContainer");
myGrid.setColTypes("tree,...");
//...gridconfigurationcommands
myGrid.loadXML("myconnector.php");
dynamicmode
myGrid=newdhtmlXGridObject('myContainer');
myGrid.setColTypes("tree,...");
//...
myGrid.kidsXmlFile="connector.php";
myGrid.loadXML("connector.php");
tree
staticmode
tree=newdhtmlXTreeObject("treeboxbox_tree","100%","100%",0)
//...
tree.loadXML("connector.php");
dynamicmode
tree=newdhtmlXTreeObject("treeboxbox_tree","100%","100%",0)
//...
tree.setXMLAutoLoading("connector.php");
tree.loadXML("connector.php");
combo
staticmode
varcombo=newdhtmlXCombo("combo_zone2","alfa2",200);
combo.loadXML("connector.php");
auto-completemode
varcombo=newdhtmlXCombo("combo_zone2","alfa2",200);
combo.enableFilteringMode(true,"connector.php",true);
combo.loadXML("connector.php");
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
dataStore
varmyDataStore=newdhtmlXDataStore();
myDataStore.load("connector.php");
dbtypes
MySQL(php_mysql)
require("connector/grid_connector.php");
$res=mysql_connect("localhost","root","");
mysql_select_db("myDatabase");
$gridConn=newGridConnector($res,"MySQL");
MySQLi(php_mysqli)
require("connector/grid_connector.php");
require("connector/db_mysqli.php");
$mysqli=newmysqli($server,$user,$pass,$mysql_db);
$gridConn=newGridConnector($mysqli,"MySQLi");
SQLite(php_sqlite)
require("connector/grid_connector.php");
require("connector/db_sqlite.php");
if(!$db=sqlite_open('db',0777,$sqliteerror)){
die($sqliteerror);
}
$gridConn=newGridConnector($db,"SQLite");
PostgreSQL(php_pg)
require("connector/grid_connector.php");
require("connector/db_postgre.php");
$res=pg_connect("host=localhostport=5432dbname=mary");
$gridConn=newGridConnector($res,"Postgre");
Oracle(php_oci)
require("connector/grid_connector.php");
require("connector/db_oracle.php");
$res=oci_connect("scott","tiger",$db);
$gridConn=newGridConnector($res,"Oracle");
MSSQL(php_mssql)
require("connector/grid_connector.php");
require("connector/db_mssql.php");
$res=mssql_connect('.\SQLEXPRESS',"sa","1",false);
mssql_select_db("sampleDB");
$gridConn=newGridConnector($res,"MsSQL");
MSSQL(php_sqlsrv)
require("connector/grid_connector.php");
require("connector/db_sqlsrv.php");
$conn=sqlsrv_connect($serverName,$connectionInfo);
$gridConn=newGridConnector($conn,"SQLSrv");
PDO(php_pdo)
require("connector/grid_connector.php");
require("connector/db_pdo.php");
$res=newPDO('mysql:host=localhost;dbname=test',$user,$pass
$gridConn=newGridConnector($res,"PDO");
FileSystem
require("connector/grid_connector.php");
require("connector/db_pdo.php");
$gridConn=newGridConnector("/var/www/test","FileSystem");
$grid->render_table("./","id","A,B,C,D,E,F");
Excelfile
require("connector/grid_connector.php");
require("connector/db_excel.php");
$res=newPDO('mysql:host=localhost;dbname=test',$user,$pass
$grid=newGridConnector("some.xls","ExcelDBDataWrapper");
$grid->render_table("A18:F83","id","A,B,C,D,E,F");
Componenttypes
Forothercomponentssyntaxofconstructorexactlythesame,except,the“Grid”inobjectnamereplacedwithcomponent'sname
Grid
require("connector/grid_connector.php");
//...
$gridConn=newGridConnector($res,"MySQL");
TreeGrid
require("connector/treegrid_connector.php");
//...
$treeGridConn=newTreeGridConnector($res,"MySQL");
Tree
require("connector/tree_connector.php");
//...
$treeConn=newTreeConnector($res,"MySQL");
Combo
require("connector/combo_connector.php");
//...
$comboConn=newComboConnector($res,"MySQL");
Scheduler
require("connector/scheduler_connector.php");
//...
$schedulerConn=newSchedulerConnector($res,"MySQL");
Form
require("connector/form_connector.php");
//...
$formConn=newFormConnector($res,"MySQL");
DataView
require("connector/dataview_connector.php");
//...
$dataConn=newDataViewConnector($res,"MySQL");
Chart
require("connector/chart_connector.php");
//...
$chartConn=newChartConnector($res,"MySQL");
DataStore
require_once("../../connector/data_connector.php");
require_once("../../connector/db_sqlite.php");
if(!$db=sqlite_open('db',0777,$sqliteerror)){
die($sqliteerror);
}
$storeConn=newJSONDataConnector($db,"SQLite");
DHTMLXTouchComponents
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
require_once("../../connector/data_connector.php");
require_once("../../connector/db_sqlite.php");
if(!$db=sqlite_open('db',0777,$sqliteerror)){
die($sqliteerror);
}
$touchConn=newJSONDataConnector($db,"SQLite");
client-side
index.html
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<scriptsrc="codebase/dhtmlx.js"type="text/javascript"></script>
<scriptsrc="codebase/connector/connector.js"></script>
<linkrel="STYLESHEET"type="text/css"href="codebase/dhtmlx.css">
<divid="gridbox"style="width:350px;height:250px";border:1pxsolid#A4BED4;></div>
<scripttype="text/javascript">
functiondoOnLoad(){
varmygrid=newdhtmlXGridObject('gridbox');
mygrid.setImagePath("codebase/imgs/");
mygrid.setSkin("dhx_skyblue");
mygrid.load("griddata.php");
}
</script>
</head>
<bodyonload="doOnLoad()">
</body>
</html>
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
server-side
griddata.php
<?php
require_once("../codebase/connector/grid_config.php");
require_once("../codebase/connector/grid_connector.php");
$res=mysql_connect("localhost","root","");
mysql_select_db("tasks");
$conn=newGridConnector($res);
$config=newGridConfiguration();
$config->setHeader("ItemName,ItemCD");
$config->attachHeader("ItemNameTest,#rspan");
$config->attachFooter("ItemName,ItemCD",Array("background:#ff0000;"
$config->attachFooter("ItemNameTest,#rspan","background:#0000ff;color:white;"
$config->setColIds("col1,col2");
$config->setInitWidths('120,*');
$config->setColSorting("connector,connector");
$config->setColColor("null,#dddddd");
$config->setColHidden("false,false");
$config->setColTypes("ro,ed");
$config->setColAlign('center,center');
$conn->set_config($config);
$conn->render_table("grid50000","id","item_nm,item_cd");
?>
client-side
index.html
<!DOCTYPEhtml>
<head>
<scriptsrc="codebase/dhtmlx.js"type="text/javascript"></script>
<scriptsrc="codebase/connector/connector.js"></script>
<scriptsrc="codebase/connector/dataprocessor.js"></script>
<linkrel="STYLESHEET"type="text/css"href="codebase/dhtmlx.css">
<divid="gridbox"style="width:450px;height:250px";border:1pxsolid#A4BED4;></div>
<scripttype="text/javascript">
varmygrid,myDP;
functiondoOnLoad(){
mygrid=newdhtmlXGridObject('gridbox');
mygrid.setImagePath("codebase/imgs/");
mygrid.setHeader("Name,Category,Ingredients");
mygrid.attachHeader("#connector_text_filter,#connector_select_filter,#connector_select_filter"
mygrid.setInitWidths("200,80,*");
mygrid.setColTypes("ro,ed,ed");
mygrid.setColSorting("str,connector,str");
mygrid.init();
mygrid.load("xml/griddata.php");
myDP=newdataProcessor("xml/griddata.php");
myDP.init(mygrid);
}
</script>
</head>
<bodyonload="doOnLoad()">
</body>
</html>
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
server-side
griddata.php
<?php
require_once("../codebase/connector/grid_connector.php");
$res=mysql_connect("localhost","root","");
mysql_select_db("tasks");
$conn=newGridConnector($res);
$conn->enable_log("temp.log");
functioncustom_sort($sorted_by){
if(!sizeof($sorted_by->rules))
$sorted_by->add("group","DESC");
}
functionformatting($row){
//renderfieldasdetailslink
if($row->get_value("vegetarian"
$row->set_value("name"
}
functionvalidate($data){
if($data->get_value("group")=="")
$data->error();
}
$conn->event->attach("beforeProcessing","validate");
$conn->event->attach("beforeSort","custom_sort");
$conn->event->attach("beforeRender","formatting");
$conn->render_table("meals","id","name,group,ingredients",
?>
dhtmlxConnectorforform
index.html
<!DOCTYPEHTML>
<html>
<head>
<linkrel="STYLESHEET"type="text/css"href="../codebase/dhtmlx.css">
<scriptsrc="../codebase/dhtmlx.js"></script>
<scripttype="text/javascript"src="../codebase/connector.js"></script>
<divid="box"style="width:250px;height:160px;background-color:white;"></div>
</head>
<body>
<scripttype="text/javascript">
//---formconfiguration.Definingcontrols
formData=[
{type:"block",list:[
{type:"fieldset",name:"mydata"
{type:"input",name
{type:"input",name
{type:"input",name
{type:"button",name
]}]},
{type:"block",list:[
{type:"button",name:"button1"
{type:"newcolumn"},
{type:"button",name:"button2"
];
Copyright©1998-2011DHTMLXLTD.Allrightsreserved.
//---forminitialization
varmyForm=newdhtmlXForm("box",formData);//objectconstructor
//---loadingdatafromdb.
myForm.load('formdata.php?id=1');//astheparameterisaconnectorfilewiththeidofloadingrecord
//---dataProcessorinitialization
varmydp=newdataProcessor("formdata.php");//objectconstructor.Hereyoushouldspecifyaconnectorfile
mydp.init(myForm);//initializesdataProcessor.Astheparameteryoushouldspecifyyourgrid
myForm.attachEvent("onButtonClick",function(id){
if(id=='button1'){//
myForm.load('formdata.php?id=1'
}
elseif(id=='button2'){
myForm.load('formdata.php?id=2'
}
elseif(id=='save'){
myForm.save();//savesdatatodb
}
});
</script>
</body>
</html>
formdata.php
<?php
require_once("../codebase/connector/form_connector.php");
$res=mysql_connect("localhost","root","");
mysql_select_db("tasks");
$conn=newFormConnector($res,"MySQL");
$conn->render_table("customers","id","name,address,email"
?>