/**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\file\FileInterface $file */
    $file = $form_state->getValue('upload_pdf');
    $added = $this->inputHelper->attachPdfToForm($file);

    $fillpdf_form = $added['form'];
    $form_fields = $added['fields'];

    if (count($form_fields) === 0) {
      drupal_set_message($this->t('No fields detected in PDF. Are you sure it contains editable fields?'), 'warning');
    }

    $fid = $fillpdf_form->id();
    $form_state->setRedirect('entity.fillpdf_form.edit_form', ['fillpdf_form' => $fid]);
  }
  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    /** @var FillPdfFormInterface $entity */
    $entity = $this->getEntity();

    /** @var \Drupal\file\FileInterface $file */
    $file = $form_state->getValue('upload_pdf');

    if ($file) {
      $existing_fields = $this->entityHelper->getFormFields($entity);

      // Delete existing fields.
      /** @var FillPdfFormFieldInterface $existing_field */
      foreach ($existing_fields as $existing_field) {
        $existing_field->delete();
      }

      $added = $this->inputHelper->attachPdfToForm($file, $entity);

      $form_fields = $added['fields'];

      // Import previous form field values over new fields.
      $non_matching_msg = '';
      $non_matching_fields = $this->serializer->importFormFieldsByKey($existing_fields, $form_fields);
      if (count($non_matching_fields)) {
        $non_matching_msg = $this->t(" These keys couldn't be found in the new PDF");
      }

      drupal_set_message($this->t("Your previous field mappings have been transferred to the new PDF template you uploaded.") . $non_matching_msg);

      foreach ($non_matching_fields as $non_matching_field) {
        drupal_set_message($non_matching_field, 'warning');
      }

      drupal_set_message($this->t('You might also want to update the <em>Filename pattern</em> field; this has not been changed.'));
    }

    $entity->set('default_entity_type', $form_state->getValue('default_entity_type'));

    $entity->save();
  }