8 – How to load a file entity by uuid?

So I am trying to use the default image for users in a menu block if a custom one does not exist. And for it I am getting the image file uuid:

$default_image = $user->get('user_picture')->getSetting('default_image');

Then loading the file entity:

$file = Drupal::service('entity.repository')->loadEntityByUuid('file', $default_image('uuid'));

This is returning null. What am I doing wrong? And is there a better way to achieve this?

architecture – DDD Modeling – Entity with generic and specific data

Suppose I am buying coffee. There are several types of coffee (A1, A2, A3), but sometimes I want to make a reference to all types of coffee (like if I had a coffee “grouped”). Considering DDD concepts, coffee A1 is different from all types of coffee, so that’s their identities and I need to reference both specific and generic Coffee Entity.

I thought I could map it like:

class Coffee{ 
  private CoffeeId id;
  private Code code;
  private SubGroup subGroup; 

For coffee A1, its id would be “ca1”, for coffee A2 its id would be “ca2” and for generic coffee could be “cag” and subGroup attribute would be null.

Someone finds another way to transform these use cases into entities?

entities – Validation on custom entity edit form

I have a custom entity where, instead of using the usual way of specifying edit form options with setDisplayOptions('form' and relying on ContentEntityForm to create my edit form for me, I have to make my own form in buildForm() (I have Ajax interactions between the fields that the stock from can’t provide). It works all right, just that I can’t trigger validation as with the stock form. The constraints are there and if I override:

public function validateForm(array &$form, FormStateInterface $form_state) {
  $entity = parent::validateForm($form, $form_state);
  $violations = $entity->validate();
  foreach ($violations as $v) {
  return $document;

the validation errors are in fact found and listed, just the form won’t display the usual red warnings, keeping the user from going on. Can I reconcile the custom form building with the automatic validation?

domain driven design – Should an Use Case method receive a “pre-filled” entity or a DTO as a parameter?

I’m building a use-case for creating blog posts, at first I thought of using an entity as a use-case parameter, and this entity would be created by the layer that calls Use Case, in my case a controller.



public function createPost(request: Request): void {

  const imagesToUpload: string() = request.files('images');

  try {

    const PostEntity = new Post(..., imagesToUpload);
    const createdPost = this.createPost.create(PostEntity)

  } catch (exception) {

Use Case:

export default class CreatePost {

  private PostRepository: PostRepository;
  private StorageAdapter: StorageAdapter;

    PostRepository: PostRepository,
    StorageAdapter: StorageAdapter
  ) {
    this.PostRepository = PostRepository;
    this.StorageAdapter = StorageAdapter;

  public create(Post: Post): PostId {

    let uploadedImages: string();

      const images = Post.getImages()

      if (images.length > 0) {
        // upload images
          (image) => uploadedImages.push(this.StorageAdapter.upload(image))

    // imutability broken

    return this.PostRepository.create(Post)

Some problems I noticed:

1 – My Entity is being created on the controller without an ID

Although I could inject a repository or even directly use a factory to generate a PostId, it doesn’t seem right for an outer layer to communicate directly with an inner layer, although I understand that it’s okay for the infrastructure to know the domain.

2 – My entity is immutable, but some information is only available after some actions have taken place in my Use Case, such as the return of uploaded images URLs, so my entity may start with an invalid state (no images)

In this scenario where I’m breaking my entity’s immutability, and initially creating it without an ID, does it make sense to use a DTO as a Use Case parameter?

2.2 – if I use a DTO, wouldn’t the Use Case layer be coupled to the DTO, knowing its properties, getters, etc? or is it “OK” to create a specific DTO for this Use Case layer? such as: CreatePostDTO

8 – Access a user entity reference in a commerce-product template file

I have a field_intervenantfield which contains a user entity reference.
In the commerce-product template file, I want to access the description field of each intervenant.

How can I achieve it?

I tried reading the following values, but none of them returns what I am looking for.

  • product.field_intervenants.entity.field_description
  • product.field_intervenants.0.entity.field_description
  • product_entity.field_intervenants.0.entity.field_description
  • product_entity.field_intervenants.field_description
  • product_entity.field_intervenants.field_description.value

Do I need to loop through it, or am I missing something else?

8 – Access user entity reference in a commerce-product twig

I have a field named field_intervenant who is a reference to my Users.
In my commerce-product twig I want to access to the description field of each of my ‘intervenant’, does anyone know the way to do it ?
Here is what I tried :


As long as some others but never gave me back something, and I can’t find it in my kint aswell, do I need to loop through it or am I missing something else?
Thanks for your help!

javascript – POST 422 (Unprocessable Entity)

I am having an error in my code when I try to upload a text (which is passed as input in a form by nextjs) to a mongodb database through my api (in fastapi). It puts 422 (Unprocessable Entity) but I don’t know why.
My code is divided into three parts, a first (the fronted) where I have the input and perform the fetch to try to send this to the api, my python code that uploads the data that is passed to mongodb and a routes method that is called by the fronted and which in turn is the one that calls the python code.
I leave my code here and I hope you can help me, thank you very much in advance.
–>nextjs code:

import { useForm } from 'react-hook-form';
import axios from 'axios';
import { useRouter } from 'next/router';

export default function Home() {
  const { register, handleSubmit, errors, reset } = useForm();
  const router = useRouter();
  async function onSubmitForm(name) {
    fetch('', {
      method: 'POST', 
      body: JSON.stringify(name), 
        'Content-Type': 'application/json'
    }).then(res => res.json())
    .catch(error => console.error('Error:', error))
    .then(response => console.log('Success:', response));
  return (
        <form onSubmit={handleSubmit(onSubmitForm)}>
            <input {...register("name")} type="text" name="name" required/>
            <button type="submit">Submit</button> 

–>Route api code:

from fastapi import APIRouter
from starlette.responses import RedirectResponse

from model.insert_date import MongoDB

router = APIRouter()

@router.post("pruebi/prueba", name="Insert the date in mongo", tags=("consultas"))
async def insertDate(start_date):
        db = MongoDB.__init__(dBName="HAR", collectionName="date")
        response = RedirectResponse(url='http://localhost:3000/paginaGrafica')
        return response

–>Python code to upload the data to mongo:

    import pymongo
    from pymongo import MongoClient
    import pandas as pd
    import json
    from datetime import date
except Exception as e:
    print("Some Modules are Missing ")

class MongoDB(object):

    def __init__(dBName=None, collectionName=None):
        client = MongoClient("localhost", 27017, maxPoolSize=50)

        DB = client(dBName)
        collection = DB(collectionName)

    def InsertDate(collection,start_date):

        data = ({'start_date': start_date})

        collection.insert_many(data, ordered=False)
        print("All the Data has been Exported to Mongo DB Server .... ")

entity system – How “smart objects” are implemented and actually work?

I’m drafting my game and implementing small stuff in it, but hit a roadblock. You see, for my game I would like for different items to behave the same or to share behavior, for instance, some items can be picked up and dropped to the floor, some items can get damaged and be repair while some only can get damage (the player cannot repair the item), some items can be use for a variety of different purposes (fire arms as weapons, frying pan as cooking tool and as a weapon), some items can get wet while others can get wet, catch fire and spread it further (or not; this is a reference to systemic games) and so on.

In my mind, the behavior must exist in the object and be abstracted from the player/AI/Other items nevertheless I’m lacking experience on how to go about this and I think that beside implementing a behavior there must exist also code that knows how to interact with such behavior, but this approach feels odd IMHO. In any case, I was asking around and The Sims was thrown in a reply, searching on the web found Living with The Sims’ AI: 21 Tricks to Adopt for Your Game, the trick 5 reads:

Each object has a public interface that broadcasts its functionality
to actors in the game. This is called advertising data in The Sims,
and contains a list of possible actions and what motives they satisfy.

If reading this correctly, it means that “smart objects” have a standard interface that actors can access to, right? My guess is that this interface covers everything behavior/systemic-wise that could happen in the game and the “actors” have code implemented that allow them to make use of this advertised interface, right?

Using Filter by an entity reference view with Rewrite Results gives “there are no entities matching” error

I’m using Drupal 9.2.
I have created entity reference views and use them as filter for entity reference fields (autocomplete widget).
When I’m using only “Content: Title” field everything works as expected. When using more fields either hidden (rewriting Title) or visible, I get “There are no entities matching (my selection)” error on save.

Does anybody have any idea why this is happening or how to debug?

8 – How to kernel test a custom formatter for an entity reference field type?

We have a custom field formatter for a string and an entity reference field type. While this works for testing the string field:

   $node = $this->createNode(('type' => 'page', 'field_id' => 'foo12345'));
   $build = $entity->field_id->view('default');
   $this->assertSame('Custom Label', $build('#title'));
   $this->assertSame('foo12345', $build(0)('#context')('value'));

The same does not work for an entity reference field type. $build is always empty:

    $node1 = $this->createNode(('type' => 'page', 'field_id' => 'foo12345'));
    $node2 = $this->createNode(('type' => 'page', 'field_ref_field' => ('target_id' => $node1->id())));
    $build = $node2->field_ref_field->view(('type' => 'my_plugin'));
    $this->assertSame('Custom Label', $build(0)('#title'));

I tried checking some of the core tests around reference field displays but came up short. Why does ->view() not return a build array (other than the cache metadata) for an entity reference field?

edit: it seems that in the test, this part of the formatter plugin returns nothing from ‘getEntitiesToView’ (but works on the actual site):

  public function viewElements(FieldItemListInterface $items, $langcode) : array {
    $elements = ();

    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
      $id = $entity->field_id->value;
      $uri = $entity->toUrl();
      $label = $this->formatLabel($id) . ' ' . $this->stripCharacters($id);

      $elements($delta) = (
        '#type' => 'link',
        '#title'=> $label,
        '#url'  => $uri,
        '#options' => $uri->getOptions(),

      $elements($delta)('#options') += ('attributes' => ());
      $elements($delta)('#cache')('tags') = $entity->getCacheTags();

    return $elements;