PHP Scripts

Published in Convert Forms
Updated 05 Jul, 2019
Heads up! This article contains PHP code and is intended for developers. We offer this code as a courtesy, but don't provide support for code customizations or 3rd party development.

Are you looking for a way to do some extra field validation during form submission? Perhaps, you'd like to silently post submitted data to another URL? With the Convert Forms PHP Scripts section and the proper knowledge of PHP and MySQL you can do just about anything.

Joomla! Forms with Custom PHP Scripts execution support

The PHP Scripts area consits of the following 4 sections that are triggered on certain events.

1. Form Prepare

The PHP script added in this area is executed just before the form's data is prepared and send to the form display function. The main focus in this area is the $form (Array) variable which contains the form's settings. This area is rather useful when you need to populate dynamically a field, add more options to a dropdown listbox or modify the styling of the form.

Populate a Field

This example sets the default value of the field 'email'.

$form['fields']['email']['value'] = 'my@email.com';

Add an extra option to a listbox

This example adds an extra option to a listbox dropdown field

$form['fields']['dropdown_45']['choices']['choices'][] = [
    'value' => 'my_value',
    'label' => 'My Label'
];

2. Form Display

The PHP script added in this area is executed just before the form is displayed. The main focus in this area is the $formLayout (String) variable which contains the HTML code of the form. You can also access the form settings here using the $form (Array) variable.

Restrict access to a form

In this example guests will see a warning message while logged-in users will see the actual form.

if ($user->guest) {
	$formLayout = '<p>Please, log in to access this form.<p>';
}

Display form submissions count

The total number for form submissions can be helpful if you want to display the number of users who participated in a survey or have entered a content. This number can easily calculated with the example below:

$count = ConvertForms\Api::getFormSubmissionsTotal($form['id']);
$formLayout .= 'This form was submitted ' . $count . ' times.';

Hide form on mobile device

The example below uses the Convert Forms Api to detect if the user is browsing with a mobile device and removes completely the form from the page.

if (ConvertForms\Api::isMobile()) {
   $formLayout = "";
}

3. Form Process

The PHP code added in this area is executed just before the form data has been saved into the database regardless if the submission is valid or not. This area is rather useful when you need to process calculations, make advanced validation or modify the value of a field. Any modifications to $post (Array) variable performed here, will be reflected in the submission entry. You can also access the form settings here using the $form (Array) variable.

Populate a Field

This example changes the post variable for field name

$post['name'] = 'John Doe';

Populate a field using the value from another field

This example changes the post variable for field text_1 to the value of field text_2

$post['text_1'] = $post['text_2'];

Validate and limit characters allowed in a field

This example displays an error message when the field message exceeds the characters limit.

$max_chars = 50;
$error = "Maximum character limit reached.";

if (strlen($post["message"]) > $max_chars) {
   throw new Exception($error);
}

Unique Field Validation

The code below ensures that a unique email address has been entered into the email field. The example below makes use the getFormSubmissions() built-in API method to retrieve all form submissions from the database.

$unique_field = 'email';
$unique_field_error = 'A form with this value has already been submitted';
   
// Do not edit below
$unique_post_value = $post[$unique_field];

if (!$submissions = ConvertForms\Api::getFormSubmissions($form['id']))
{
    return;
}

foreach ($submissions as $key => $submission)
{
    if (!isset($submission->params->$unique_field))
    {
        continue;
    }

    $submission_unique_value = $submission->params->$unique_field;

    if ($unique_post_value == $submission_unique_value)
    {
        throw new Exception($unique_field_error);
    }
}

4. After Form Submission

The PHP code added in this area is executed after the form has been successfully submitted and the data has been saved into the database. This is rather useful when you are trying to run some extra tasks such as silently post data to another URL or feed data to third party applications. The $submission (Array) variable is available in this hook and contains all submitted values.

Delete submission from the database

There are cases when you'd like to delete the submitted data from the database after the submission has been processed. The example below, uses the submission_delete() built-in API method to delete the current submission from the database.

ConvertForms\Api::removeSubmission($submission->id);

Set the form success message

The example below, modifies the success message that will be displayed in the form

$submission->form->successmsg = "We have received your request. Submission ID: #" . $submission->id;

Save submission data to a file as JSON

The example below, reads the submitted data from the $submission object and stores specific info into a TXT file in the root of your webspace in JSON format.

$file = JPATH_SITE . '/submissions.txt';

$data = JFile::exists($file) ? json_decode(file_get_contents($file), true) : [];

if (!is_array($data)) {
    return;
}

array_push($data, [
	'ID'    => $submission->id,
	'Date'  => $submission->created,
	'Name'  => $submission->params['name'],
	'Email' => $submission->params['email']
]);

// Save the file again
JFile::write($file, json_encode($data));
Note: For debugging purposes you can always use die(); statements after echo or var_dump() commands. For example: var_dump($post); die();

LIMITED SALE 20% off any Tassos.gr extension. Coupon code ABCEKDJUEO