2

We would like to be able to put our site into a "read-only" mode prior to doing major releases etc. I was hoping to achieve this for forms on the site by enabling or disabling my custom module, which I could easily do from drush during our release process.

The module would use a hook to disable all forms and show the closed message instead.

This is what I had so far:

<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implementation of hook_form_alter().
 *
 * Disables any webforms when this module is active. Include a custom config key
 * called `exempt_from_maintenance_mode` with any value to allow your form to
 * remain open during maintenance.
 *
 * E.g.
 *     exempt_from_maintenance_mode: 1
 *
 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
 */
function yvw_maintenance_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
    // Check for custom config key
    if (array_key_exists('#exempt_from_maintenance_mode', $form)) {
        return;
    }

    // Load the webform entity. This should prevent the module from disabling
    // all forms across the site.
    $webform_id = $form['#webform_id'];
    $webform = \Drupal::entityTypeManager()->getStorage('webform')->load($webform_id);

    // Only disable the webform if its currently enabled
    if ($webform->status() === true) {
        $webform->setStatus('closed');
        // Does not save. Maybe we need a different hook.
    }
}

The problem is I would need to call $webform->save(); which would permanently close the form. I was hoping there was a hook where I could modify the form configuration only at runtime, and not persist any of the changes to the database. But I haven't been able to find any hooks that look like they would do it.

I had a look at Close a webform when total seats reach a maximum which is close to what I want, but it appears that would only run on submission, and also permanently closes the form.

1 Answer 1

2

Webforms are config entities and you can use hook_webform_load() to close the webform before it is rendered and then altered. Instead of closing and resaving the webform, you can call $webform->setPropertyOverride('status', FALSE); which will safely close the webform and prevent it from being permanently closed.

3
  • Thanks so much! That is exactly what I needed.
    – Henry
    Commented Mar 7, 2019 at 5:31
  • I'm using the Webform Node module. This doesn't seem to work when I use $webform->setPropertyOverride('status', WebformInterface::STATUS_CLOSED);.
    – mbomb007
    Commented Aug 1 at 19:15
  • I'm using the load hook as suggested, but it still shows the status wrong.
    – mbomb007
    Commented Aug 1 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.