0

I am new to Drupal. Now, learning drupal 8.

I have added a module from command drupal generate:module named 'my_module`

I have added an entity for my_module:

drupal generate:entity:content
//bundle "NO"

What I want

I would like to add/insert in to this entity on every Node add/update.

I have got this code into my my_module.module

function my_module_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state)
{
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'my_module_node_form_submit';
      }
    }
}

function my_module_node_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
   $node = $form_state->getFormObject()->getEntity();

   $url = $node->field_website->uri; //my node field
   $name = $node->field_com->value; //my node field

   //HOW TO ADD $url, $name IN TO above custom ENTITY
}

My entity table:

1: my_module

id
uuid
langcode

2: my_module_field_data

id PrimaryIndex
langcode PrimaryIndex
name
url
status
created
changed
default_langcode Index

Please help.

1 Answer 1

2

You can do like this

Suppose your entity name is my_entity.

<?php
use Drupal\my_module\Entity\my_entity;

function my_module_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state)
{
    foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
            $form['actions'][$action]['#submit'][] = 'my_module_node_form_submit';
        }
    }
}

function my_module_node_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $node = $form_state->getFormObject()->getEntity();

    $url = $node->field_website->uri;
    $name = $node->field_com->value;

    // Now to check    
    //Generate my_entity entity.
    $entity = my_entity::create(
               [
                 'label' => 'token',
                 'id' => $node->id(),
                 'status' => true,
                 'name'=> $url,
                  "url" => $name,
                  "created" => time()
               ]
         );
    $entity->save();
}

To update enity:

$entity = my_entity::load('content entity id');
$entity->set("name", 'name value');
$entity->set("url", 'url value');
$entity->save();
0

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.