Processing Snippets

This information is based upon a question that was asked on GitHub, it references the conversion of a parameter used in eForm into FormLister

The question was:

Is there an equivalent of the following code for FormLister ?

&eformOnBeforeMailSent=``

The parameter was used to process a snippet that processes the server information of the person sending the form

The snippet (getServer) code:

<?php
function getServer( &$fields ){
$fields['remote_addr']=$_SERVER['REMOTE_ADDR'];
$fields['remote_host']=$_SERVER['REMOTE_HOST'];
$fields['user_agent']=$_SERVER['HTTP_USER_AGENT'];
return true;
}
?>

The answer to the question was a combination of a link to the documentation, specifically the section about Data Processing, and the conversion of the original snippet call, in two variations along with the parameter(s) that should be set to call the snippet.

Snippet conversion variant 1

<?php
$FormLister->setField('remote_addr', $_SERVER['REMOTE_ADDR']);
$FormLister->setField('remote_host', $_SERVER['REMOTE_HOST']);
$FormLister->setField('user_agent', $_SERVER['HTTP_USER_AGENT']);

Snippet conversion variant 2

<?php
$FormLister->setFields(array(
    'remote_addr' => $_SERVER['REMOTE_ADDR'],
    'remote_host' => $_SERVER['REMOTE_HOST'],
    'user_agent' => $_SERVER['HTTP_USER_AGENT']
));

Parameters that can be used for this example

&prepare=`getServer`

OR

&prepareProcess=`getServer`

There are multiple choices for the parameter, here is the explanation to why these were chosen:

Snippets called in the "Prepare" parameter are executed every time, whereby "prepareProcess" only processes them once. In this particular example, there's no difference, but it can be if you are working with a DB or CURL.

Further examples

All of the examples shown here were provided by the developer of the snippet

Example 1

//prepare-snippet to deny form procession if given name is foobar
$name = $FormLister->getField('name'); // $name = $data['name'] can be written as well
if ($name == 'foobar') {
    $FormLister->setValid(false);
}

Example 2

//prepare-snippet to manual field validation
$name = $FormLister->getField('name');
if ($name == 'foobar') {
    $FormLister->addError('name', 'foobar', 'Your name cannot be foobar');
}

Example 3

//prepareProcess-snippet to make report more nice
$data['message'] = nl2br(strip_tags($data['message']));
$data['name'] = ucfirst($data['name']);
$data['phone'] = empty($data['phone']) ? 'none' : $data['phone']; // assume that phone is not required field but we want to write 'none' in report if user has left it blank

return $data; // $FormLister->setFields($data) can be written as well

Snippets from the prepare parameter are run before form validation, from prepareProcess, after form validation but before the main controller action (sending mail or creating user etc.).

In-depth / advanced usage of this feature requires PHP knowledge

Suggest an edit to this page.