0

I have this form to handle a custom content entity: enter image description here created by this code:

  public function buildForm(array $form, FormStateInterface $form_state, $contractId = NULL) {

    Some code to inialize here...

    $wrapper = 'formWrapper';
    $form['#prefix'] = '<div id="' . $wrapper . '">';
    $form['#suffix'] = '</div>';

    $form['designation'] = [
      '#type' => 'select',
      '#options' => $aMembers,
      '#title' => $this->t('Member'),
      '#required' => TRUE,
      '#empty_option' => t('- Select member -'),
      '#default_value' => $memberId,
      '#ajax' => [
        'callback' => '::memberCallback',
        'wrapper' => 'theSubscription',
      ],
    ];

    $form['theSubscription'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'theSubscription'],
      '#quantities' => $iNumberOfQuantities,
    ];

        $value = $subscription['quantity01'];
    $form['theSubscription']['quantity01'] = [
            '#type' => 'number',
            '#title' => 'quantity01',
            '#min' => 0.00,
            '#max' => 99.95,
            '#step' => 0.05,
            '#value' => $value,
      ];
    }

    $sharedwith_id = $subscription['sharedwith_member_id'];
    $form['theSubscription']['sharedwith'] = [
      '#type' => 'select',
      '#title' => t('Shared with'),
      '#options' => $aMembersforsharing,
      '#value' => $sharedwith_id,
    ];

    $form['theSubscription']['comment'] = [
      '#type' => 'textarea',
      '#title' => t('Comment'),
      '#rows' => 1,
      '#value' => $subscription['comment'],
    ];

    $fileId = (int) $subscription['file__target_id'];
    $form['theSubscription'][$fileId] = [
      '#type' => 'managed_file',
      '#description' => $this->t('Limited to @size MB.', ['@size' => $upload_max_inMB]) . '<br>' . $this->t('Allowed types: pdf.'),
      '#upload_location' => 'private://contracts/subscriptions/',
      '#upload_validators' => [
        'file_validate_extensions' => ['pdf'],
        'file_validate_size' => [$upload_max],
      ],
      '#default_value' => [$fileId],
    ];

    if ($sContractIsOpenForSubscription) {
      $form['save'] = [
        '#type' => 'submit',
        '#name' => 'save',
        '#value' => $this->t('Save'),
      ];
    }

    $form['leave'] = [
      '#type' => 'button',
      '#name' => 'leave',
      '#value' => $this->t('Leave'),
      '#ajax' => [
        'callback' => '::leaveCallback',
      ],
      '#limit_validation_errors' => [],
    ];

    $form['#attached']['library'][] = 'amap/amap';

    return $form;
  }

There are two buttons: 'save' of type 'submit' and 'leave' of type 'button' with an Ajax calback.
Everything works fine: 'leave' quits the form properly and 'save' actually saves data content entity as expected before presenting the empty form for another possible update.
Except for that piece of code which doesn't work (it is executed just after entity update):

\Drupal::messenger()->addMessage($this->t('The changes have been saved for « %designation ».', ['%designation' => $form["designation"]["#options"][$result["designation"]]]));

By the way, I also tried this:

$response = new AjaxResponse();
$response->addCommand(new MessageCommand($this->t('The changes have been saved for « %designation ».', ['%designation' => $form["designation"]["#options"][$result["designation"]]])));
return $response;

without success.

What is wrong with this code?

[Update] code executed by the two buttons: leave (Quitter):

  public function leaveCallback($form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new \Drupal\Core\Ajax\RedirectCommand(Url::fromRoute('amap.contracts')
      ->toString()));
    return $response;
  }

save (Enregistrer): function submitForm(a

rray &$form, FormStateInterface $form_state) {

    if ($form_state->getTriggeringElement()['#name'] == 'save') {
      some code to prepare entity update...
      if ($hash != $result['hash']) { <-- Is there aniting to do?
        Code to update content entity...
        _export_amap_CSV('amap_contracts_subscriptions', 'rest_export_1', $contract); <-- Export content entity as CSV file
        \Drupal::messenger()->addMessage($this->t('The changes have been saved for « %designation ».', ['%designation' => $form["designation"]["#options"][$result["designation"]]]));
      }
    }
    else {
      $form_state->setRebuild();
    }
  }
3
  • It's kind of incomplete code to debug the issue like submit handler code missing, however what I understood if you added the entity update/custom code in submit handler before the this code :\Drupal::messenger()->addMessage(), then you need to rearrange the code. to execute the message code before entity update code Oct 21, 2023 at 10:08
  • I added submit handler code to my question. I tried to move \Drupal::messenger()->addMessage before Code to update content entity.... It didn't change anything: still no message displayed.
    – gbmapo
    Oct 21, 2023 at 16:56
  • It's something that can't replicable or may be I 'm interpreting something else however for debug code, if you want you can try out these steps: Add message() before entity update then add entity update code, then again add message(), see the sequence in which order these code lines execute, Oct 21, 2023 at 18:14

1 Answer 1

0

It appears that it was some javascript in my library ($form['#attached']['library'][] = 'amap/amap';) which was interfering with sending the message...

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.