Last active
July 31, 2024 13:35
-
-
Save cballenar/e87c741da0cd7fe368162175e31087cb to your computer and use it in GitHub Desktop.
Set a Drupal's Webform paths automatically based on title. Add as custom module or to an existing module of your own.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
* Contains webform_auto_paths.module. | |
* | |
* Set a Drupal's Webform paths automatically based on the title. This improves | |
* the default use of the machine name (32 chars max) which can result in | |
* cropped or enumerated form URLs if the title is too long. | |
* | |
* The paths are set on the presave hook and will only be generated if the | |
* fields are empty. Allowing for easy customization. | |
*/ | |
use Drupal\webform\Element\Webform; | |
/** | |
* Implements hook_ENTITY_TYPE_presave(). | |
*/ | |
function webform_auto_paths_webform_presave(Webform $webform) { | |
// Get the webform title. | |
$title = $webform->label(); | |
// Trim and convert the title to kebab case. | |
$alias = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', trim($title))); | |
// Set the URL alias if it's empty. | |
if (empty($webform->getSetting('page_submit_path'))) { | |
$webform->setSetting('page_submit_path', '/form/' . $alias); | |
} | |
// Set the confirmation URL alias if it's empty. | |
if (empty($webform->getSetting('page_confirm_path'))) { | |
$webform->setSetting('page_confirm_path', '/form/' . $alias . '/confirmation'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment