logo live demo | download | class source | demo source | changelog.txt | github | email me
current version: 2016-04-14
project home and demos: http://lazymofo.wdschools.com/

What is Lazy Mofo (LM) PHP Datagrid?

LM is a single PHP5 class for performing CRUD (create, read, update and delete) operations on a MySQL database table.
What can LM do?

Contents

What's New

Requirements

Example 1 - Basic Usage

include('lazy_mofo.php');

// required for csv export
ob_start();

// connect to database with pdo
$dbh = new PDO("mysql:host=localhost;dbname=test;", 'user', 'password');

// create LM object, pass in PDO connection
$lm = new lazy_mofo($dbh); 

// table name for updates, inserts and deletes
$lm->table = 'market';

// identity / primary key column name
$lm->identity_name = 'market_id';

// use the lm controller 
$lm->run();

Example 2 - Advanced Usage

include('lazy_mofo.php');


// required for csv export
ob_start();


// connect with pdo 
$dbh = new PDO("mysql:host=localhost;dbname=testdb;", "username", "password");


// create LM object, pass in PDO connection
$lm = new lazy_mofo($dbh); 


// table name for updates, inserts and deletes
$lm->table = 'market';


// identity / primary key for table
$lm->identity_name = 'market_id';


// optional, make friendly names for fields
$lm->rename['country_id'] = 'Country';


// optional, define input controls on the form
$lm->form_input_control['photo'] = '--image';
$lm->form_input_control['is_active'] = "select 1, 'Yes' union select 0, 'No' union select 2, 'Maybe'; --radio";
$lm->form_input_control['country_id'] = 'select country_id, country_name from country; --select';


// optional, define editable input controls on the grid
$lm->grid_input_control['is_active'] = '--checkbox';


// optional, define output control on the grid 
$lm->grid_output_control['contact_email'] = '--email'; // make email clickable
$lm->grid_output_control['photo'] = '--image'; // image clickable  


// new in version >= 2015-02-27 all searches have to be done manually
$lm->grid_show_search_box = true;


// optional, query for grid(). LAST COLUMN MUST BE THE IDENTITY for [edit] and [delete] links to appear
$lm->grid_sql = "
select 
  m.market_id
, m.market_name
, m.photo
, m.contact_email
, c.country_name
, m.is_active
, m.create_date
, m.market_id 
from  market m 
left  
join  country c 
on    m.country_id = c.country_id 
where coalesce(m.market_name, '') like :_search 
or    coalesce(m.contact_email, '') like :_search 
or    coalesce(c.country_name, '') like :_search 
order by m.market_id desc
";
$lm->grid_sql_param[':_search'] = '%' . trim(@$_REQUEST['_search']) . '%';


// optional, define what is displayed on edit form. identity id must be passed in also.  
$lm->form_sql = "
select 
  market_id
, market_name
, country_id
, photo
, contact_email
, is_active
, create_date
, notes 
from  market 
where market_id = :market_id
";

$lm->form_sql_param[":$lm->identity_name"] = @$_REQUEST[$lm->identity_name]; 


// optional, validation. input:  regular expression (with slashes), error message, tip/placeholder
// first element can also be a user function or 'email'
$lm->on_insert_validate['market_name'] = array('/.+/', 'Missing Market Name', 'this is required'); 
$lm->on_insert_validate['contact_email'] = array('email', 'Invalid Email', 'this is optional', true); 


// copy validation rules to update - same rules
$lm->on_update_validate = $lm->on_insert_validate;  


// use the lm controller
$lm->run();

Hiding or Altering Links and Buttons

Most links, buttons, and messages can be hidden or altered. View the class source code to see all the member variables.
Example:

// change back button to read "Cancel"
$lm->form_back_button = "<input type='button' value='Cancel' class='lm_button dull' onclick='_back();'>";

// alter link text
$lm->grid_add_link = str_replace('Add a Record', 'Add New', $lm->grid_add_link);
$lm->grid_edit_link = str_replace('[edit]', 'Edit', $lm->grid_edit_link);

// hide delete and export links
$lm->grid_delete_link = "";
$lm->grid_export_link = "";

// change success message
$lm->form_text_record_added = "New Record Added";
$lm->grid_text_record_added = "New Record Added";

Redirect to Grid Screen After Update and Insert

By default the user is redirected back to the edit form after making updates or inserting a record. Redirect users to the opening grid screen by setting the following variables to false:


    $lm->return_to_edit_after_insert = false;
    $lm->return_to_edit_after_update = false;

Input and Output Controls - define how a field is rendered

Input and Output Controls are associative arrays used to define how to render input or output for a field.

Inputs render form inputs such as text, select, or checkbox.

Outputs render: text, links, and images. Output controls only apply to the grid view and are defined in grid_output_control.

Define Inputs on edit form()
$lm->form_input_control["field_name"] = "[sql] --command";

Define Inputs on grid()
$lm->grid_input_control["field_name"] = "[sql] --command";

Define Output on grid()
$lm->grid_output_control["field_name"] = "[sql] --command";

Examples: 

    $lm->form_input_control['client_pic'] = '--image';

    $lm->form_input_control['pdf'] = '--document';

    $lm->form_input_control['weird_data']  = '--my_user_function';

    $lm->form_input_control['will_you_attend'] = "select 1 as key, 'Yes' as val union select 0, 'No' union select 3, 'Maybe'; --radio";

    $lm->form_input_control['country_id'] = 'select country_id as val, country_name as opt from country; --select';

    $lm->form_input_control['is_active'] = "--checkbox"; // without a sql prefix this control will default to yes/no

Defining Custom Input and Output Controls

User defined functions can be defined to render an input or output control.

Example: 

$lm->form_input_control['weird_data'] = '--my_user_function';

function my_user_function($column_name, $value, $command, $called_from){

    // $column_name: field name
    // $value: field value  
    // $command: full command as defined in the arrays: form_input_control, grid_input_control, or grid_output_control
    // $called_from: which function called this user function; form, or grid

    global $lm;
    $val = $lm->clean_out($value);
    return "<input type='text' name='$column_name' value='$val' size='100'>";

}

Controls Which are Automatically Populated

By default LM will populate form_input_control and grid_output_control with --date, --datetime, --number and --textarea according to meta data. To disable this behavior set auto_populate_controls = false.

Native Input Controls

For use with form_input_control and grid_input_control arrays.

Native Output Controls

For use with form_output_control and grid_output_control arrays.

Adding Search

Version >= 2016-04-14 requires searching to be done manually.

Example:

$lm->grid_show_search_box = true;

$lm->grid_sql = "select m.market_id, m.market_name, m.photo, m.contact_email, c.country_name, m.is_active, m.create_date, market_id from market m left join country c on m.country_id = c.country_id where coalesce(m.market_name, '') like :_search or coalesce(m.contact_email, '') like :_search or coalesce(c.country_name, '') like :_search order by m.market_id desc";
$lm->grid_sql_param = array(':_search' => '%' . trim(@$_REQUEST['_search']) . '%');

Customizing the Search Form

Placeholders [script_name] and [_search] (not show here) are populated by the class.
Example:

$lm->grid_show_search_box = true; // show html defined in grid_search_box

$_new_search1 = $lm->clean_out(@$_REQUEST['_new_search1']);
$_new_search2 = $lm->clean_out(@$_REQUEST['_new_search2']);

// define our own search form with two inputs instead of the default one
$lm->grid_search_box = "
<form class='lm_search_box'>
	<input type='text' name='_new_search1' value='$_new_search1' size='20' class='lm_search_input'>
	<input type='text' name='_new_search2' value='$_new_search2' size='20' class='lm_search_input'>
	<input type='submit' value='Search' class='lm_search_button'>
	<input type='hidden' name='action' value='search'>
</form>
"; 

$lm->query_string_list = "_new_search1,_new_search2"; // add variable names to querystring so search is perserved when paging, sorting, and editing.

Defining Separate Add and Edit Forms

Different forms may be defined for adding records versus editing records.

Example:

if(!isset(@$_REQUEST[$lm->identity_name])){
	// form for adding records
	$lm->form_sql = 'select * from market where market_id = :market_id';
}
else{
	// form for editing records
	$lm->form_sql = 'select market_id, market_name, country_id, photo, is_active, create_date, notes from market where market_id = :market_id';
}

$lm->form_sql_param = array(':' . $lm->identity_name => @$_REQUEST[$lm->identity_name]); 

Validation

Server-side validation displays an error message next to the form input.
A general error message is displayed at the top and can be defined with the $lm->validate_text_general string setting.

Separate arrays are used for inserts and updates. If the validate needs are the same for both inserts and updates then just copy the existing array to duplicate the rules.

Alternatively, validation can be handled in On Insert/Update/Delete events (see below).

$lm-gt;on_insert_validate['field_name'] = array(string $regexp_or_user_function, string $error_message[, string $tip_placeholder , boolean optional_input]);

$lm-gt;on_update_validate['field_name'] = array(string $regexp_or_user_function, string $error_message[, string $tip_placeholder , boolean optional_input]);
Example: 

$lm->on_insert_validate['market_name'] = array('/.+/', 'Missing Market Name', 'This is Required'); 
$lm->on_insert_validate['contact_email'] = array('email', 'Missing or invalid Email', 'Optional Email', true); // built in validator for email, set to optional input
$lm->on_insert_validate['country_id'] = array('my_validate', 'Missing or invalid country', 'Required');        // user defined function

// copy array - same setting for updates
$lm->on_update_validate = $lm->on_insert_validate;

function my_validate(){

	if($_POST['country_id') == '')
		return false;
	else
		return true;

}

On Insert/Update/Delete Events

On Insert/Update/Delete functions are useful for validation and data manipulation.

These functions can be also be used for validation. Strings returned by the user defined functions are displayed at the top as error messages and the insert/update/delete action is halted.

Example: 

$lm->on_update_user_function = 'my_hash';

function my_hash(){

	if(isset($_POST['password_reset']))
		$_POST['password'] = password_hash($_POST['password_reset']);
	
	if(mb_strlen($_POST['password_reset']) > 100)
		return "Password too long";

}

After Insert/Update/Delete Events

User define functions can be defined in the properties listed below.

after_ events are useful for running trigger-like actions. The after_insert_user_function event uniquely receives the identity id of the newly added record.

Example: 

$lm->after_insert_user_function = 'my_after_insert';

function my_after_insert($id){
	
	// after_insert_user_function is the only action to get the identity id
	// now that the record is added we can do anything we need to

	global $lm;

	$sql_param = array(':market_id' => $id);
	$sql = "insert into related_table(field1, market_id) values (now(), :market_id)";
	$lm->query($sql, $sql_param);

}

Cast Data Based on Colunm Name

The cast_user_function array is used for storing column names and their corresponding cast function.

Example: 

// when using the checkbox input maybe we'd want unchecked to be 0 instead of null 
$lm->cat_user_function['is_active'] = 'my_cast';

function my_cast($val){
	
	return intval($val);
	
}

Cross Site Request Forgery Protection Token

This script does not validate csrf itself but has a placeholder csrf variable from loaded from $_SESSION['_csrf']. To protect from csrf, place your nonce token in $_SESSION['_csrf'] and validate the csrf on POST commands.

Example: 

// in your login script give the user a random string token
$_SESSION['_csrf'] = base64_encode(openssl_random_pseudo_bytes(15));

// somewhere else, before the page is processed, run some code like this 
if($_SERVER['REQUEST_METHOD'] === 'POST' && $_SESSION['_csrf'] != $_POST['_csrf'])
	die('Invalid csrf token');

Date Formats

Lazy Mofo will automatically identify date and datetime fields. All output of dates and datetimes are output in the format defined by member variables date_out and datetime_out.

Example: 

// default US format
$lm->date_out = 'm/d/Y';
$lm->datetime_out = 'm/d/Y h:i A';

// or set non-US date format
$lm->date_out = 'd/m/Y';
$lm->datetime_out = 'd/m/Y h:i A';

// or use a ISO-ish date format for html5 date inputs
$lm->date_out = 'Y-m-d';
$lm->datetime_out = 'Y-m-d H:i';

Adding JQuery UI Datepicker

Example: 

<link rel='stylesheet' href='//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css'>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
<script src='//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js'></script>
<script>
$(function() {
	
	// note how field class names are prefixed with 'lm_'
	$('input.lm_create_date').datepicker(); 
	
	// non US date example dd/mm/yy and week starting on monday(1) instead of sunday(0)
	// make sure lazy mofo class members for date_out and datetime_out correspond with your local date format
	//$('input.lm_create_date').datepicker({ dateFormat: 'dd/mm/yy', firstDay: 1 });


});
</script>

Export to CSV

Output buffering (ob_start) must be used at the beginning of the script for the export to CSV feature to function properly.

More Features and Settings

View class source code to see all the available settings and features.




Project Sponsored By:
Computer Animation Schools | Graphic Design Degrees | Web Design School | Criminal Justice and Paralegal Schools
Accounting Schools | Massage Therapy Schools | Pharmacy Tech Schools | Auto Mechanic Schools
Dental Hygienist Schools | Medical Tech Training | Phlebotomy Schools | Technician Schools