Drupal 8 or 9 - Webform - Searching and loading submission using form fields value

In Drupal, sometime we need to deal with already submitted form data. E.g. we may give end user to display some values of submitted records based on provided phone number or any other field.

For this, we would use Drupal database service which would allow us to build select query. In select query , you can mention fields you want to fetch and conditions to filter the data.

And if you fetch submission Id, then you can load the entire submission data.

Here is the code sample.

 


      // Find records in database for the webform submission
      $select = \Drupal::service('database')
          ->select('webform_submission_data', 'wsd')
          ->fields('wsd', array('sid'))
          ->orderBy('wsd.sid', 'DESC')
          ->condition('wsd.webform_id', 'webform_id', '=')
          ->condition('wsd.name', 'email_id', '=')
          ->condition('wsd.value', 'example@example.com', '=')
          ->execute();
      $results = $select->fetchAll(\PDO::FETCH_COLUMN);

      // Fetch or load records of extracted submission Id
      if($results){
          $sid = $results[0];
          $submission = \Drupal\webform\Entity\WebformSubmission::load($sid);
          $submission_data = $submission->getData();
          // Here, you can write further code to use this Data
         
      }

 

Tags