0

In an edit form for a content with paragraphs, I set errors on the paragraph specific field with this particular syntax:


$form_state->setErrorByName('field_paragraphs][' . $key . '][subform][field_sharepoint_file_url][' . $key2, t('Invalid URL'));

(see the missing square brackets at the beginning and at the end, solution found here)

This is working well.

However, I also need to register a different value on this field, and I can't seem to find the right way to do so.

I've tried to do this in a submit callback:

$form_state->setValue('field_sharepoint_file_url', $data->alias);

Or by retrieving the paragraph object in the hook_ENTITY_TYPE_presave:

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'page') {
    $result = $entity->get('field_paragraphs')->referencedEntities();
    if (!empty($result)) {
      foreach ($result as $paragraph) {
        /* @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
        if($paragraph->getType() == 'sharepoint_file') {
          /* @var \Drupal\Core\Field\FieldItemList $url */
          $urls = $paragraph->get('field_sharepoint_file_url');
          /* @var \Drupal\Core\Field\Plugin\Field\FieldType\StringItem $url */
          foreach ($urls as $url) {
            // [...]
            $paragraph->set('field_sharepoint_file_url', $data->alias);
          }
        }
        $paragraph->save();
      }
    }
  }
}

But the new value is never registered in database.

Thanks for any tip on this.

1

I'd imagine the first didn't work because your custom submit handler is run after the form default submit handler so it's too late (You didn't provide this code so can't be certain). You'd need to make sure your submit handler is run before any other submit handlers. To do that in the array of submit handlers your needs to be first in the array

Similarly for the 2nd option you've tried, you're in hook_presave so you're changing things but then when the normal entity save function happens after this any changes you made are overwritten

1
  • Thanks for your suggestions. The order of the submit handlers was the culprit.
    – claire_
    Mar 12 '20 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.