VSource Web Solutions About Us  |  News  |  Contact Info  |  Network  |  Policies  |  Login  |  Support  |  Forum  |  (866) 346-9327


Online Demo



   
 
Search Documentation Search Documentation
 
   

Datamanager Code Examples

   
 
Table Of Contents - Collapse

NEXT: Datamanager Actions
 
   

Conventions used in this document:

  • Any text that is in this font is considered code, a literal value, or the name of a file, folder, MySQL table, MySQL field, or a value in a MySQL field.
  • Any text that is surrounded by angle brackets like  <this>  means that you should substitute it for your own value. Example: vconsole/modules/<module>/ means that you should substitute <module> for your own value like invoices for the Manage Invoices module.
  • Any text that is surrounded by square brackets like  [this]  means that it is optional. Example: check_email($email, $error[, $dnscheck]);  means that [, $dnscheck] is optional
  • When you see ... in the code font, this means that you can add 1 or more items at that point. Do not actually include ... in your code.

Code Examples:
Here, we will give a few code examples to get you started. Although these code examples are fairly simple, they are still powerful enough for production use in some situations. In this example, we will walk you through creating a datamanager module that has 4 simple fields with add, edit, and delete actions.

Step 1: Create your MySQL table. This table will hold the data records. We will also pretend that we already have a few records in our example so that you can see how it all works.

Here is our MySQL table structure with our records and the table name is test_table.

----------------------------------------------------------------------
| id | created    | modified   | name          | size     | vccolor  |
-----+------------+------------+---------------+----------+-----------
  1  | 2008-01-09 | 2008-01-15 | First Record  | 10778921 |          |
  2  | 2008-06-12 | 2008-06-12 | Second Record | 89901123 | blue     |
  3  | 2008-07-04 | 2008-07-10 | Third Record  | 2202292  | green    |
  4  | 2008-07-05 | 2008-07-05 | Fourth Record | 72085    | blue     |
  5  | 2008-07-05 | 2008-07-07 | Fifth Record  | 1002299  |          |
----------------------------------------------------------------------

-- Here is the SQL to execute in order to create this table and these records.
CREATE TABLE IF NOT EXISTS `test_table` (
`id` int(11) NOT NULL auto_increment,
`created` date NOT NULL,
`modified` date NOT NULL,
`name` varchar(100) NOT NULL,
`size` int(11) NOT NULL,
`vccolor` varchar(15) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

INSERT INTO `test_table` (`id`, `created`, `modified`, `name`, `size`, `vccolor`) VALUES
(1, '2008-01-09', '2008-01-15', 'First Record', 10778921, ''),
(2, '2008-06-12', '2008-06-12', 'Second Record', 89901123, 'blue'),
(3, '2008-07-04', '2008-07-10', 'Third Record', 2202292, 'green'),
(4, '2008-07-05', '2008-07-05', 'Fourth Record', 72085, 'blue'),
(5, '2008-07-05', '2008-05-07', 'Fifth Record', 1002299, '');

Step 2: Add the new datamanager module record to the vc_modules table.
Execute the following MySQL query: (Note that your lft and rgt field values may differ depending on where you want your module to be in the hierarchical tree (See Managing Hierarchical Data - Nested Set Model for more information on what the lft and rgt fields should contain and how they determine a modules place in the hierarchical tree)

INSERT INTO `vc_modules` SET
  `module` = 'test',
  `version` = '1.0',
  `type` = 'DM',
  `lft` = '17',
  `rgt` = '18',
  `name` = 'Test Module',
  `help` = 'This is the help that is displayed on hover.';

Step 3: Create your base file structure.
Since our module is called test, we need to create the following new folders.
vconsole/modules/test/
vconsole/modules/test/actions/

Step 4: Create the main.php file. This file is called everytime a user clicks on the module button. The file should be located at:
vconsole/modules/test/main.php
Here is the code for this file. (This is a simplified version of the file without comments. To see the full version with comments, click here.)

<?php
global $GLOB, $OUT, $DATA, $PARAMS;
 
// Make sure that the action does not contain any bad characters
$_REQUEST['action'] = preg_replace("/\W/i", '', $_REQUEST['action']);

// Check to see that the action file exists.
if (file_exists("modules/{$_SESSION['module']}/actions/{$_REQUEST['action']}.php")) {
  // Check to see that the user has permission to the action
  if (check_action_permission(FALSE, FALSE, TRUE)) {
    // Execute the action file.
    require("modules/{$_SESSION['module']}/actions/{$_REQUEST['action']}.php");
  }
  // No access, set an error message.
  else { set_message('error', "Access Denied. Please check with your administrator for access."); }
}
 
// Get the Datamanager array and store it in a variable ($dms)
$dms = get_dms_array($_SESSION['module']);
// Pass the dms structure to the datamanager. The datamanager never returns.
datamanager($dms);

?>

Step 5: Create the dms.php file. The dms.php file is called by the get_dms_array() function in the main.php file above. This file is the heart of your module and defines what your module will look and behave like. The file should be located at:
vconsole/modules/test/dms.php
Here is the code for this file. (This is a simplified version without many comments. To see the skeleton file that we recommend starting off with, click here.)

<?php
// First thing is to define your queries. All queries should contain a WHERE clause.

// Count Query (should return a single value. The total number rows that the user can see.)

$cquery = "SELECT COUNT(*) FROM `test_table` WHERE 1";

// Data Query (should return the the full data set required to display rows. 1 field for each column to display)
$dquery = "SELECT * FROM `test_table` WHERE 1";

// Index Query (Just like the data query except it returns only a single row - specified by ||rowid||.
// Don't take out ||rowid||. ||rowid|| will be sutstituted for an actual id when it needs it.)

$iquery = "SELECT * FROM `table` WHERE `id` = ||rowid||";

// Reindex Query (Should return all the id's from the table - Used to reindex)
$rquery = "SELECT `id` FROM `table` WHERE 1";

// This is your $dms array that will be returned.
$dms = array(
  'module' => 'test',
  'table' => 'test_table',
  'tableindex' => 'id',

  // Single Operations, Things we can do to a single record.
  'singleops' => array(
    // Our Add Action (Shown on right click)
    array(
     'image' => 'icon_document_add',
     'label' => 'New Item',
     'help' => 'Click to create a new item.',
     'action' => 'add'
    ),
    // Our Edit Action (Shown on right click)
    array(
     'image' => 'icon_document_config',
     'label' => 'Edit',
     'help' => 'Click to edit this record.',
     'action' => 'edit'
    ),
    // Our Delete Action (Shown on right click)
    array(
     'image' => 'icon_trash',
     'label' => 'Delete',
     'help' => 'Click to delete this record.',
     'action' => 'del',
     'separator' => 'before'
    )
  ),
 
  // Group Operations, Things we can do to multiple records at once.
  'groupops' => array(
    // Our Delete Action (Shown on right click)
    array(
     'image' => 'icon_trash',
     'label' => 'Delete',
     'help' => 'Click to delete all selected records.',
     'action' => 'del'
    )
  ),

  // Data Fields, Since we have 4 MySQL fields, (Not including vccolor and id)
  // We will define 4 field definitions here.

  'data' => array(
    'fields' => array(
      // First Field - created
      'created' => array(
        'header' => array(
          'defaultview' => true,
          'type' => 'text',
          'title' => 'Created On',
          'help' => 'Click to sort by this column.',
          'sortfield' => '`created`'
        ),
        'data' => array(
          'type' => 'date'
        )
      ),
      // Second Field - modified
      'modified' => array(
        'header' => array(
          'defaultview' => true,
          'type' => 'text',
          'title' => 'Modified On',
          'help' => 'Click to sort by this column.',
          'sortfield' => '`modified`'
        ),
        'data' => array(
          'type' => 'date'
        )
      ),
      // Third Field - name
      'name' => array(
        'header' => array(
          'defaultview' => true,
          'type' => 'text',
          'title' => 'Record Name',
          'help' => 'Click to sort by this column.',
          'sortfield' => '`name`',
        ),
        'data' => array(
          'type' => 'text',
          'datatitle' => true
        )
      ),
      // Fourth Field - size
      'size' => array(
        'header' => array(
          'defaultview' => true,
          'type' => 'text',
          'title' => 'Record Size',
          'help' => 'Click to sort by this column.',
          'sortfield' => '`size`',
        ),
        'data' => array(
          'type' => 'number',
          'format' => 'test_format_size',
          'showtotal' => true
        )
      )
    )
  ),

  // MySQL Queries
  'queries' => array(
    'count' => $cquery,
    'data' => $dquery,
    'index' => $iquery,
    'reindex' => $rquery
  ),
);

// Now return our $dms array
return $dms;

?>

Remember, there are a lot of different parameters that you can use in your $dms structure. Check out the full list of $dms parameters to see how you can further customize your application. After creating these files, you should have a fully functional Datamanager Module. Here is a screenshot of the result.

Datamanager Code Example

Step 6: Create your functions.php file. Your functions.php file should contain a single function called test_format_size. The reason that we only want this 1 function is because, in our dms.php file, we only have 1 field that requires a format function. That field is the size field ('format' => 'test_format_size'). (If you wanted to customize what the user sees for each field, you could define a format function for each field if you like.) What we want to do is give the Record Size as a byte count rather than a plain number. So create the following file:
vconsole/modules/test/functions.php
Here is the code for this file.

<?php
 
// Function to format the size field
function test_format_size($row) {
  return format_filesize($row['size']);
}

?>

This file with this single function will format our size field so that it shows up as a file size instead of a number. Here is what the interface looks like after adding this file. Notice that the Record Size column is now formatted as a file size.
Datamanager Code Example After Format

Step 7: Create your action files.
All that's left now is to create your action files. Your action files should be located in the following folder:
vconsole/modules/test/actions/
When you right click on a record, you will see the 3 actions that you specified up in the singleops and groupops sections of the dms.php file. Those actions are named add, edit, and del. So we whould have these 3 action files:
vconsole/modules/test/actions/add.php
vconsole/modules/test/actions/edit.php
vconsole/modules/test/actions/del.php

Here is what the code looks like for these files. (Please see the Datamanager Actions section of this publication for more information on how to format these files.)
This is the add.php action file. This is a simplified version of the file that is not heavily commented. To see the skeleton file that we recommend starting off with, click here.)

<?php
global $GLOB, $OUT, $DATA, $PARAMS, $DBS;
// This is the add.php file.
// A simple wizardmanager action file to add a new record.


$wm = array(
  // Wizard Information.
  array(
    'title' => 'New Item',
    'image' => 'document_add',
    'info' => 'You are adding a new item.'
  ),
  // Step 1 of the wizard
  array(
    'condition' => 1, // Always execute the first step
    'fields' => array(
      // Record Name Field
      array(
        'type' => 'text',
        'name' => 'name',
        'label' => 'Record Name',
        'labelpos' => 'before',
        'help' => 'Enter a record name',
        'pack' => 'nextrow',
        'fielddata' => array(
          'attributes' => array(
            'size' => 50,
            'maxlength' => 50
          )
        ),
        'validate' => array(
          'required' => true, // Must enter a value
          'type' => 'text', // Allow basic text only
          // Must be between 5 and 50 characters
          'maxlength' => 50,
          'minlength' => 5
        )
      ),
      // Size
      array(
        'type' => 'text',
        'name' => 'size',
        'label' => 'Record Size',
        'labelpos' => 'before',
        'help' => 'Enter a size in bytes',
        'pack' => 'nextrow',
        'fielddata' => array(
          'attributes' => array('size' => 50)
        ),
        'validate' => array(
          'required' => true,
          'type' => 'number',
          'minnum' => 1024, // 1KB min
          'maxnum' => (1024 * 1024 * 1024) // 1GB max
        )
      ),
    )
  )
);

// Pass the $wm array to the wizardmanager
$data = wizardmanager($wm);
if (is_array($data)) {
  // The user saved the data and all fields are validated.
  // No need to validate again.
  // Uncomment the next line to see what $data contains
  // html_print_r($data);


  // Insert the record.
  $id = db_query("INSERT INTO `test_table` SET
    `created` = NOW(),
    `modified` = NOW(),
    `name` = "
. db_quote($data[1]['name']) . ",
    `size` = "
. db_quote($data[1]['size']), $dbr);

  // Index the record so it shows up in search results
  searchindex($_SESSION['module'], $id);

  // Set a message to the user. (messages are stored in $OUT['messages'])
  set_message('success', 'Your new record has been added.');
 
  // Print out the message and javscript to update the datamanager table
  // Separate these 2 things with <<>>

  print "{$OUT['messages']}<<>>updateDataTable();";
  exit;

} else { // User hit the cancel button
  print "<<>>wmdivClose();";
  exit;
}  

Here is the edit.php file, It is just like the add.php file, except it edits an existing record and updates the modified time.
<?php
global $GLOB, $OUT, $DATA, $PARAMS, $DBS;
// This is the edit.php file.
// A simple wizardmanager action file to edit an existing record.


// Make sure that the user selected only 1 record.
$selected = datamanager_getselected();
if (count($selected) != 1) {
  set_message('error', 'You must select 1 item to edit.');
  return;
}

// Get the record so that we can edit it.
db_query("SELECT * FROM `test_table` WHERE `id` = " . db_quote($selected[0]), $dbr);
$mod = mysql_fetch_assoc($dbr);

// If we didn't find the record, handle that.
if (!$mod['id']) {
  set_message('error', 'Could not find the record to edit.');
  return;
}

$wm = array(
  // Wizard Information.
  array(
    'title' => 'Edit Item',
    'image' => 'document_config',
    'info' => 'You are editing an existing item.'
  ),
  // Step 1 of the wizard
  array(
    'condition' => 1, // Always execute the first step
    'fields' => array(
      // Record Name Field
      array(
        'type' => 'text',
        'name' => 'name',
        'label' => 'Record Name',
        'labelpos' => 'before',
        'help' => 'Enter a record name',
        'pack' => 'nextrow',
        'fielddata' => array(
          'default' => $mod['name'],
          'attributes' => array(
            'size' => 50,
            'maxlength' => 50
          )
        ),
        'validate' => array(
          'required' => true, // Must enter a value
          'type' => 'text', // Allow basic text only
          // Must be between 5 and 50 characters
          'maxlength' => 50,
          'minlength' => 5
        )
      ),
      // Size
      array(
        'type' => 'text',
        'name' => 'size',
        'label' => 'Record Size',
        'labelpos' => 'before',
        'help' => 'Enter a size in bytes',
        'pack' => 'nextrow',
        'fielddata' => array(
          'default' => $mod['size'],
          'attributes' => array('size' => 50)
        ),
        'validate' => array(
          'required' => true,
          'type' => 'number',
          'minnum' => 1024, // 1KB min
          'maxnum' => (1024 * 1024 * 1024) // 1GB max
        )
      ),
    )
  )
);

// Pass the $wm array to the wizardmanager
$data = wizardmanager($wm);
if (is_array($data)) {
  // The user saved the data and all fields are validated.
  // No need to validate again.
  // Uncomment the next line to see what $data contains
  // html_print_r($data);

  // Update the record.

  db_query("UPDATE `test_table` SET
    `modified` = NOW(),
    `name` = "
. db_quote($data[1]['name']) . ",
    `size` = "
. db_quote($data[1]['size']) . "
     WHERE `id` = "
. db_quote($mod['id']), $dbr);

  // Reindex the record so it shows up in search results
  searchindex($_SESSION['module'], $mod['id']);

  // Set a message to the user. (messages are stored in $OUT['messages'])
  set_message('success', 'Your record has been modified.');
 
  // Print out the message and javscript to update the datamanager table
  // Separate these 2 things with <<>>

  print "{$OUT['messages']}<<>>updateDataTable();";
  exit;

} else { // User hit the cancel button
  print "<<>>wmdivClose();";
  exit;
}  

Here is the del.php file. This file is also a wizardmanager file but unlinke the edit.php file, this file allows you to delete multiple records at once.
<?php
global $GLOB, $OUT, $DATA, $PARAMS, $DBS;
// This is the del.php file.
// A simple wizardmanager action file to delete multiple records.


// Make sure that the user selected at least 1 record.
$selected = datamanager_getselected();
if (count($selected) < 1) {
  set_message('error', 'You must select 1 or more items to delete.');
  return;
}

$wm = array(
  // Wizard Information.
  array(
    'title' => 'Delete Items',
    'image' => 'trash',
    'info' => "You are deleting" . count($selected) . " items."
  ),
  // Step 1 of the wizard
  array(
    'condition' => 1, // Always execute the first step
    'fields' => array(
      // Confirmation Message
      array(
        'type' => 'blank',
        'label' => '<div class="error"><div>
                    You are about to delete all selected records.<br />
                    Deleting a record is permanent.
                    Please make sure before continuing.</div></div>'
,
        'labelpos' => 'above',
        'pack' => 'nextrow'
      ),
      // Confirmation Checkbox
      array(
        'type' => 'checkbox',
        'name' => 'confirm',
        'label' => 'Do you want to delete all selected records?',
        'labelpos' => 'after',
        'merge' => true,
        'pack' => 'nextrow',
        'fielddata' => array(
          'value' => 1
        ),
        'validate' => array(
          'required' => true,
          'failmsg' => 'You must check the checkbox to continue.'
        )
      )
    )
  )
);

// Pass the $wm array to the wizardmanager
$data = wizardmanager($wm);
if (is_array($data)) {
  // The user saved the data and all fields are validated.
  // No need to validate again.
  // Uncomment the next line to see what $data contains
  // html_print_r($data);

  // Delete all selected records.

  db_query("DELETE FROM `test_table` WHERE `id` IN (" .
    join(', ', db_quote($selected)) . ")", $dbr);

  // Delete any search indexes for the deleted records
  // 1 call to delete_searchindex() is all we need.

  delete_searchindex($_SESSION['module'], 'test_table');

  // Set a message to the user. (messages are stored in $OUT['messages'])
  set_message('success', 'Your records have been deleted.');
 
  // Print out the message and javscript to update the datamanager table
  // Separate these 2 things with <<>>

  print "{$OUT['messages']}<<>>updateDataTable();";
  exit;

} else { // User hit the cancel button
  print "<<>>wmdivClose();";
  exit;
}  

You now have a fully functional module with add, edit, and delete actions.
Need more examples? Send an email to rperea@vsourceweb.com and we will see if we can post it.


NEXT: Datamanager Actions


COMMENTS
 

There are no comments at this time.

Post Your Comment
 
Your Name*
Your Email Address* (Not Shown)
Your Comment (HTML OK)*
Enter the characters that you see here
Get New Image
*required fields