Enhancer for NULL field values

Created on 29 December 2023, 12 months ago
Updated 9 February 2024, 11 months ago

Problem/Motivation

I have a site running Gatsby on the front end with Drupal 10 on the back end. For optional fields, if there's no value supplied (meaning the field is NULL), the JSON:API endpoint shows it as NULL, but Gatsby can't see it. We had gotten around this during the initial build of the site by giving optional fields default values, but this seems like more of a hack than a long-term solution.

I tried writing an enhancer for JSON:API Extras that would check for a NULL value and change it to an empty string if found, but the enhancer doesn't seem to run if the field value is NULL. Admittedly I could be getting it wrong but the enhancer runs consistently if the field value isn't NULL.

Is there a way to make the enhancer run for NULL field values?

πŸ’¬ Support request
Status

Active

Version

3.24

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States jsutta United States

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @jsutta
  • πŸ‡¨πŸ‡΄Colombia camilo.escobar

    I created a field enhancer and was also hoping to provide sort of default value when the field han an empty or NULL value, but I found the same: field enhancers doesn't run when the field is empty. It would be useful to make it work to transform empty values as well.

  • πŸ‡¨πŸ‡ΏCzech Republic siva01

    We have resolved this issue by using a custom Drupal\custom_module\Normalizer, where the function normalizeFieldItems has been rewritten to provide a default value if the field value is NULL.

    It works, but it requires an extension of the @internal class FieldNormalizer. So I am not sure if it is the best practice, but it works.

  • πŸ‡¨πŸ‡΄Colombia camilo.escobar

    Hi @siva01! Thanks for sharing your solution.

    I assume you decorated the service serializer.normalizer.field.jsonapi via an impostor normalizer and overwrote the function normalizeFieldItems(). It's a clever solution, interesting approach.

    For other people who want to go down this path, it is important to note that there is another party involved in the implementation of an impostor normalizer (in addition to the links you provided above): a Service Provider class. That's necessary to enable the /src-impostor-normalizers folder to host impostor classes within the \Drupal\jsonapi\Normalizer namespace.

Production build 0.71.5 2024