Using the PHP Scripts section

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

    Form Prepare

    The PHP script added in this area is executed just before the form's data is prepared and sent 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 Textbox Field

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

    $form['fields']['email']['value'] = '[email protected]';

    Populate a Checkboxes Field

    The following example inserts new options to a Checkboxes field and changes its value:

    // The name of the field
    $fieldName = 'checkbox';
    
    // The list of the options
    $options = [
        [
            'label' => 'Red',
            'value' => 'red'
        ],
        [
            'label' => 'Blue',
            'value' => 'blue'
        ],
        [
            'label' => 'Green',
            'value' => 'green'
        ]
    ];
    
    // Optionally, you can pre-check some options using this variable
    $value = ['blue', 'red'];
    
    // DO NOT EDIT BELOW
    $form['fields'][$fieldName]['choices']['choices'] = $options;
    $form['fields'][$fieldName]['value'] = $value;

    Populate a Dropdown with data from the database

    The example below returns all articles from the database and adds each article data zs an option to a dropdown field

    $query = $db->getQuery(true)
        ->select('id, title')
        ->from('#__content');
    
    $db->setQuery($query);
    
    $articles = $db->loadObjectList();
    $choices = [];
    
    foreach ($articles as $article)
    {
        $choices[] = [
            'value' => $article->id,
            'label' => $article->title,
        ];
    }
    
    $form['fields']['articlesDropdown']['choices']['choices'] = $choices;

    Advanced Examples

    A list of advanced examples that can be used before the form has been prepared and served to the user.

    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 content. This number can easily be calculated with the example below:

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

    Hide the form after X submissions

    The example below will hide the form after it has been submitted X number of times.

    $count = ConvertForms\Api::getFormSubmissionsTotal($form['id']);
    if ($count >= 50) {
         $formLayout = '';
    }

    Hide form on a 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 = "";
    }
    

    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 the $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 the 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'];

    Custom Validation Error

    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);
    }

    Limit how many submissions your form accepts

    This example makes your form accept X number of submissions and once the limit is reached, an error message will appear and it won't accept any new submissions.

    // Set the maximum submissions
    $max_submissions = 40;
    
    // Specify the error message for reaching maximum submissions.
    $error_message = 'We do not accept further submissions.';
    
    // Do not edit below
    if (ConvertForms\Form::getSubmissionsTotal($form['id']) >= $max_submissions)
    {
        throw new Exception($error_message);
    }

    Advanced Examples

    A list of advanced examples that can be used just before the form data has been saved into the database regardless if the submission is valid or not.

    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 posting data to another URL or feeding 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);

    Modify 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;

    Display a different success message based on a field value

    The example below modifies the success message based on the value of a submitted field

    $field_value = $submission->params['somefieldkey'];
    $message = $field_value == 'somevalue' ? 'some message' : 'alternative message';
    $submission->form->successmsg = $message;

    Advanced Examples

    A list of advanced examples that can be used after the form has been submitted

    Supported PHP variables

    Convert Forms provides some variables within PHP Scripts sections for commonly used jobs. You can find the list below:

    Variable Name Description
    $app The Joomla Application Object
    $doc The Joomla document object
    $db The Joomla database object
    $user The currently logged-in user object
    $itemid The "Itemid" value of the current request

    Troubleshooting

    My PHP code does not run. I don't even see an error message.

    It's very likely your PHP code is ignored because it contains one of the following forbidden functions: 

    • fopen
    • popen
    • unlink
    • rmdir
    • dl
    • escapeshellarg
    • escapeshellcmd
    • exec
    • passthru
    • proc_close
    • proc_open
    • shell_exec
    • symlink
    • system
    • pcntl_exec
    • eval
    • create_function
     

    Additionally, when a PHP snippet contains backticks `` won't be executed too. In this case, you should replace backticks with single quotes.

    Frequently Asked Questions

    Can I include PHP files within my code?

    The PHP Scripts sections allow you to include any external file from within your Joomla installation as long as you have the correct path. This is quite useful if you need to use the same PHP code on multiple forms, you can place the code in a PHP file and include it in your form's PHP Scripts section.

    include 'file/to/path.php';
    if (functionFromFile())
    {
    	// Do something...
    }
    Note: For debugging purposes, you can always use die(); statements after echo or var_dump() commands. For example: var_dump($post); die();
    Last updated on Oct 29th 2024 14:10