xCRUD v.1.6 - Documentation and code examples

# xCRUD v.1.6

## Documentation and code examples

- created: 10/13/2012
- latest update: 04/07/2014
- by: f0ska
- xcrud.com/
- email: lostfader@yahoo.com

xCRUD - is a simple-usage but powerful Create-Read-Update-Delete application for php and MySQL.

### 1. Basic configuration and quick start

Upload the folder with application to your local or remote server (by default, it is called "xcrud"). No matter how it will be named later, and where it will be located.

Important: Do not renaming anything in the application folder!

Now you need to configure the default connection to the database and set the URL to the application folder.
The configuration file is located in the application folder and is called Xcrud_config.php. This file contains all the basic settings, most of which you can change directly in the application initialization. More information about this you can read in the following sections of this documentation.

    class Xcrud_config{
        // default connection
        public static $dbname = 'dbname';
        public static $dbuser = 'dbuser';
        public static $dbpass = 'dbpass';
        public static $dbhost = 'localhost';
        ....
    // more settings here... :)

When everything is set up, you can try to include the main application file, and create a new instance of the application.

    include('real_path/xcrud/xcrud.php');
    $xcrud = Xcrud::get_instance();
    $xcrud->table('my_table');
    echo $xcrud->render();

That's it. If done correctly, you should see your table.

Note: If you start with blank file, your result code must look like this

    <?php
        include('xcrud/xcrud.php');
        $xcrud = Xcrud::get_instance();
        $xcrud->table('your_table');
    ?>
    <!DOCTYPE HTML>
    <html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Some page title</title>
    </head>

    <body>

    <?php
        echo $xcrud->render();
    ?>

    </body>
    </html>

I highly recommend to use UTF-8 in your projects. This will save you from a lot of problems with the encoding and localizations.

### 2. Advanced Configuration

The configuration file contains default settings, you can customize the behavior xCRUD to your taste. The configuration file is well commented, you should not have any problems with the editing.

### 3. Main features of the application.

xCRUD – is a simple-usage but powerfull Create-Read-Update-Delete (CRUD) generator application for PHP and MySQL. The application offers you many ways to work with your data and scaffolding, while remaining very easy to use even for non-programmers. Content management becomes simple and flexible, hours of saved time, minutes to implement. You can use it as plain php library or with your favorite framework and cms.

xCRUD implements Singleton pattern, so it can be initialized in any part of the script as desired. It will not appear on the performance, because you will always work with a single original object xCRUD. You can pre-set parameters and output data in different parts of your script: in different functions, classes, or even in different files. This way, you can create custom settings for your specific set xCRUD (first, read the configuration file, most of the default settings can be done there).

xCRUD implements multi-instance system, which allows a single page load multiple instances xCRUD and work with multiple tables simultaneously. Regardless on how many copies, xCRUD open only one connection to your database, which is also significantly improves performance gains.

You can connect every instance to different database and work not only with different tables on the page, but also with multiple databases even on one page.

The application uses a fast ajax interface for all of your actions, you do not need to wait for page reloading and loading unneeded modules, you get access to the data almost immediately.

xCRUD uses native php session. For each request, each instance is generating unique validation key that becomes invalid immediately after usage, which ensures a secure, as well as ease and independence ajax-side of the application. Also you can use experimental alternative session, but for this you need mcrypt and memcache(d) modules installed on your server.

xCRUD supports all popular types of MySQL fields. Also, you can control the display of your fields, establish simple validation rules. xCRUD enables working with visual editor for text fields, date- and time-picker for date fields, automatically generates a drop-down lists for the fields of ENUM and SET. xCRUD will generate interactive google map for POINT type.

You can use any text editor for textarea field. xCRUD has preinstalled configs for TinyMCE and CKEditor.

xCRUD supports file and image uploading, unlimited thumbs creation and resizing. Blob storage is also available.

xCRUD provides control over your data. You can change the data directly to the entry through the callback function, and get the data immediately after writing to the database (eg for password hashing or creation (updating) data in other tables. You can create callbacks for most general actions.

You can completely change the look xCRUD, editing just one small css file. You can easy create your own themes or just different screens (templates) for some actions in same template.

xCRUD supports localization via ini files, so you can easy create your unique language file.

### 4. The main methods and loading xCRUD

get_instance () - returns the main object xCRUD. This is a static method and can be called anywhere, indefinitely.

    $xcrud = Xcrud::get_instance();

You can create multiple instances of xCRUD on one page (for example, to work with multiple tables):

    $xcrud1 = Xcrud::get_instance();
    $xcrud2 = Xcrud::get_instance();

Next, for each instance you can use different methods.

If you want to get the same instance in different functions/file (for expample, in controller an view), you must specify instance name. Calling an instance by name you will always get the same instance. Example:

    // controller.php
    $xcrud = Xcrud::get_instance('MyInstance');
    $xcrud->table('users');

    // view.php
    $xcrud = Xcrud::get_instance('MyInstance');
    $echo xcrud->render();

table ( table_name ) - sets the table from which data will be loaded. Takes the name of the table in the first parameter. This method is mandatory.

    $xcrud->table('my_table');

You can also load a table from another database.

Most of methods requiring table, try to define this first of all.

Xcrud needs at least one primary or unique field in your table. If not, you will get an error. The best practice is to use primary autoincrement column in every table. This was done to prevent losing of your data. Xcrud can't work with complex (combined) primary index.

connection ( username, password, remote_table, [localhost], [utf-8] ) - creates a connection for the current instance xCRUD. Takes a user name, password, table, host, and the connection character. Host and encoding optional and defaults to 'localhost' and 'utf-8', respectively.

    $xcrud2->connection('username','password','remote_table','localhost','utf-8');

This method is rewriting connection settings from configuration file for current instance

language( lang_code ) - sets interface language in first parameter, default is 'en'

    $xcrud->language('en'); // will load en.ini lang file from languages folder

The best way is set language in configuration file. Use this method only if you really need dynamic language switching.

set_lang( lang_var, translate ) - allows you to replace existing translate in current instance.

Note: the best way is to customize lang file. Do not create new variables with set_lang(), put them in language file.

render () - displays your data. While this method is not called, xCRUD takes no action, the database is not connected, this saving system resources (especially critical for large data).

    $out = $xcrud->render();
    // some code...
    echo $out;
    // or
    echo $xcrud->render();
    // or
    echo $xcrud;

You can start xcrud not only from grid (by default), and always from create, edit or details screen:

    $xcrud->render('create'); // add entry screen
    $xcrud->render('edit', 12); // edit entry screen, '12' - primary key
    $xcrud->render('view', 85); // view entry screen, '85' - primary key

Remember that the render () method must be called last, it just returns the data for output, and all the methods declared after (for the current instance) will not be applied.

### 5. Compatibility and plug-ins.

Configuration tricks

You can rewrite config settings from 'scripts' and 'editor' sections directly on your page. This will be affected on all instances on page. You can use it when you need dynamically change some parameter from that sections.

Example:

    Xcrud_config::$some_parameter = 'some value';

You must write this after you included xcrud.php file and before render() method. All parameters and description you can find in configuration file (xcrud_config.php)

load_css() - Static method. Allow you to load xcrud's css files at you custom place. By default xcrud loads styles before instance output

    echo Xcrud::load_css();

load_js() - Static method. Allow you to load xcrud's javascript files and scripts at you custom place. By default xcrud loads javascript after instance output

    echo Xcrud::load_js();

#### Bootstrap, jQuery and javascript conflicts

If your template already uses jquery or jqueryui or bootstrap, you must turn off them in configuration file.

Note, all xCRUD's scripts must be loaded after jQuery. If your jQuery loads in the bottom of page, you must call <?php echo Xcrud::load_js() ?> in the bottom of page after jQuery and <?php echo Xcrud::load_css() ?> in top (the best in <head></head>).

If xCRUD's content rendered before output in template, set $manual_load parameter in TRUE in configuration file. This will prevent automatic loading scripts and styles.

#### Troubles with session

Many frameworks and cms can destoy native php session on reload. xCRUD generates Security key error to any action. If this was happenned, you can try to use alternative session (you need memcache(d) and mcrypt modules on your server).

Also you will get an error when session name was changed from default. And you can try to customize $sess_name or $dynamic_session parameters in configuration.

If you have deep integration with your framework or cms (this mean, the xcrud's ajax file (uri) is a part of your system), you can use special functions to synhronize xcrud's session with yours. Codegniter example:

Ajax controller:

    class Ajax extends CI_Controller{
        public function __construct(){
            parent::__construct();
        }
        public function index(){
            include(FCPATH.'/xcrud/xcrud.php');
            Xcrud::import_session($this->session->userdata('xcrud_sess'));
            Xcrud::get_requested_instance();
            $this->session->set_userdata(array('xcrud_sess'=>Xcrud::export_session()));
        }
    }

Some content controller:

    class Ajax extends CI_Controller{
        public function __construct(){
            parent::__construct();
        }
        public function orders(){
            include(FCPATH.'/xcrud/xcrud.php');
            $xcrud = Xcrud::get_instance();
            $xcrud->table('orders');
            $data['content'] = $xcrud->render();
            $this->load->view('some_content', $data);

            // Xcrud::export_session() will destroy all xcrud's instances
            $this->session->set_userdata(array('xcrud_sess'=>Xcrud::export_session()));
        }
    }

### 6. Select Data.

where ( fields, value ) - sets the condition of choice.
Multiple calls are united all the conditions with the operator 'AND'.
Option 1: Accept the input field and value. The field should be indicated by a sign of comparison. Value will be automatically quoted.

    $xcrud->where('catid =', 5);
    $xcrud->where('created >', $last_visit);
    // or
    $xcrud->where('catid =', 5)->where('created >', $last_visit);

Option 2: Accepts associations are an array of field-value. The field should be indicated by a sign of comparison. Value will be automatically quoted.

    $cond = array('catid =' => 5, 'created >' => $last_visit);
    $xcrud->where($cond);

Please note: all the conditions in array will be merged with the operator 'AND'.

Option 3: Accepts custom line environment, you must specify the name of the table in front of each field, to avoid any conflict in relationships with other tables. You also have to take care of yourself on preparing values.

    $xcrud->where("content.catid = 5 AND content.created > '{$last_visit}'");
    // or
    $xcrud->where("", "content.catid = 5 AND content.created > '{$last_visit}'"); // 1.5 compat.

Alternative usage

    // using OR glue
    $xcrud->where('catid', 5);
    $xcrud->or_where('created >', $last_visit);

    // using IN and NOT IN
    $xcrud->where('catid', array('5','7','8'); // `catid` IN ('5','7','8')
    $xcrud->where('catid !', array('5','7','8'); // `catid` NOT IN ('5','7','8')

or_where() - the same as where() method, but multiple calls will be united with operator 'OR'

no_quotes( fields ) - The method allows to cancel the automatic shielding values, so you can use the functions in mysql query. Affects on where expressions and pass_var () method. Takes comma-separated fieldnames or array of fieldnames in first parameter.

    $xcrud->no_quotes('created');
    $xcrud->pass_var('created','now()');
    //or
    $xcrud->where('created !=','null');

relation ( field, target_table,target_id, target_name, where, order_by, multi, concat_separator, tree, depend_field, depend_on ) - binds the current table with a list of the other table. Takes as input the name of the field in the current table, the name of the linked table, the link field, the title field , the selection condition for the linked table (optional).

    $xcrud->relation('catid','categories','cid','category_name',array('published' => 1));
    //or
    $xcrud->relation('catid','categories','cid','category_name','categories.published = 1');

Since 1.5.4 relation() has additional parameters:

relation ( field, target_table, target_id, target_name, where_array, main_table, multi, concat_separator, tree, depend_field, depend_on )

- field - main table relation field, that will be replases; data will be written in this field
- target_table - related (target) table, options for dropdown will be get from here
- target_id - row id from target table, will be writen into field
- target_name - field, that will be displayed as name of dropdown option. This can be array of few fields.
- where - (optional) - allows to specify selection items from the target_table, see where(). Default is null.
- order_by - (optional) - order by condition (eg. 'username desc'). Default is by target_name.
- multi - (optional, boolean) - can change dropdown to multiselect (items will be saved separated by comma). Default is false.
- concat_separator - (optional) - take effect only when target_name is array. Default is ' '.
- tree - (optional) - array, sets tree rendering of dropdown list. Options: 1. array('parent_key'=>'some_field_name') - parent key field name, will be created pk tree. 2. array('left_key'=>'some_field_name','level_key'=>'some_field_name') - left key and level field names, will be created nested sets tree.
- depend_field - field from current table, options will be extracted based on parent field value ( like country_id column in cities table)
- depend_on - field, thats will be parent to current dropdown.

You can use {field_tags} in 'where' parameter to get variable from current row

fk_relation(label, field, fk_table, in_fk_field, out_fk_field, rel_tbl, rel_field, rel_name, rel_where, rel_orderby, rel_concat_separator, before, add_data ) - allows to create, manage and display many-to-many connections. The syntax is similar to relation().

- label - Displaing field label (mus be unique, used as alias)
- field - connection field from current table
- fk_table - connection table
- in_fk_field - field, connected with main table
- out_fk_field - field, connected with relation table
- rel_tbl - relation table
- rel_field - connection field from relation table
- rel_name - field, that will be displayed as name of dropdown option. This can be array of few fields.
- rel_where - (optional) - allows to specify selection items from the target_table, see where(). Default is null.
- rel_orderby - (optional) - order by condition (eg. 'username desc'). Default is by rel_name.
- rel_concat_separator - (optional) - take effect only when rel_name is array. Default is ' '.
- before - (optional) - if selected, field will be inserted before this field (by default - in the end)
- add_data (array) - (optional) - additional inserting data

Structure of connections:

    table
    |- field  --|
                |
                |    fk_table
                |--  |- in_fk_field
                     |- out_fk_field  --|
                                        |
                                        |    rel_table
                                        |--  |- rel_field

nested_table ( inst_name, connect_field, nested_table, nested_connect_field ) - takes instance name in first parameter, main field in second parameter, nested table in third and connection field from nested table in 4th.

Nested tables are using for easy editing of related records in other tables, such as the order and the goods in the order (see demo).

You can specify one nested table for each field of your main table. You can set options for nested tables as well as you do for the main table. Method nested_table () creates an instance of a nested table, access to which can be obtained through the field name (specified in the first parameter of the method nested_table ()), only add to it the prefix nested_.

    $xcrud->table('orders'); // main table
    $products_list = $xcrud->nested_table('products_list','orderNumber','orderdetails','orderNumber'); // nested table
    $products_list->unset_add(); // nested table instance access

####

search_pattern( '%', '%' ) - allows to define search pattern for grid search. Method replaces default param ($search_pattern) from configuration.

#### Table joining

xCRUD provide table joining and manipulating with a few tables in one box. You can use extended field syntax, when you type field name (column name or alias) as table and field with dot separator (sample: $xcrud->change_type('order.total', 'price');). You no need to use this when you not use table joining.

join( field, joined_table, join_on_field [, alias] )

field - field from current table to join; joined_table - table, that is joined; join_on_field - joining on this column from joined table; alias - (optional) - need to use when you join one tabes more than one times.

    $xcrud->table('users');
    $xcrud->join('id','profiles','user_id'); // join users and profiles on users.id = profiles.user_id

    // now join 'profiles' and 'tokens' tables
    $xcrud->join('profiles.token_id','tokens','id'); // on profile.token_id = tokens.id

    // simple actions with fields: default and joined
    $xcrud->column('username','email','profile.city','tokens.created');

join uses INNER JOIN, thats mean in all tables must be present joined rows. join connects only one row from table, joined on fields must be unique. When joined rows in not unique xCRUD will be worked incorrect.

#### Custom SQL

query( sql_query ) - custom sql query. This method allow you to use custom sql query and display read-only datagrid.

    $xcrud = Xcrud::get_instance();
    $xcrud->query('SELECT * FROM users WHERE age > 25');
    echo $xcrud->render();

### 7. Overview table.

columns ( columns, reverse ) - sets the columns that you want to see in the review table. Takes a string, separated by commas, or an array of values. The second optional parameter causes the function to do the opposite, ie hides the selected columns. Takes tru / false, default false.

    $xcrud->columns('name,email,city');
    //or
    $xcrud->columns(array('name','email','city'));

    // hide columns
    $xcrud->columns('name,email,city', true);

order_by ( name, direction ) - sets the initial sorting of the table, take the field and sort order. By default - in ascending order ('asc').

    $xcrud->order_by('name','desc');

label ( fieldname, your_label ) - Allows you to specify the name of your columns and fields, takes the field and the field name or an array.

    $xcrud->label('name','Your Name');
    //or
    $xcrud->label(array('name' => 'Your Name'));

column_name( fieldname, your_label ) - the same as label(), but affects only on columns in grid.

show_primary_ai_column ( bool ) - takes true / false, setting the display of primary auto-increment columns in the overview table.

    $xcrud->show_primary_ai_column(true);

limit ( int ) - sets the initial limit for display tables, takes an integer in the first argument. The value set by this function is always available in the list to select the number of lines per page.

    $xcrud->limit(25);

limit_list ( string_or_array ) - specifies a list of values ​​for the limits list. Takes an array of values, or string. Option 'all' lift a moderate amount of a result (display all rows).

    $xcrud->limit_list('5,10,15,all');
    //or
    $xcrud->limit_list(array('5','10','15','all'));

table_name ( name, tooltip, tooltip_icon ) - Changes the name of the table in the title, takes a string as the first parameter, tooltip text in second parameter (optional) and tooltip icon name in 3rd (optional)

See 'default' theme icons

    $xcrud->table_name('My custom table!');
    $xcrud->table_name('My custom table!', 'Some tooltip text');
    $xcrud->table_name('My custom table!', 'Some tooltip text','icon-leaf');

unset_add( true ) - hides add button from list view.

    $xcrud->unset_add();

unset_edit( true ) - hide edit button from list view.

    $xcrud->unset_edit();

unset_view( true ) - hides view button from list view.

    $xcrud->unset_view();

unset_remove( true ) - hide remove button from list view.

    $xcrud->unset_remove();

unset_csv( true ) - hides csv-export button from list view.

    $xcrud->unset_csv();

unset_search( true ) - hides search feature.

    $xcrud->unset_search();

unset_print( true ) - hides printout feature.

    $xcrud->unset_print();

unset_title( true ) - hides table title.

    $xcrud->unset_title();

unset_numbers( true ) - hides rows numbers.

    $xcrud->unset_numbers();

unset_pagination( true ) - hides pagination

    $xcrud->unset_pagination();

unset_limitlist( true ) - hides list with limits buttons or dropdown

    $xcrud->unset_limitlist();

unset_sortable( true ) - makes columns unsortable

    $xcrud->unset_sortable();

unset_view(), unset_edit(), unset_remove(), duplicate_button() - this methods can get additional condition parameters (with {field_tags})

    $xcrud->unset_edit(true,'username','=','admin'); // 'admin' row can't be editable

remove_confirm( true ) - removes confirmation window on remove action. Takes true / false in the first parameter.

    $xcrud->remove_confirm(false);

start_minimized ( true ) - start xCRUD instance minimized. Takes true / false in the first parameter.

    $xcrud->start_minimized(true);

benchmark ( true ) - displays information about the performance in the lower right corner of the xCRUD window. Takes true / false in the first parameter.

    $xcrud->benchmark(true);

column_cut ( int, [fields] ) - sets the maximum number of characters to be displayed in columns. Takes an integer value in the first parameter. In the second parameter you can define target field(s)

    $xcrud->column_cut(30); // all columns
    $xcrud->column_cut(30,'title,description'); // separate columns

duplicate_button ( true ) - show duplicate button. You can duplicate only the records in those tables that have auto-incremental primary field, and have no other unique indexes. Otherwise you will get an error.

    $xcrud->duplicate_button();

links_label( label ) - creates label for links in grid view. Takes new label in first parameter

    $xcrud->links_label('home url');
    // or
    $xcrud->links_label('<i class="icon-home"></i>'); // bootstrap icon for bootstrap theme

emails_label( label ) - creates label for links in grid view. Takes new label in first parameter

    $xcrud->emails_label('Contact email');

sum ( columns, classname, custom_data ) - calculates sum for columns and shows result row in the bottom of table. Calculates sum of the entire list, regardless of pagination. Takes columns list in first parameter, optional classname in second, and optional custom text pattern in third.

    $xcrud->sum('price,fee,quantity');
    //or
    $xcrud->sum(array('price','fee','quantity'));
    //or
    $xcrud->sum('price','align-center','Total price is {value}'); // use {value} tag to get sum value in pattern

button( link, title, icon, classname, array_of_attributes, condition_array ) - adds custom link in grid, like edit or remove. You can define url in first parameter (required), name (optional) in 2nd, icon(optional) in 3rd, class attribute (optional) in 4th, additional button attributes (assoc array) as 5th.

For icon field you must use predefined classes, this is Icon glyphs for bootstrap theme (e.g. icon-glass, icon-music...). Also see 'default' theme icons for default theme.

    $xcrud->button('http://example.com');
    $xcrud->button('http://example.com','My Title','icon-link','',array('target'=>'_blank'));

    // {column_tags} usage:
    $xcrud->button('http://example.com/{user_id}/?token={user_token}');

You can use buttons with text labels. See $button_labels parameter in configuration file

Also button() supports simple condition in 6th parameter. Condition value supports {field_tags}. Example:

    // show button whith link from 'link' field when 'link' field is not empty
    $xcrud->button('{link}','userlink','link','','',array('link','!=',''));

highlight( field, operator, value, color, classname ) - adds background color or class attribute for grid cell based on user's condition.

    $xcrud->highlight('orderNumber','=','10101','red');
    $xcrud->highlight('orderNumber','>=','10113','#87FF6C');
    $xcrud->highlight('city','=','Madrid','','main-city'); // you can define class attribute

Also you can get value from current row using {field_tag}

    $xcrud->highlight('sum', '>', '{profit}', 'red');

highlight_row( field, operator, value, color, classname ) - the same as highlight(), but full row will be highlighted

column_class( column(s), classname ) - adds class atribute to column(s).

    $xcrud->column_class('price,sum,count', 'align-center');

Predefined classes: align-left, align-right, align-center, font-bold, font-italic, text-underline

subselect( column_name, query, before_column ) - select to other table with parameters. This will create new column and inserts it after last column in table, or before colum defined in 3rd parameter

    //subselect
    $xcrud->subselect('Order total','SELECT SUM(priceEach) FROM orderdetails WHERE orderNumber = {orderNumber}'); // insert as last column
    $xcrud->subselect('Products count','SELECT COUNT(*) FROM orderdetails WHERE orderNumber = {orderNumber}','status'); // insert this column before 'status' column

    // you can use order() and change_type() for this columns;
    $xcrud->change_type('Order total','price','',array('prefix'=>'$'));
    $xcrud->order_by('Products count');

Also you can operate with fields only in current row

    $xcrud->subselect('Sum','{price}*{qty}');

modal( field(s), icon ) - shows cell info in modal. See 'default' theme icons

    $xcrud->modal('customerName,customerDescription);
    $xcrud->modal('customerName', 'icon-user');
    $xcrud->modal(array('customerName'=>'icon-user'));

column_pattern(column_name, pattern_code) - replaces default column cell output by custom pattern. Pattern can contain {field_tags} and {value} tag (value of current column)

    $xcrud->column_pattern('username','My name is {value}');

Differense between {value} and {username} (see example): {username} will return raw value from current cell, but {value} will return full output if your field has some extra features (like image or formatted price)

field_tooltip( field(s), tooltip_text [, icon ] ) - creates tooltip icon for field label in create/edit/view mode. See 'default' theme icons

    $xcrud->field_tooltip('productName','Enter product name here');

column_tooltip( column(s), tooltip_text [, icon ] ) - creates tooltip icon for column label in create/edit/view mode. See 'default' theme icons

    $xcrud->field_tooltip('productName','Enter product name here');

search_columns( [ column(s) ] [, default_column ] ) - defines column list for search and default search column

    $xcrud->search_columns('productVendor,quantityInStock,buyPrice','quantityInStock');

buttons_position( position ) - changes position of grid buttons. Can be 'left', 'right' or 'none'. 'None' option will hide buttons, their features will be available (unlike of unset_ methods). Default is 'right' and can be changed in configuration file.

    $xcrud->buttons_position('left');

hide_button( button_name(s) ) - hides system or your custom button ( defined with render_button() method ). This not disables button feature (unlike of unset_ methods).

    $xcrud->hide_button('save_and_return');

Default system buttons are: view, edit, remove, duplicate, add, csv, print, save_new, save_edit, save_return, return.

column_width( column(s), width ) - sets width of xcrud columns manualy.

    $xcrud->column_width('description','65%');
    $xcrud->column_width('first_name,last_name','100px');

### 8. Create / Edit

fields ( field(s), reverse, tab_name, mode ) - the table fields that you want to see when you edit or create entries. Takes a string, separated by commas, or an array of values. The second optional parameter causes the function to do the opposite, ie hides the selected fields. Takes tru / false, default false.

    $xcrud->fields('name,email,city');
    //or
    $xcrud->fields(array('name','email','city'));
    // hide fields
    $xcrud->fields('name,email,city', true);

You can create tabs for some fields, just set tab name in 3rd parameter:

    $xcrud->fields('username,email', false, 'Account info');
    $xcrud->fields('country,city,sex,age', false, 'Personal');

Also you can use different columns for different actions (create, edit, view), set action in 4th parameter:

    $xcrud->fields('first_name,last_name,country', false, false, 'view');

You can play with combination of this parameters. Tabs is unaviable if second parameter is true.

show_primary_ai_field () - takes true / false, setting the display of primary auto-increment field when editing the entry.

    $xcrud->show_primary_ai_field(true);

Primary auto-increment field will be always disabled.

readonly ( field(s), mode ) - Sets the selected fields attribute 'readonly'. Takes a string, separated by commas, or an array of values. Second paremeter sets mode (create, edit), default is all.

    $xcrud->readonly('name,email,city');
    //or
    $xcrud->readonly(array('name','email','city'));

disabled ( field(s), mode ) - Sets the selected fields attribute 'disabled'. Takes a string, separated by commas, or an array of values. Second paremeter sets mode (create, edit), default is all.

    $xcrud->disabled('name,email,city');
    //or
    $xcrud->disabled(array('name','email','city'));

    // separate screens
    $xcrud->disabled('email','edit');

readonly_on_create (), readonly_on_edit (), disabled_on_create (), disabled_on_edit () - do the same thing as the methods above, but allow you to separate the creation and editing. This methods are deprecated and will be deleted.

no_editor ( field(s) ) - allows you to load a text box without an editor (it has an effect when editor is loaded). Takes a string, separated by commas, or an array of values.

    $xcrud->no_editor('name,email,city');
    //or
    $xcrud->no_editor(array('name','email','city'));

change_type ( field(s), type, default, params_or_attr ) - Allows you to change the visual representation of the field. Takes the name of the field, a new type, default value, and an additional parameter (a set of values ​​for lists or the length of the field for the text boxes). Available field types: bool, int, float, text, textarea, texteditor, date, datetime, timestamp, time, year, select, multiselect, password, hidden, file, image, point.

    $xcrud->change_type('last_visit','timestamp');
    $xcrud->change_type('nickname','text','',20);
    $xcrud->change_type('email','multiselect','email2@ex.com','email1@ex.com,email2@ex.com,email3@ex.com,email4@ex.com,email5@ex.com');

See more about change_type () in Field types section.

Hidden type will add hidden input in form. Use fields() and pass_var() metods to hide fields and put custom data in your table if you need to preserve your data (pass_var will not add any input).

pass_var ( field, value, mode ) - Allows you to record a variable or data directly in the database, bypassing the add / edit form. The field may not be present in the field, edit field will not affect your data. Function takes the name of the field in the first parameter, and your data, or variable in the second. Optional third parameter is available that allows you to clearly define where you want to paste the data - when creating or editing.

    $xcrud->pass_var('user_id', $user_id);
    $xcrud->pass_var('created', date('Y-m-d H:i:s'), 'create');
    $xcrud->pass_var('was_edited', 'Yes, it was!', 'edit');

    //using field from current row
    $xcrud->pass_var('modified', '{last_action}');

pass_default( field, value ) - pass default value into field, takes the name of the field and default value, or array in first parameter.

    $xcrud->pass_default('name','Joe');
    //or
    $xcrud->pass_default(array('name' => 'Joe', 'city' => 'Boston'));

condition ( field, operator, value, method, parameter(s) ) - allows you to make some changes based on the data in the form. Takes field in first parameter, operator in second, value in 3rd, in the fourth - the method that is executed when triggered conditions, and in the fifth - the parameter passed to the method. Supported methods: readonly(), readonly_on_create(), readonly_on_edit(), disabled(), disabled_on_create(), disabled_on_edit(), no_editor(), validation_required(), validation_pattern(). Supported operators: =, >, <, >=, <=, !=, ^=, $=, ~=.

    $xcrud->condition('access','<','5','disabled','password,email,username');
    // if access < 5 than make password, email and username not editable
    // or
    $xcrud->condition('access','<','5','validation_pattern',array('username','[0-9A-Za-z]+'));

^= - starts with, $= - ends with, ~= - contains.

validation_required ( field(s), chars ) - a simple rule that takes the name of the field and the number of characters (default - 1) or an array.

    $xcrud->validation_required('name');
    $xcrud->validation_required('city',3);
    //or
    $xcrud->validation_required(array('name' => 1, 'city' => 3));

validation_pattern ( field(s), pattren ) - uses a simple validation pattern to selected fields. Takes the field name and the name of the pattern or array. Available patterns: email, alpha, alpha_numeric, alpha_dash, numeric, integer, decimal, natural. Also you can use your own regular expression in second parameter.

    $xcrud->validation_pattern('name', 'alpha');
    $xcrud->validation_pattern('email', 'email');
    //or
    $xcrud->validation_pattern(array('name' => 'alpha', 'email' => 'email'));
    // or
    $xcrud->validation_pattern('username', '[a-zA-Z]{3,14}');

alert( email_field, cc, subject, body, link ), alert_edit(...), alert_creale(...) - sends emails when data was changed: on create, update or both. Takes email from entry (you must define column in first parameter) and carbon copy list (if defined) from second parameter(can be comma-separated string or array). You must define subject in 3rd and email body in 4th parameter. You can define additional link for email in 5th parameter (optional).

In message body you can use simple tags to retrive some values from row, just write column name in {}.

    $xcrud->alert('email','admin@example.com','Password changed','Your new password is {password}');
    $xcrud->alert_create('email','','Email Testing','Hello!!!!!');

mass_alert(), mass_alert_edit(), mass_alert_create() - the same like alert(), but it send message to all emails from selected table.

mass_alert(email_table,email_column,email_where,subject,message,link,curent_param,param_value)

    $xcrud->mass_alert('user','email','subscribe = 1','Email test','Hello!');

page_call(url, data_array, param, param_value, method), page_call_create(...), page_call_edit(...) - sends http query to another file/page. This method not receive any data. It only sends request when row was added or changed.

You can define any data into data_array, including {field_tags}, this data will be received in target page like $_GET or $_POST array. If param is defined, method will run only if field value from current row (param) will be equal to param_value. Method defines type of request (get or post), default is get.

    $xcrud->page_call('http://mysite/admin/mytarget.php', array('id'=>'{user_id}','text'=>'User {user_name} here!'));

If your site using authorization, you can try to send browser cookie with request. This featue is experimental and can be turn on from configuration file. BE CAREFUL: DON'T USE IT FOR REQUESTS TO EXTERNAL SITES!!!

set_attr( field(s), array attr ) - allows to set custom attributes for fields in edit form. field(s) - form field(s), attr - assoc array with attributes.

    $xcrud->set_attr('user',array('id'=>'user','data-role'=>'admin'));

### 9. Field types

Function change_type () a little difficult to understand, because it uses a specific syntax, which varies depending on the task. Let's try to beat these tasks for conventional groups.

The first three parameters are always the same. They take the name of the field, the desired type of field and default value. The third and the fourth parameter is not required. If you do not specify them, ​​will be loaded values by default.

4th parameter - array with type-parameters and/or html attributes. You can use custom html attributes in most of types.

#### 1. Text fields.

This group includes the following types of fields: text, int, float, hidden.

For these types the function of the default value in the third parameter, and the maximum number of characters in the fourth parameter (exclude hidden).

    $xcrud->change_type('user_code', 'int', '000', 10); // v1.5 legacy
    $xcrud->change_type('user_code', 'int', '000', array('maxlength'=>10)); // v1.6

Use fields() and pass_var() metods to hide fields and put custom data in your table.

#### 2. Multi-line text fields.

This group includes the following types of fields: textarea, texteditor.

This types no need any additional parameters.

    $xcrud->change_type('user_desc', 'textarea');

#### 3. Date fields.

This group includes the following types of fields: date, datetime, time, year, timestamp.

These types of fields will only accept the default value in the third parameter.

    $xcrud->change_type('created', 'datetime', '2012-10-22 07:01:33');

Date range can be used with date type:

    $xcrud->change_type('created', 'date', '', array('range_end'=>'end_date')); // this is start date field and it points to end date field
    $xcrud->change_type('created', 'date', '', array('range_start'=>'start_date')); // this is end of range date and it points to the start date range date

This will create relation between two date fields.

#### 4. Lists.

This group includes the following types of fields: select, multiselect, radio, checkboxes

These types of fields are set to default in the third argument, and a list of available values, separated by commas, in the second parameter. multiselect can contain several values ​​by default.

    $xcrud->change_type('adm_email','select','email2@ex.com','email1@ex.com,email2@ex.com,email3@ex.com,email4@ex.com,email5@ex.com');
    $xcrud->change_type('fav_color','multiselect','black,white','red,blue,yellow,green,black,white');

    // v1.6 new syntax
    $xcrud->change_type('fav_color','multiselect','black,white', array('values'=>'red,blue,yellow,green,black,white'));

You can show optgroups in dropdowns. Just us multidimensional array:

    $xcrud->change_type('country','select','',array('values'=>array('Europe'=>array('UK'=>'United Kindom','FR'=>'France'),'Asia'=>array('RU'=>'Russia','CH'=>'China'))));

#### 5. Password.

This group includes the following types of fields: password.

Takes the type of hashing in the third parameter (e.g. md5 or sha1 or sha256... , leave blank if you do not want to use hashing) and the maximum number of characters in the fourth. The peculiarity of this field is that it does not load the values ​​and does not store the null value (not allowing you to change the previous one to null). This is due to the fact that passwords are usually encrypted or hashed before being stored in the database.

    $xcrud->change_type('user_key', 'password', '', 32);
    $xcrud->change_type('user_pass', 'password', 'sha256', 8);
    // attributes example
    $xcrud->change_type('user_pass', 'password', 'md5', array('maxlength'=>10,'placeholder'=>'enter password'));

#### 6. Upload.

This group includes the following types of fields: file, image.

Takes the path to the upload folder (must exist and be writable) in the third parameter and configuration array in the fourth.

For all uploaded files xCRUD creates a unique name to avoid overwriting, but you can cancel the renaming. In this case, the file name will be brought to the alpha-numeric pattern.

    $xcrud->change_type('attach', 'file', '', array('not_rename'=>true));

You can resize the uploaded image, and crop them at different proportions.

    $xcrud->change_type('photo','image','',array('width'=>300)); // resize main image
    $xcrud->change_type('photo','image','',array('width'=>300, 'height'=>300, 'crop'=>true)); // auto-crop
    $xcrud->change_type('photo','image','',array('manual_crop'=>true)); // crop it as you want

You can create a preview picture for your image to be stored in that same folder, and a marker will differ at the end of the name. You can also specify the size of thumbnails, resize method and subfolder.

Note: 'Manual crop' will crop thumbnails in same proportion as main image

You can add any number of thumbs, you must create subarray in thumbs array for each thumbnail

    $xcrud->change_type('photo','image','',array(
        'thumbs'=>array(
            array('width'=> 50, 'marker'=>'_small'),
            array('width'=> 100, 'marker'=>'_middle'),
            array('width' => 150, 'folder' => 'thumbs' // using 'thumbs' subfolder
        )
    ));

You can save your image as a binary string in the database. For this field in your database must be of type BLOB, MEDIUMBLOB or LONGBLOB. Thumbnail creation in this case is not available. If you do not know how to extract data from these fields, it is better use the normal load.

    $xcrud->change_type('photo','image','',array('blob'=>true));

Uploads parameters:

Files:

- not_rename - (true/false) - disables auto-renaming of uploaded files
- text - (string) - replaces text in list view to custom
- path - relative or absolute path to uploads folder
- blob - (true/false) - saves image as binary string in database blob field
- filename - (string) - name of downloadable file

Images:

- not_rename - (true/false) - disables auto-renaming of uploaded files
- path - relative or absolute path to uploads folder
- width, height - (integer) - sets dimensions for image, if both is not set image will not been resized
- crop - (true/false) - image will be cropped (if not set, image will be saved with saving proportions). Both width and height required
- manual_crop - (true/false) - Allows to crop image manually
- ratio - (float) - cropped area ratio (uses with manual_crop)
- watermark - (string) - relative or absolute path to watermark image
- watermark_position - (array) - array with two elements (left,top), sets watermark offsets in persents (example: array(95,5) - right top corner)
- blob - (true/false) - saves image as binary string in database blob field. Thumbnails creation is not available.
- grid_thumb - (int) - number of thumb, which will be displayed in grid. If not set, original image will be displayed.
- detail_thumb - (int) - number of thumb, which will be displayed in detail view/create/edit . If not set, original image will be displayed.
- thumbs - array of thumb arrays:
  - width, height, crop, watermark, watermark_position - see parent
  - marker - (string) - thumbnail marker (if you not set marker or folder, the main image will be replaced with thumbnail)
  - folder - (string) - thumbnail subfolder, relative to uploads folder (if you not set marker or folder, the main image will be replaced with thumbnail)

All paths are always relative to xcrud's folder

#### 7. Price

This group includes the following types of fields: price.

Takes default value in third parameter and array of parameters in 4th.

    $xcrud->change_type('amount', 'price', '5', array('prefix'=>'$'));

Parameters:

- max - (integer) - maximal length of text field (create/update), default is 10
- decimals - (integer) - cout of decimals, default is 2
- separator - (string) - thousands separator, default is comma (list view)
- prefix - (string) - prefix for list view
- suffix - (string) - suffix for list view
- point - (string) - decimal point for list view

#### 8. Remote images

This group includes the following types of fields: remote_image.

Takes default value in 3rd parameter and link part in 4th (e.g. if your field contains only file name, not full url).

    $xcrud->change_type('avatar', 'remote_image');
    // or
    $xcrud->change_type('avatar', 'remote_image', '', 'http://my-img-host.net/my-folder/');
    // 1.6
    $xcrud->change_type('avatar', 'remote_image', '', array('link'=>'http://my-img-host.net/my-folder/'));

#### 9. Locations and maps

This group includes the following types of fields: point.

This automatically works with 'POINT' mysql field type. In text field type coordinates will be saved as string separated with comma. 4th parameter gets array with map settings, also you can define them in configuration file to use by default.

    $xcrud->change_type('my_location','point','39.909736,-6.679687',array('text'=>'Your are here'));

Parameters:

- width - (integer) - width of map
- height - (integer) - height of map
- zoom - (integer) - map zoom
- text - (string) - text in info window
- search_text - (string) - placeholder for search field
- search - (true/false) - show search field
- coords - (true/false) - show coordinates field

### 10. Data manipulation

xCRUD use loadable libraries for data manipulation. You can use static functions in the classes, methods, objects, or simply a set of procedural functions. You need to specify the path to your library functions, and xCRUD it connects itself, when in fact will need. Xcrud will call own functions.php file when path is not defined. Xcrud instance will be always available in your function as last parameter.

callable - is callable parameter, if you want to call method from class, you must use an array, e.g. array('class', 'method'). For procedural function just set function name.

$postdata - the object, which represented xcrud's form data sent to server side. It has three methods:

- $postdata->get( field ) - returns value of a field or FALSE if field is not exist
- - $postdata->get( field )->as_date() - returns mysql date representation of value
  - $postdata->get( field )->as_time() - returns mysql time representation of value
  - $postdata->get( field )->as_datetime() - returns mysql datetime representation of value
- $postdata->set( field, value ) - sets new value in a field or creates new field in $postdata. Returns nothing. You no need to use unlock_field() method anymore.
- $postdata->to_array() - returns all data in array.

before_insert (callable, path) - allows you to prepare the data before inserting it into the database. Takes an callable in first parameter and the library path in second. Your function should take postdata object in the first parameter, xcrud's instance in second and no need to return anything.

    // function in functions.php
    function hash_password($postdata, $xcrud){
        $postdata->set('password', sha1( $postdata->get('password') ));
    }

    // creating action
    $xcrud->before_insert('hash_password'); // automatic call of functions.php
    //or
    $xcrud->before_insert('hash_password', 'functions.php'); // manualy load

before_update (callable, path) - allows you to prepare the data before updating the records in the database. Takes a callable as the first parameter and the library path in second. Your function should take an array of data in the first parameter and the same return. As well as optionally the primary key in the second parameter.

    // function in functions.php
    function hash_password($postdata, $primary, $xcrud){
        $postdata->set('password', sha1( $postdata->get('password') ));
    }

    // creating action
    $xcrud->before_update('hash_password');

after_insert (callable, path), after_update (callable, path) - allow you to pass data and primary key after upgrading to the custom function. The syntax is the same as in before_update (), except that the function is not obliged to return something.

before_remove (callable, path), after_remove (callable, path) - sends to user-defined function only the primary key record to be deleted in the first parameter. The syntax is the same as in previous examples. User-defined function is not obliged to return something.

In $postdata ANY date, datetime, time or timestamp field will be available only as TIMESTAMP.
Use $postdata->get( field )->as_date(), $postdata->get( field )->as_time(), $postdata->get( field )->as_datetime() to retrive date(time) in mysql format.

column_callback (column, callable, path) - allows you to define custom layer for your column data.

    $xcrud->column_callback('name','add_user_icon');

functions.php:

    <?php
    function add_user_icon($value, $fieldname, $primary_key, $row, $xcrud)
    {
       return '<i class="icon-user"></i>' . $value;
    }
    ?>

$row - full current row.

field_callback (field, callable, path) - allows you to define custom layer for your edit field.

    $xcrud->field_callback('name','nice_input');

functions.php:

    <?php
    function nice_input($value, $field, $priimary_key, $list, $xcrud)
    {
       return '<div class="input-prepend input-append">'
            . '<span class="add-on">$</span>'
            . '<input type="text" name="'.$xcrud->fieldname_encode($fieldname).'" value="'.$value.'" class="xcrud-input" />'
            . '<span class="add-on">.00</span>'
            . '</div>';
    }
    ?>

$list - all fields data

fieldname_encode() - this encodes field name in compatible format.

You can use data-required and data-pattern attributes, and unique class.

Important: you need to use xcrud-input class for your custom inputs to make its usable by Xcrud.

replace_insert(callable, path), replase_update(...), replace_remove(...) - replaces standsrt xcrud actions (insert, update, remove) by custom function. Each of this methods passes in the the target function its parameters.

Target function for replace_remove()

    function remove_replacer($primary_key, $xcrud){ ... }

Target function for replace_insert()

    function insert_replacer($postdata, $xcrud){ ... }

Target function for replace_update()

    function update_replacer($postdata, $primary_key, $xcrud){ ... }

$xcrud - xcrud current instance object.

replace_insert() and replace_update() methods must return value of primary key!

call_update( postdata, primary_key )

You can call xcrud update method in your replace_insert(), replase_update(), replace_remove() target functions:

    $xcrud->call_update($postdata, $primary_key);

#### Upload callbacks

before_upload(callable, path) - runs when files was sent to a server, but not processed yet.

after_upload(callable, path) - file was uploaded and moved to deinstanation folder (but not resized yet, if image).

after_resize(callable, path) - file was already resized. Available only for images.

Callback function example:

    function file_callback($field,$filename,$file_path,$config,$xcrud){
        ...
    }

- $field - full field name (table and culumn with dot separator)
- $filename - name of the file (not available for before_upload())
- $file_path - full file path with file name (not available for before_upload())
- $config - array with parameters from change_type() method (4th parameter).
- $xcrud - xcrud instance

####

#### Database instanse

In all external files you can use xcrud database instanse:

    $db = Xcrud_db::get_instance();
    $db->query(...) // executes query, returns count of affected rows
    $db->result(); // loads results as list of arrays
    $db->row(); // loads one result row as associative array
    $var = $db->escape($var); // escapes variable, ads single quotes
    $db->insert_id(); // returns last insert id

#### Control file type with upload callback (quick sample):

    $xcrud->after_upload('after_upload_example');

functions.php:

    function after_upload_example($field, $file_name, $file_path, $params, $xcrud){
        $ext = trim(strtolower(strrchr($file_name, '.')), '.');
        if($ext != 'pdf' && $field == 'uploads.simple_upload'){ // you can use other check-in
            unlink($file_path);
            $xcrud->set_exception('simple_upload','This is not PDF','error');
        }
    }

#### Additional variables

This methods allow you to send custom data in xcrud's templates or in calback functions.

set_var( var_name, value ) - set user variable

get_var( var_name ) - get user variable

unset_var( var_name ) - unset user variable

#### Interactive ajax callbacks

You can easy create some actions with callback on server side in xcrud's grid (see example)

First you must create callback (like other callbacks) with method 'create action()'.

create_action( action_name, callable, [path] ) - action_name - name of your action, callable - name of your callback (function or method), path (optional) - path to your file with function, default is 'functions.php'.

    $xcrud->create_action('my_action','my_function');

Than, create function in your functions.php (or you can use other file)

    function my_functions($xcrud){
        // some manipulations
    }

Finally, create button or link (or any) with specific class and data attributes. Simpliest button will be:

    <button class="xcrud-action" data-task="action" data-action="my_action">GO!</button>

This is required. You can define any other data attributes and all of them will be sent with action. To receive them in callback function you must call get() method with your attribute name in parameter (without data- prefix):

    function my_functions($xcrud){
        $myvalue = $xcrud->get('myvalue'); // data-myvalue attr.
        // some manipulations
    }

#### Returning errors from callback function

You can do you own validation or something more in any callback function during saving and return user back to form.

set_exception( [fields] , [text], [message_type] ) - fields - highlighted fields in form, text - error message, message_type - type of error message (error, note, success, info), just css class for message box, default is 'error'.
All arguments is optional.

    // function in functions.php
    function hash_password($postdata, $primary, $xcrud){
        $pass = $postdata->get('password');
        if(preg_match('/[a-zA-Z]+/u',$pass) && preg_match('/[0-9]+/u',$pass)){
            $postdata->set('password', sha1( $pass ) );
        }
        else{
            $xcrud->set_exception('password','Your password is too simple.');
        }
    }

### 11. Themes guide

You can create you own themes and customize standart themes in very simple way.

#### Theme structure and files

Xcrud's theme has 5 required files:

1. xcrud_container.php
2. xcrud_list_view.php
3. xcrud_detail_view.php
4. xcrud.ini
5. xcrud.css

xcrud_container.php - this file is static container for ajax side of Xcrud. It can be non-styled, but all Xcrud's event are delegated to this container. I not recommend to change something in this file.

xcrud_list_view.php - grid rendering.

xcrud_detail_view.php - rendering of create/edit/view screen

xcrud.ini - List of class names of core html elements, which cannot be changed in theme files.

xcrud.css - theme styles.

All this files will be loaded automatically.

#### Global variables in templates

$mode - shows current action. It can be list, create, edit, view.

#### Standart render methods

Some of render methods can accept tag paremeter. It can be a simple string ('div','h1' etc) or array (array('tag'=>'div')). In array you can add any other html attributes (array('tag'=>'a','href'=>'http://example.com')).

csv_button( classname, icon ) - render csv export button

print_button( classname, icon ) - render print button button

add_button( classname, icon ) - render Add button button

render_limitlist( buttons ) - render dropdown list or buttons with available rows per page. buttons = true - enable buttons instead of dropdown, default is false.

render_pagination( numbers, offsets ) - pagination; numbers - count of pagination buttons (default is 10); offsets - first and last buttons offsets (default is 2)

render_search() - search form

render_button( name, task, mode_after_task, classname, icon, primary_key ) - sender system action button.

render_benchmark( tag ) - shows benchmark info. Recomended to put it in the end of template.

render_grid_head( row_tag, item_tag, arrows_array ) - return grid heading. Arrorws array contains arrows for ordered column. Default is array('asc' => '&uarr; ', 'desc' => '&darr; ')

render_grid_body( row_tag, item_tag ) - main grid rendering

render_grid_footer( row_tag, item_tag ) - renders grid footer if available ( eg sum row)

render_fields_list( mode, container, row, label, field, tabs_container, tabs_menu_container, tabs_menu_row, tabs_menu_link, tabs_content_container, tabs_pane ) - big method, creates details row grid and tabs. Default values: ($mode, $container = 'table', $row = 'tr', $label = 'td', $field = 'td', $tabs_block = 'div', $tabs_head = 'ul', $tabs_row = 'li', $tabs_link = 'a', $tabs_content = 'div', $tabs_pane = 'div'). $mode parameter is required.

render_table_name( mode, tag, minimized ) - render table heading with table tooltip and toggle arrow. minimized - used only in container file.

#### Sending custom variables in template

set_var( var_name, value ) - set user variable

get_var( var_name ) - get user variable

unset_var( var_name ) - unset user variable

In theme files current instance can be accessed as $this, e.g. $this->get_var('my_var');

#### Relocating template files

load_view( task, file ) - this method allows you to replace default view file by your custom by task for current instance.

    $xcrud->load_view('create','my_custom_create_form.php');

Your custom theme files must be in your theme folder.

#### Creating non-standart rendering

$this->result_list - array of arrays with full result from database (grid). You can use it to create your own grid rendering.

$this->result_row - array with full result form database (create/edit/view).

$this->fields_output - array with rendered fields, exept hidden and additional fields. Every element contains:

1. label - field name, generated by Xcrud or defined by label() method
2. name - full field name, used by Xcrud.
3. value - raw value from database
4. field - already rendered form field by Xcrud.

$this->hidden_fields_output - array of rendered hidden fields

### 12. Date and time formats

#### PHP date format

Link: http://www.php.net/manual/en/function.date.php

The format of the outputted date string. See the formatting options below. There are also several predefined date constants that may be used instead, so for example `DATE_RSS` contains the format string 'D, d M Y H:i:s'.

The following characters are recognized in the `format` parameter string
`format` character | Description | Example returned values
--- | --- | ---
Day | --- | ---
d | Day of the month, 2 digits with leading zeros | 01 to 31
D | A textual representation of a day, three letters | Mon through Sun
j | Day of the month without leading zeros | 1 to 31
l (lowercase 'L') | A full textual representation of the day of the week | Sunday through Saturday
N | ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) | 1 (for Monday) through 7 (for Sunday)
S | English ordinal suffix for the day of the month, 2 characters | st, nd, rd or th. Works well with j
w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday)
z | The day of the year (starting from 0) | 0 through 365
Week | --- | ---
W | ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) | Example: 42 (the 42nd week in the year)
Month | --- | ---
F | A full textual representation of a month, such as January or March | January through December
m | Numeric representation of a month, with leading zeros | 01 through 12
M | A short textual representation of a month, three letters | Jan through Dec
n | Numeric representation of a month, without leading zeros | 1 through 12
t | Number of days in the given month | 28 through 31
Year | --- | ---
L | Whether it's a leap year | 1 if it is a leap year, 0 otherwise.
o | ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) | Examples: 1999 or 2003
Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003
y | A two digit representation of a year | Examples: 99 or 03
Time | --- | ---
a | Lowercase Ante meridiem and Post meridiem | am or pm
A | Uppercase Ante meridiem and Post meridiem | AM or PM
B | Swatch Internet time | 000 through 999
g | 12-hour format of an hour without leading zeros | 1 through 12
G | 24-hour format of an hour without leading zeros | 0 through 23
h | 12-hour format of an hour with leading zeros | 01 through 12
H | 24-hour format of an hour with leading zeros | 00 through 23
i | Minutes with leading zeros | 00 to 59
s | Seconds, with leading zeros | 00 through 59
u | Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds. | Example: 654321
Timezone | --- | ---
e | Timezone identifier (added in PHP 5.1.0) | Examples: UTC, GMT, Atlantic/Azores
I (capital i) | Whether or not the date is in daylight saving time | 1 if Daylight Saving Time, 0 otherwise.
O | Difference to Greenwich time (GMT) in hours | Example: +0200
P | Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) | Example: +02:00
T | Timezone abbreviation | Examples: EST, MDT ...
Z | Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. | -43200 through 50400
Full Date/Time | --- | ---
c | ISO 8601 date (added in PHP 5) | 2004-02-12T15:19:21+00:00
r | » RFC 2822 formatted date | Example: Thu, 21 Dec 2000 16:01:07 +0200
U | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | See also time()

#### jQuery UI date format

Link: http://api.jqueryui.com/datepicker/#utility-formatDate

Link: http://trentrichardson.com/examples/timepicker/

Format a date into a string value with a specified format.

The format can be combinations of the following:

- d - day of month (no leading zero)
- dd - day of month (two digit)
- o - day of the year (no leading zeros)
- oo - day of the year (three digit)
- D - day name short
- DD - day name long
- m - month of year (no leading zero)
- mm - month of year (two digit)
- M - month name short
- MM - month name long
- y - year (two digit)
- yy - year (four digit)
- @ - Unix timestamp (ms since 01/01/1970)
- ! - Windows ticks (100ns since 01/01/0001)
- '...' - literal text
- '' - single quote
- anything else - literal text

There are also a number of predefined standard date formats available from `$.datepicker`:

- ATOM - 'yy-mm-dd' (Same as RFC 3339/ISO 8601)
- COOKIE - 'D, dd M yy'
- ISO_8601 - 'yy-mm-dd'
- RFC_822 - 'D, d M y' (See RFC 822)
- RFC_850 - 'DD, dd-M-y' (See RFC 850)
- RFC_1036 - 'D, d M y' (See RFC 1036)
- RFC_1123 - 'D, d M yy' (See RFC 1123)
- RFC_2822 - 'D, d M yy' (See RFC 2822)
- RSS - 'D, d M y' (Same as RFC 822)
- TICKS - '!'
- TIMESTAMP - '@'
- W3C - 'yy-mm-dd' (Same as ISO 8601)

Time format

- H - Hour with no leading 0 (24 hour)
- HH - Hour with leading 0 (24 hour)
- h - Hour with no leading 0 (12 hour)
- hh - Hour with leading 0 (12 hour)
- m - Minute with no leading 0
- mm - Minute with leading 0
- s - Second with no leading 0
- ss - Second with leading 0
- l - Milliseconds always with leading 0
- c - Microseconds always with leading 0
- t - a or p for AM/PM
- T - A or P for AM/PM
- tt - am or pm for AM/PM
- TT - AM or PM for AM/PM
- z - Timezone as defined by timezoneList
- Z - Timezone in Iso 8601 format (+04:45)
- '...' - Literal text (Uses single quotes)

### 13. Migrate from 1.5

V.1.5 and 1.6 have a good compatibility, but not at all. All in short form. Description for separate methods you can find in this documentation.

#### Changed methods:

- change_type() - now it reqires array of attributes in last parameter for any form element (previous syntax saved). 3rd parameter is always default value for any type (even file and image). 4th parameter for image changes structure.
- relation() - you can use {field_tags} in 'where'(5th), an set order in 6th.
- where() - can receive custom condition in 1st or in 2nd parameter
- button() - 5th and 6th parameters totaly changed. No any url parametes there (you can create any url in first param). 5th - array with button html attributes, 6th - condition array.
- all before_*/after_* callbacks - first parameter was removed. If you need to load function from class, you can use array('class','method').
- 'date', 'datetime' and 'time' types changed data format. This affects only on callbacks ($postdata) and pass_var(). This mean that date or time will be sent in timestamp.

#### Removed methods:

All of this you can find in configuration file.

- disable_jquery()
- disable_jquery_ui()
- scripts_url()
- jquery_no_conflict()
- sess_expire()
- tinymce_folder_url()
- tinymce_init_url()
- force_tinymce()
- primary()

#### Deprecated methods:

This will be removed soon. Saved only for compatibility with v1.5

- readonly_on_create()
- disabled_on_create()
- readonly_on_edit()
- disabled_on_edit()
- alert_create()
- alert_edit()
- mass_alert_create()
- mass_alert_edit()
- page_call_create()
- page_call_edit()

### 14. Resources and thanks

jQuery - http://jquery.com/

jQuery UI - http://jqueryui.com/

jQuery-Timepicker-Addon - https://github.com/trentrichardson/jQuery-Timepicker-Addon

PhpLetter - http://www.phpletter.com/Our-Projects/AjaxFileUpload/

Twitter Bootstrap - http://getbootstrap.com/

Icomoon - http://icomoon.io/