From 9118efe352889c1bb08208261455fd07fce794bf Mon Sep 17 00:00:00 2001
From: Liam Morland <lkmorlan@uwaterloo.ca>
Date: Wed, 4 May 2022 17:09:39 -0400
Subject: [PATCH] Issue #3278852: Always display warning on FillPDF form page
 when there are no fillable fields

Rather than only when the PDF is uploaded and only when using the pdftk
backend.
---
 src/Form/FillPdfFormForm.php              | 26 ++++++++++++++++++++---
 src/Plugin/PdfBackend/PdftkPdfBackend.php |  1 -
 2 files changed, 23 insertions(+), 4 deletions(-)

diff --git a/src/Form/FillPdfFormForm.php b/src/Form/FillPdfFormForm.php
index 01b5634..84c467a 100644
--- a/src/Form/FillPdfFormForm.php
+++ b/src/Form/FillPdfFormForm.php
@@ -138,6 +138,13 @@ class FillPdfFormForm extends ContentEntityForm {
     /** @var \Drupal\fillpdf\FillPdfFormInterface $fillpdf_form */
     $fillpdf_form = $this->entity;
 
+    $existing_fields = $fillpdf_form->getFormFields();
+
+    if (!count($existing_fields)) {
+      $fillpdf_form_fields_empty_message = $this->t('PDF does not contain fillable fields.');
+      $this->messenger()->addWarning($fillpdf_form_fields_empty_message);
+    }
+
     $form['title']['token_tree'] = $this->adminFormHelper->getAdminTokenForm();
 
     // @todo Encapsulate this logic into a ::getDefaultEntityType() method on FillPdfForm
@@ -397,9 +404,22 @@ class FillPdfFormForm extends ContentEntityForm {
     $form['user_password']['#group'] = 'security';
 
     // @todo Add a button to let them attempt re-parsing if it failed.
-    $form['fillpdf_fields']['fields'] = FillPdf::embedView('fillpdf_form_fields',
-      'block_1',
-      $fillpdf_form->id());
+    if (count($existing_fields)) {
+      $form['fillpdf_fields']['fields'] = FillPdf::embedView('fillpdf_form_fields',
+        'block_1',
+        $fillpdf_form->id());
+    }
+    else {
+      $form['fillpdf_fields'] = [
+        '#theme' => 'status_messages',
+        '#message_list' => [
+          'warning' => [$fillpdf_form_fields_empty_message],
+        ],
+        '#status_headings' => [
+          'warning' => t('Warning message'),
+        ],
+      ];
+    }
 
     $form['fillpdf_fields']['#weight'] = 100;
 
diff --git a/src/Plugin/PdfBackend/PdftkPdfBackend.php b/src/Plugin/PdfBackend/PdftkPdfBackend.php
index e697371..5fe89cd 100644
--- a/src/Plugin/PdfBackend/PdftkPdfBackend.php
+++ b/src/Plugin/PdfBackend/PdftkPdfBackend.php
@@ -119,7 +119,6 @@ class PdftkPdfBackend extends PdfBackendBase implements ContainerFactoryPluginIn
     $output = [];
     exec("{$pdftk_path} {$template_path} dump_data_fields_utf8", $output, $status);
     if (count($output) === 0) {
-      $this->messenger()->addWarning($this->t('PDF does not contain fillable fields.'));
       return [];
     }
 
-- 
GitLab