How to save to custom database table with MODX Formit

There are several ways you can save data to a custom table using MODX, there is an Extra called FormSave which does it all for you, but if you want more control and would like to create your own table and connect using Formit, here is a step by step guide as to how to create this.


How to save FormIt date to DB in MODX

Here is a step by step guide to using a custom hook for FormIt to save data to your custom database table.

What are hooks?

Hooks are basically scripts that run after a form is validated by FormIt. They can be chained; the first hook will execute, and if succeeds, will proceed onto the next hook. If a hook fails, it will not proceed to the next hook, but return back to the form with any error messages sent. The order of your hooks is important because they are processed one after the other

Hooks may also be Snippet names, which will then execute the Snippet as a hook.

There are two types of hooks:

A 'preHook', specified via the 'preHooks' property on the FormIt snippet, that executes when the form loads. Useful for pre-loading values.

The normal hook, specified via the 'hooks' property on the FormIt snippet, that executes after the form is validated. Useful for custom post-processing.

Step 1: Create your form using Formit parameters

Below is a simple contact form

 
<form action="[[~[[*id]]]]" method="post">
<input type="hidden" name="nospam:blank" /> 
<label for="Name">Name:</label> [[!+fi.error.name]] <input id="name" type="text" name="name" value="[[!+fi.name]]" /> 
<label for="Phone">Phone No:</label>[[!+fi.error.phone]] <input id="phone" type="tel" name="phone" value="[[!+fi.phone]]" />
<label for="Email">Email Address:</label> [[!+fi.error.email]] <input id="email" class="clear" type="email" name="email" value="[[!+fi.email]]" /> 
<label for="”message”">Message</label> <textarea name="”message”"></textarea> <input id="enquire" type="submit" value="Submit" /></form>
 
 

Step 2: Add the Formit Snippet tag

You will need to change the &redirectTo the resource for your set up or alternatively if not using redirect use &successMessage to display success message after a successful submission. See Formit for more information.

[[!FormIt?
&submitvar=`submit` 
&hooks=`formit2db,email,redirect`
&validate=`nospam:blank,name:required,phone:required,email:email:required`
&emailTpl=`emailResponse`  
&emailSubject=`Message from website` 
&emailTo=`youremail@domainname.com`  
&redirectTo=`6` ]]
 
 

Step 3: Create the Email Chunk Template

The email hook in the FormIt snippet tag will send the details of the message to the email address specified in the &emailTo property.

The &emailTpl property points to the name of a Chunk in which you'll have placeholders for each field in your form as below.

Message from website


<p>Name: [[+name]]<br />
Contact number: [[+phone]]<br /> 
Email address: [[+email]]<br /> 
Message: [[+message]]</p>

Step 4: Create the table in your database to store the submissions

Using PhpMyAdmin (or whatever method you prefer )open up your MODX database and create a new table that will hold our submitted date, called custom_contacts (you can, of course, call it what you like). Click on SQL tab and add following:

 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
CREATE TABLE IF NOT EXISTS `custom_contacts` (
`id` int(25) unsigned NOT NULL auto_increment,
`name` varchar(225) NOT NULL default '',
`phone` varchar(200) NOT NULL default '',
`email` varchar(20) NOT NULL default '',
`message` LONGTEXT NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ;

 

Step 5: Create MODX Package

Data is being saved in a table in your MODX database, and it’s good practise to use xPDO’s object model to access it. You will need to create a schema and add it as a xPDO model. To help with this process you will need to make use of the CreateXpdoClasses snippet written by Bob Ray to automate the process. Full details of creating Custom Database Tables can be found a bobsguides.com.

There are further instructions on how to make use of Bob’s snippet on his website. You can copy and paste the code from the downloable ZIP file here into a new snippet called ‘CreateXpdoClasses’.

Create a new resource called ‘Create Classes’ with an empty template and the put the following snippet tag into the Content field.

[[CreateXpdoClasses? &myPackage=`contacts` &myPrefix=`custom_`]]

Save, publish and preview the resource. You should see a message to confirm that the schema and class files are have been created. You only need to run this once, then you can unpublish. Check everything has been created by navigating to core/components/contacts/ directory.

Step 6: Create Custom Hook

This is what makes everything happen! The formit2db snippet which is called as a hook in your Formit tag and runs after validation has occurred.

 
/* List of data being passed from FormIt
1. name
2. phone
3. email
4. message
*/

/* Fetch information from the form */
$db_name = $hook-&gt;getValue('name');
$db_phone = $hook-&gt;getValue('phone');
$db_email= $hook-&gt;getValue('email');
$db_message= $hook-&gt;getValue('message');

/* Add contacts package and throw an error if fail */
$path = MODX_CORE_PATH . 'components/contacts/';
$result = $modx-&gt;addPackage('contacts',$path . 'model/','custom_');

if (! $result) {
  $errorMsg='Failed to add package ';
  $hook-&gt;addError('error_message',$errorMsg); 
  return false;
}
/* Create new posting object &amp; check if object was
   created or else throw an error. Name of class in
   schema is the name of the Object */

$contact = $modx -&gt; newObject('Contacts');

if (!is_object($contact) || !($contact instanceof xPDOObject)) {
    $errorMsg='Failed to create object of type: Contacts ';
    $hook-&gt;addError('error_message',$errorMsg); 
    return false;
}
/* Set data from form */
$contact -&gt; set('name', $db_name);
$contact -&gt; set('phone', $db_phone);
$contact -&gt; set('email', $db_email);
$contact -&gt; set('message', $db_mesage);

/* Save data from form and throw out errors if fails */

if (!$contact-&gt;save()) {
    $errorMsg='Failed to save message';
    $hook-&gt;addError('error_message',$errorMsg); 
    return false;
}
else
  return true;

 

Step 7: Run!

Test that everything works.

Thanks to Bob Ray for his guidelines on creating a custom table as well as his CreateXpdoClasses snippet and for the original blog post by King’Ori.

Comments (0)

Add a Comment





Allowed tags: <b><i><br>Add a new comment: