How to represent a list of entities within a table of the same entity in PostgreSQL?

There’s a couple of ways you can go about this but the most relational and normalized way would be to create a second table called UserFriendList with the columns UserId and FriendUserId which would store one row per Friend for each User. This table would be one-to-many from User.Id to UserFriendList.UserId but would also be able to help bridge the join back to the User table on UserFriendList.FriendUserId to User.Id to get all the User attributes of the friends. This kind of table is known as a bridge / junction / linking table.

Alternatively you can store the FriendList column directly on the User table as either a comma delimited list or in JSON, but these are both denormalized solutions, which will become harder to maintain changes, potentially lead to data redundancy, and will inflate the size of your User table which could make querying it less efficient.

entities – Enable Layout Builder via code

I figured it out. You can enable Layout Builder by running the following code in a custom module:

$entity_type = 'node';
$content_type = 'article';
$view_type = 'default';


Hopefully this helps someone else. Having to do it via the UI is painful if you have a lot of content types. I’m actually surprised this isn’t a Drush command yet. Oh well.


entities – Enable LayoutBuilder via code in D9

I have a question hopefully someone can help me with. I would like to enable Layout Builder via code, rather than using the GUI. I was following the instructions in this article (, but they don’t seem to work. They might be outdated. I’m on Drupal 9.1. Specifically, I’m having a hard time getting the following piece of code to work:

$entityViewDisplay = Drupal::entityTypeManager->getStorage('entity_view_display')

Can anyone help me understand it? I just keep getting a “null” response.

entities – Add new default value to existing content type

I’m currently on the latest version of Drupal 8. I have a content type called News and Articles. In this content type I have a field called Category which is a taxonomy term -> Entity reference field. When I first created this content type I added all my categories as default values.

Now 2 years later I want to add another default value to this content type. All the answers I’ve seen so far deal with making the change through the database. I wanted to see if there was a different option? Reason is because I have about 400 pages using this content type, really don’t want to make a new one.

Here a screenshot to the list I want to add to:

design – Actions (use cases) vs entities as domain objects entities

I have seen this talk (no need to watch it) on how to structure your Go applications several times and I still can’t conciliate with the way she strictly separates her domain objects. Her sample app is a beer review API and she separates her domain the actions an user would perform for a single beer entity but I struggle to understand how would she make the app more scaleble. What if the app would not also review beers but it is a complete management system where bars, beer-tasters, users, wines, wine-taster,etc. would need to come and interact with the beer reviews ?

Wouldn’t it me more conviniente or what are the drawbacks of defining your domain beer and couple all the tipical CRUD operations like reading, listing, etc. on that single package ?

The way she structures her domain:

(Unrelated) This is the app I’m trying to apply this concepts to:

search – Exract all node field values to json including reference entities with value

I am writing a module to export drupal’s content to another platform, the module provides a UI to manage content types and their fields to be shared on another platform via API.

So far i have managed to get node field values using this sample code

$nid = 4951;
$node = Drupal::entityTypeManager()->getStorage('node')->load($nid);
$data = ();
foreach ($node->getFields() as $name => $field) {
  $data($name)  = $field->getString();

the $field->getString(); however do not provides reference entity values and only provide ids.

The out of the above code is like:

{"nid":"4951","uuid":"0fae7e9b-d860-43f0-9559-a8bd6bab22b7","vid":"1272611","langcode":"en","type":"article","revision_timestamp":"1612303794","revision_uid":"1166","revision_log":"","status":"1","uid":"866","title":"xyz Chapter April Update","created":"1555961981","changed":"1612303794","promote":"0","sticky":"0","default_langcode":"1","revision_default":"1","revision_translation_affected":"1","moderation_state":"published","scheduled_transition_date":"","scheduled_transition_state":"","metatag":"","path":"/wisconsin-chapter-april-update, 17276, en","menu_link":"","body":"some this here, rich_text","field_article_author":"Wisconsin Chapter","field_article_chapter":"541","field_article_endnotes":"","field_article_questions_cta":"1","field_article_recommendation":"","field_article_recommended_link":"","field_article_related":"","field_article_related_link":"","field_article_resource_download":"","field_article_subhead":"Here's the latest news from the abc.","field_article_thumbnail":"","field_article_type":"news","field_blog_section":"","field_meta_tags":"","field_tax_article_type":"24, 28, 45","field_tax_audience":"","field_tax_breadcrumbs":"","field_tax_content_format":"50","field_tax_disease":"55, 56, 57, 58","field_tax_ga_type":"","field_tax_research_type":"","field_tax_topic":"90, 91, 92, 93, 94, 108, 109, 111"}

Scroll last and see for example field_tax_topic

Is there a direct or indirect way of automatically detecting reference entity field and extracting its values, also it should be dynamic solution and that must work with new field types as well.

Any pointer or direction to do it in the right way will help!

entities – Autofill drupal field in edit page

I am not sure if this was posted earlier, but I would be specific and conscise.

I am writing a Drupal module to store post meta in the “Node edit” page field. Just basic field, in node edit page.

What I am Looking for
Upon inserting the title of the node, I have multivalued field(3 values to take), the first one gets automatically populated with the title of the page.

And when I have set the url of the node, the field (2nd) value also gets populated… and like so.

How to implement the above? With Javascript if possible, that would be more native. Or Drupal Jquery API.

Use for the above Module I am building plain meta field for my website.

I can build Module, and know about JavaScript, JQuery, but I do not know how to put all together to make the above.

mysql – Checking if entities match an id in on relation where it could show up in either of two columns

The problem

I’m trying to make a page for a website (with PostgreSQL database) that allows the owner of a group to add new members from their friends list.

Given the owner_id of a Group its group_id I need to retrieve only the user_ids from users who are both friends with the owner, and not in the group.

The relations being queried

I need to use the following relations

  • UserFriend: Stores two user_ids to connect those two users from the User relation to each other as friend.
  • UserGroup: Stores a user_id and group_id to connect the Group relation to its members in the User relation.

The two relations are described as follows:


  Column   |  Type   | Collation | Nullable | Default 
 user_id_a | integer |           | not null | 
 user_id_b | integer |           | not null | 


  Column  |  Type   | Collation | Nullable | Default 
 user_id  | integer |           | not null | 
 group_id | integer |           | not null | 

My attempt so far with example data

For example, given the data below, I want to find all users that are friend with user 3, and not in group 3.

SELECT user_id_a, user_id_b FROM UserGroup UG, UserFriend UF 
    WHERE (UF.user_id_a = 3 AND UF.user_id_b != UG.user_id)
       OR (UF.user_id_b = 3 AND UF.user_id_a != UG.user_id)
       AND UG.group_id = 3 GROUP BY user_id_a, user_id_b;

Expected Result

 user_id_a | user_id_b 
         1 |         3

Even better if it could just show something like


Actual Result

 user_id_a | user_id_b 
         1 |         3
         3 |         2
         3 |         4

Example data


 user_id_a | user_id_b 
         1 |         2
         1 |         3
         1 |         4
         3 |         4
         3 |         2


 user_id | group_id 
       1 |        1
       2 |        1
       3 |        1
       4 |        1
       1 |        2
       2 |        3
       3 |        3
       4 |        3


I’m fairly certain that the issue has something to do with the way I’m handling the fact that the user_id I’m trying to match could be in either column of UserFriend, but I’m not sure how to fix it. I’ve also tried using JOINs without any luck.

design – Can entities in Clean Architecture use boundary objects?

Let’s say that we are working on some kind of school management system and we want to drop (remove) a course from a particular student during the enrollment process. We might have an enrollment entity that might look something like this:

class Enrollment(Entity):
    def __init__(self, course, student, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.course = course
        self.student = student

    def drop(self):
        # Some code

The use case that is responsible for performing the “drop” operation could look something like the following:

class DropCourse(UseCase):
    def __init__(self, enrollment_gateway):
        self.enrollment_gateway = enrollment_gateway
    def execute(self, request):
        enrollment = self.enrollment_gateway.get_by_id(request.enrollment_id)
        if not enrollment:
            raise EnrollmentNotFoundError
        enrollment.drop()         # Source of my question

In this example, I’m calling the drop method of the enrollment entity, but I’m having difficulty deciding how to go about executing the logic that will perform this action. I have thought of three possible solutions to this.

One solution is to pass the ‘CourseDropper’ object to the constructor of the enrollment entity. When the drop method of the entity is called, use the course_dropper object to do the work. The problem I see with this solution is that over time, the constructor of the entity might grow if I add more and more dependencies to it that perform similar operations.

Another solution can be to add a “CourseDropper” object to the constructor of the use case, that has a method called ‘drop_enrollment’ that takes an enrollment as an argument. This object could then use whatever database we happen to be using and mark the enrollment as ‘dropped’.

The third solution, which is the one I’m currently leaning towards, is to pass the ‘CourseDropper’ object to the drop method of the entity from the use case itself. It would be really easy to implement, because all the entity has to do is call the drop method of the course dropper and pass itself in as an argument.

I’m not sure if the last solution violates any of the clean architecture or SOLID principles. Which of these solution would be better in terms of design and architecture?

8 – Creating Parent-Child Entities

Is there a way to create parent-child entities in Drupal 8? I’m trying to create a structure where the top entity is for County, and the next level entity is for departments, and next level would be staff. There will be different counties so the departments created at the second level entity will only be tied to the county it’s created for, and same goes for staff which will only be associated to the the 2nd level entity(departments). So Let’s say department 1 on County 1 will have different staff from department 2 of the sane county 1.

Also how will the path for this be programmed? Where in Drupal or what files should be created or modified so that it will structured like myowndrupalxx.xxxmodulecounty1department2staff1 to display staff information for staff #1 of department 2 of county 1?

Lastly, can the database tables have a key for each table, so let’s say for the Staff table being at the 3 level, it will have 3 keys, County, Department, and Staff, vs. the County table will have 1 key County. This way it does follow the parent-child or relational database structure.

I am not a very skilled programmer in Drupal so please provide your explanations in lay man terms as much as possible.