9 – Programmatically enable the entity view display

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';

Drupallayout_builderEntityLayoutBuilderEntityViewDisplay::load("{$entity_type}.{$content_type}.{$view_type}")
  ->enableLayoutBuilder()
  ->setOverridable()
  ->save();

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.

Source: https://www.drupal.org/project/drupal/issues/3158916

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.

mysql – Entity Relationship Diagram for Grade Calculator

I was wondering if anyone would be able to review my Grade Calculator for a course ERD? I’m looking for ways to improve the current design (if any improvements need to be made that is) and if anyone could review the current MySQL query which is there. In order for this to be reviewed I was told I needed an SQL query to accompany it.
enter image description here

SELECT
    `yearGroup`.`id` AS `year_group_id`,
    `yearGroup`.`year` AS `year_group`,
    CONCAT(
    TRUNCATE
        (
            COALESCE(
                SUM(
                    `assignment`.`percentage_achieved` *(
                        `assignment`.`percentage_weighting` / 100
                    )
                ),
                0
            ) /(
            SELECT
                COUNT(*)
            FROM
                `unit`
            WHERE
                `unit`.`year_group_id` = `yearGroup`.`id`
        ),
        2
        ),
        '%'
) AS `grade`
FROM
    `assignment`
RIGHT JOIN `unit` ON `unit`.`id` = `assignment`.`unit_id`
RIGHT JOIN `yearGroup` ON `yearGroup`.`id` = `unit`.`year_group_id`
WHERE
    `yearGroup`.`course_id` = 1
GROUP BY
    `yearGroup`.`id`

9 – Book node entity to set child nodes access permissions

I’m working on a simple permissions module for books. This module should make a book with its child nodes private. The toplevel content type is called reader than I have a child content type edition and a child content type of edition is article.

In the content type reader I have a boolean field called Private (field_private). This can be turned on to make the node private.

My module is inspired by the Private Content module, this basically covers what I want. The only thing I need is to also set permissions of the child nodes.

The code I have written so far seems to work. But what I have to do now is save the toplevel reader and than save all child nodes manually. I’m wondering if it is possible to automatically set the permissions of the child nodes when the toplevel reader (parent) node is saved?

My guess is I have to iterate trough the children and change their views access permission. But how?

My code till now:
In my own private_content module I have a private_content.module file.

In this file I have a hook_node_grants function:

function private_content_node_grants(AccountInterface $account, $op){
  $grants = array();

  if ($op == 'view') {
    if (!$account->isAnonymous()) {
      $grants('private_author') = array($account->id());
    }
    if ($account->hasPermission('access private content')) {
      $grants('private_view') = array(PRIVATE_GRANT_ALL);
    }
  }
  return $grants;
}

And I have a hook_node_access_records function:

function private_content_node_access_records(NodeInterface $node){
  $grants = array();

  //check content type
  if ($node->bundle() == 'reader') {
    //if reader
    $book = $node;
  } else if ($node->bundle() == 'edition' || $node->bundle() == 'article') {
    //if edition or article
    //get parent book
    $book = Node::load($node->book('bid'));
  }

  //get private state from book
  $private = $book->field_private->get(0)->value;

  if ($node->status && $private == 1) {
    // Grant read access to users with 'access private content'.
    $grants() = array(
      'realm' => 'private_view',
      'gid' => PRIVATE_GRANT_ALL,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 0,
    );

    // Grant read access to the owner, but not ANONYMOUS user.
    if (!$node->getOwner()->isAnonymous()) {
      $grants() = array(
        'realm' => 'private_author',
        'gid' => $node->getOwnerId(),
        'grant_view' => 1,
        'grant_update' => 0,
        'grant_delete' => 0,
        'priority' => 0,
      );
    }

    // Otherwise, deny read access for private nodes.
  }

  return $grants;
}

When to use entity and when to use DTOs

Also, that the aim beneath DTO’s is to gather in a single response as much info as necessary for clients to save calls to the server.

That’s not the aim of a DTO. It’s a side effect that you can more easily achieve when already using DTOs. But using DTOs and bundling data are two different design decisions that should each be made for their own reasons.

What I am having a hard time with is understanding what is the best situation to use DTO’s compared to use of entity?

In essence, an “entity” is just shorthand for “the DTO between the data store and our persistence logic”. It’s a DTO just like any other DTO, meant to be used for data transfer between two specific points.

Depending on the two layers that are passing data to one another, these DTOs tend to get a contextual nickname:

        ┌───────────┐    ┌──────┐    ┌───┐
DB  ─┬─►│Persistence│◄─┬─┤Domain├─┬─►│Web├─┬─►  END USER
     │  └───────────┘  │ └──────┘ │  └───┘ │
     │                 │          │        │
 "Entity"           "Domain  "Business   "Model"
                     Object"    Object"

On a technical level, all of these intermediary objects are DTOs. We just give them different names so it’s easier to talk about them and understand what someone means when they say “entity”, without forcing them to have to say “the DTO between the database and the persistence layer”.

This also inherently explains why/when to use an “entity” specifically. Entities are used as a means of communication between the database and the persistence logic. If you’re passing data between different layers, then it shouldn’t be handled by an entity.

Very important note Your specific architecture will change what layers you have and what the DTOs are commonly called. I used a DDD example which relies on an ORM here, but you might be using a different architecture altogether, which would mean you need to adapt the names accordingly.

For example, if you don’t use an ORM and write SQL queries manually, then you might refer to the Persistence->Domain DTO as the “entity”, since you don’t actually have a DTO class between DB->Persistence.

For example when I am trying to save new user in database should I use DTO or entity?

It’s a staged process.

  1. The web controller receives a model, maps it to a business object, and passes it to the domain.
  2. The domain receives the business object, translates it into a domain object, and performs the operation. At some point, this means passing (some of) the data to the persistence layer.
  3. The persistence layer receives the domain object, maps it to an entity, and sends that entity on to the database.
  4. (Commonly hidden step: your ORM maps your entity to a SQL command and sends that to the database)

For retrieving data from database and communicating with frontend in that case only use of DTO’s?

This is the same staged process, albeit in the opposite order.

Hoewever, there may be contextual differences. For example, if your retrieved data doesn’t retrieve full entities (i.e. table rows), but instead is more of a “report” of very specific data columns (maybe even some calculated columns), then this object returned from the DB is generally not even called an “entity”.

“Entity” generally refers to the class that represents a full table row.

8 – JSON:API error unprocessable entity status 422 entity_id this value should not be null

I’m trying to post a flag with JSON:API but I’m getting the following error:

"errors": [
    {
        "title": "Unprocessable Entity",
        "status": "422",
        "detail": "entity_id: This value should not be null.",
        "source": {
            "pointer": "/data/attributes/entity_id"
        }
    }

I’m very confused because in the data I’m posting, the entity_id is definitely included…

javascript – Error al guardar datos de un form modal en entity framework y AJAX

tengo un proyecto personal y me estaba guiando con otro proyecto que consegui, pero no logro hacer que guarde los datos, esta hecho en asp.net AJAX MVC con entity en sql server, no tuve promelas al listar los datos en DATATABLE, el error solamente es al guardar y al traer los datos de la tabla que tengo

<div class="modal fade" id="FormModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Creacion de Garantias</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <div class="row">
                <div class="col-sm-12">


                    <input type="hidden" id="txtIdCliente" />



                    <div class="row">
                        <div class="col">
                            <label for="txtIDC">Identificacion de Cliente:</label>
                            <input type="text" class="form-control" placeholder="IDC" id="txtIDC">
                        </div>

                        <div class="col">
                            <label for="txtNombre">Nombre de Cliente:</label>
                            <input type="text" class="form-control" placeholder="Nombre" id="txtNombre">
                        </div>




                    </div>

                    <div class="row">


                        <div class="col">
                            <label for="txtLat">Latitud:</label>
                            <input type="text" class="form-control" id="txtLat">
                        </div>

                        <div class="col">
                            <label for="txtLong">Longitud:</label>
                            <input type="text" class="form-control" id="txtLong">
                        </div>




                    </div>

                    <div class="row">


                        <div class="col">
                            <label for="txtUbicacion">Ubicacion</label>
                            <input class="form-control" type="text" id="txtUbicacion" />

                        </div>

                        <div class="form-row align-items-center">
                            <div class="col-auto my-1">
                                <label class="mr-sm-2" for="txtTipoReg">Tipo de Registro</label>
                                <select class="custom-select mr-sm-2" id="txtTipoReg">

                                    <option value="1">Garantia</option>
                                    <option value="2">Agricola</option>

                                </select>
                            </div>
                        </div>


                    </div>



                    <div class="row">


                        <div class="col">
                            <label for="txtNumG">Num. Gta</label>
                            <input class="form-control" type="text" id="txtNumG" />

                        </div>


                        <div class="form-row align-items-center">
                            <div class="col-auto my-1">
                                <label class="mr-sm-2" for="txtTipPre">Tipo de Predio:</label>
                                <select class="custom-select mr-sm-2" id="txtTipPre">

                                    <option value="1">Agricola</option>
                                    <option value="2">nose</option>

                                </select>
                            </div>
                        </div>



                    </div>


                    <div class="row">

                        <div class="form-row align-items-center">
                            <div class="col-auto my-1">
                                <label class="mr-sm-2" for="txtConUs">Tipo de Predio:</label>
                                <select class="custom-select mr-sm-2" id="txtConUs">

                                    <option value="1">Propietario</option>
                                    <option value="2">alquiler</option>

                                </select>
                            </div>
                        </div>

                        <div>
                            <label for="txtFecha">Fecha:</label>
                            <input class="form-control" type="date" id="txtFecha" />

                        </div>


                    </div>


                    <div class="row">

                        <div class="col">
                            <label for="txtValC">Valor Comercial:</label>
                            <input class="form-control" type="text" id="txtValC" />

                        </div>

                        <div class="col">
                            <label for="txtSupTo">Superficie Total:</label>
                            <input class="form-control" type="text" id="txtSupTo" />

                        </div>

                        <div class="col">
                            <label for="txtUS">US$/Ha:</label>
                            <input class="form-control" type="text" id="txtUS" />

                        </div>




                    </div>



                    <div class="row">


                        <div class="col">
                            <label for="txtSupAg">Sup. Agricola Habilitadas:</label>
                            <input class="form-control" type="text" id="txtSupAg" />

                        </div>


                        <div class="col">
                            <label for="txtSupGan">Sup. Ganadera Habilitadas:</label>
                            <input class="form-control" type="text" id="txtSupGan" />

                        </div>


                    </div>




                    <div class="row">


                        <div class="col">
                            <label for="txtObs">Observaciones:</label>
                            <input class="form-control" type="text" id="txtObs" />

                        </div>

                    </div>

                </div>
            </div>


        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
            <button type="button" class="btn btn-primary" onclick="Guardar()">Guardar</button>
        </div>
    </div>
</div>

Este es mi form

Este es mi codigo en controlador, creo que puede estar mal, no tengo experiencia en ENTITY, por un momento pense que se debia a los tipos de datos del formulario

 public JsonResult Guardar(Clientes oCliente)
    {

        bool respuesta = true;
        try
        {

            if (oCliente.idCliente == 0)
            {
                using (GeolocaEntities db = new GeolocaEntities())
                {
                    db.Clientes.Add(oCliente);
                    db.SaveChanges();
                }
            }
            else
            {
                using (GeolocaEntities db = new GeolocaEntities())
                {
                    Clientes tempCliente = (from c in db.Clientes
                                            where c.idCliente == oCliente.idCliente
                                            select c).FirstOrDefault();

                    tempCliente.IDC = oCliente.IDC;
                    tempCliente.Nombre = oCliente.Nombre;
                    tempCliente.Ubicacion = oCliente.Ubicacion;
                    tempCliente.Latitud = oCliente.Latitud;
                    tempCliente.Longitud = oCliente.Longitud;
                    tempCliente.TipoReg = oCliente.TipoReg;
                    tempCliente.NumGa = oCliente.NumGa;
                    tempCliente.TipoPre = oCliente.TipoPre;
                    tempCliente.CondUso = oCliente.CondUso;
                    tempCliente.avaluo = oCliente.avaluo;
                    tempCliente.valCom = oCliente.valCom;
                    tempCliente.supTot = oCliente.supTot;
                    tempCliente.supUsa = oCliente.supUsa;
                    tempCliente.SupAgHab = oCliente.SupAgHab;
                    tempCliente.SupGaHab = oCliente.SupGaHab;
                    tempCliente.obs = oCliente.obs;

                    db.SaveChanges();
                }

            }
        }
        catch
        {
            
           respuesta = false;

        }

       return Json(new { resultado = respuesta }, JsonRequestBehavior.AllowGet);

Estas son las Funciones en Ajax que intento usar

<script>
    var tabla_persona;
     $(document).ready( function () {
         tabla_persona = $('#myTable').DataTable({
             "ajax": {
               
                "url": "@Url.Action("Listar", "Garantia")",
                "type": "GET",
                "datatype": "json"
            },
            "columns": (
                { "data": "IDC" },
                { "data": "Nombre" },
                { "data": "Ubicacion" },
                { "data": "Latitud" },
                { "data": "Longitud" },

                /*
                { "data": "TipoReg" },
                { "data": "NumGa" },
                { "data": "TipoPre" },
                { "data": "CondUso" },
                { "data": "avaluo" },
                { "data": "valCom" },
                { "data": "supTot" },
                { "data": "supUsa" },
                { "data": "SupAgHab" },
                { "data": "SupGaHab" },
                { "data": "obs" },
               */


             //   { "data": "Nombre" },
                {
                    "data": "idCliente", "render": function (data) {
                        return "<button class='btn btn-primary btn-sm' type='button' onclick='abrirModal(" + data + ")'><i class='fas fa-pen'></i></button>" +
                            "<button class='btn btn-danger btn-sm ml-2' type='button' onclick='Eliminar(" + data + ")'><i class='fa fa-trash'></i></button>"
                 },
                    "orderable": false,
                    "searchable": false,
                    "width": "150px"
                }
            ),
            dom: 'Bfrtip',
            buttons: (
                {
                    text: 'Agregar Nuevo',
                    attr: { class: 'btn btn-success btn-sm' },
                    action: function (e, dt, node, config) {
                        abrirModal(0)
                    }
                }
             ),
             "language": {
                 "url": "@Url.Content("~/Content/datatable/idioma/datatable.es-ES.json")"
             }

        });
    });


    function abrirModal($idcliente) {

        $("#txtIdCliente").val($idcliente);
        if ($idcliente != 0) {

            jQuery.ajax({
                url: "@Url.Action("Obtener","Garantia")" + "?idcliente=" + $idcliente,
                type: "GET",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {

                    if (data != null) {

                        $("#txtIDC").val(data.IDC);
                        $("#txtNombre").val(data.Nombre);
                        $("#txtLat").val(data.Latitud);
                        $("#txtLong").val(data.Longitud);
                        $("#txtUbicacion").val(data.Ubicacion);
                        $("#txtTipoReg").val(data.TipoReg);
                        $("#txtNumG").val(data.NumGa);
                        $("#txtTipPre").val(data.TipoPre);
                        $("#txtConUs").val(data.CondUso);
                        $("#txtFecha").val(data.avaluo);
                        $("#txtValC").val(data.valCom);
                        $("#txtSupTo").val(data.supTot);
                        $("#txtUS").val(data.supUsa);
                        $("#txtSupAg").val(data.SupAgHab);
                        $("#txtSupGan").val(data.SupGaHab);
                        $("#txtObs").val(data.obs);

                    }

                }
            });
        } else {
          

            $("#txtIDC").val("");
            $("#txtNombre").val("");
            $("#txtLat").val("");
            $("#txtLong").val("");
            $("#txtUbicacion").val("");
            $("#txtTipoReg").val("");
            $("#txtNumG").val("");
            $("#txtTipPre").val("");
            $("#txtConUs").val("");
            $("#txtFecha").val("");
            $("#txtValC").val("");
            $("#txtSupTo").val("");
            $("#txtUS").val("");
            $("#txtSupAg").val("");
            $("#txtSupGan").val("");
            $("#txtObs").val("");
        }

        $('#FormModal').modal('show');

    }

    function Guardar() {
        var $data = {
            oCliente: {
                idCliente: parseInt($("#txtIdCliente").val()),
                IDC: $("#txtIDC").val(), 
                Nombre: $("#txtNombre").val(),
                Ubicacion: $("#txtLat").val(),
                Latitud: $("#txtLong").val(),
                Longitud: $("#txtUbicacion").val(),
                TipoReg: $("#txtTipoReg").val(),
                NumGa: $("#txtNumG").val(),
                TipoPre: $("#txtTipPre").val(),
                CondUso: $("#txtConUs").val(),
                avaluo: $("#txtFecha").val(),
                valCom: parseInt($("#txtValC").val()),
                supTot: parseInt($("#txtSupTo").val()),
                supUsa: parseInt($("#txtUS").val()),
                SupAgHab: parseInt($("#txtSupAg").val()),
                SupGaHab: parseInt($("#txtSupGan").val()),
                obs: $("#txtObs").val(),


            }
        }

        jQuery.ajax({
            url: "@Url.Action("Guardar", "Garantia")",
            type: "POST",
            data: JSON.stringify($data),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {

                if (data.resultado) {
                    tabla_persona.ajax.reload();
                    $('#FormModal').modal('hide');
                } else {
                    alert("No se pudo guardar los cambios");
                }
            },
            error: function (error) {
                console.log(error)
            },
            beforeSend: function () {

            }
        });

    }

Aqui me arroja el Else del metodo GUARDAR, por lo tanto no me esta guardando nada

database design – MySQL how can you reach an entity that has no relations with any other entity, from another entity?

Assuming we have these entities:

Flight(flightID(PK), from, to, distance)

Aircraft (aircraftID(PK), name)

Certificate(aircraftID (PK), employeeID(PK)) foreign keys: aircraftID REFERENCES Aircraft(aircraftID), employeeID REFERENCES Employee (employeeID)

Employee(employeeID, name, salary)

My question is, is it possible to select all aircraft pilots for the flights that go from “A”city to “B”city by using SELECT, PROJECT, JOIN keywords etc.. If so, how?

A pilot is an employee who has a certificate for an aircraft.

I don’t think this is possible since flight entity does not have any foreign key relationship with any other entity. But this is a question from my midterm and my professor does not agree with me.

entities – How to use “content entity” type in a View?

Add a views_data handler to the entity type. Either the core standard EntityViewsData

content_entity_example/src/Entity/Contact.php

  *   handlers = {
  *     "views_data" = "DrupalviewsEntityViewsData",

or a custom handler:

content_entity_example/src/Entity/Contact.php

  *   handlers = {
  *     "views_data" = "Drupalcontent_entity_exampleEntityContactViewsData",

content_entity_example/src/Entity/ContactViewsData.php

<?php

namespace Drupalcontent_entity_exampleEntity;

use DrupalviewsEntityViewsData;

/**
 * Makes the content_entity_example entity available to Views
 *
 * @ingroup content_entity_example
 */
class ContactViewsData extends EntityViewsData {

  /**
   * {@inheritdoc}
   */
  public function getViewsData() {
    $data = parent::getViewsData();

    // $data from the parent is enough to make it work but modify as required.

    // Give it a more description name in the dropdown when creating a new view.
    $data('contact')('table')('base')('title') = $this->t('Content Entity Example Contact');

    // Make the Name field appear to Views as Last Name
    $data('contact')('name')('title') = $this->t('Last Name');

    return $data;
  }

}

To apply this code to the example module use the patch from this issue https://www.drupal.org/project/examples/issues/2725833