Skip to content
Advertisement

Drupal 8 or 9 Save data to the content type from a custom module

I am using drupal 8.9.*, I want to Save data to the content type from a custom module so that i can see the data entered in Drupal’s common content list page.

I dont know how to save data to the content type, I have tried using object of $node to save it (and some other method I tried but later came to know its deprecated). I have also passed machine-name of the content type. Where I am going wrong on this, all the Drupal documentation is distorted, hard to find a correct version of 8 || 9. Here is my code.

Routing data file, birth_details.routing.yml

birth_details.newreading:
  path: '/new-reading'
  defaults: 
    _title: 'Enter the birth details for reading'
    _form: 'Drupalbirth_detailsFormBirthDetails'
  requirements: 
    _permission: 'access content'

My form BirthDetails.php, (hard coded some values for testing purpose)

<?php
    namespace Drupalbirth_detailsForm;

    use DrupalCoreFormFormBase;
    use DrupalCoreFormFormStateInterface;

    class BirthDetails extends FormBase {

        public function getFormId(){
            return 'birth_data';
        }

        public function buildForm(array $form, FormStateInterface $form_state){

            $form['title'] =  [
                '#type' => 'textfield',
                '#description' => $this->t('Enter your name here!'),
            ];
            $form['field_birth_date'] =  [
                '#type' => 'textfield',
                '#description' => $this->t('Enter your field_birth_date here!'),
            ];
            $form['field_birth_location'] =  [
                '#type' => 'textfield',
                '#description' => $this->t('Enter your field_birth_location here!'),
            ];
            $form['field_email_id'] =  [
                '#type' => 'textfield',
                '#description' => $this->t('Enter your field_email_id here!'),
            ];
            $form['field_gender'] =  [
                '#type' => 'textfield',
                '#description' => $this->t('Enter your field_gender here!'),
            ];

            $form['actions']['#type'] = 'actions';
            $form['actions']['submit'] = [
                '#type' => 'submit',
                '#value' => $this->t('Save data'),
                
            ];

            return $form;
        }

        public function submitForm(array &$form, FormStateInterface $form_state){
            $node = new stdClass();
            $node = Node::create([
              'type' => 'birth_data',
              'title' => 'first lastname',
              'field_birth_date' => '23 NOV 2020 11:11:11',
              'field_birth_location' => 'Osaka',
              'field_email_id' => 'test@myid.com',
              'field_gender' => 'Male',
            ]);
            $node->save();  
            echo "<pre>";
            print_r($form_state);
            exit;

        }
    }

and finally machine name of the custom content type is birth_data, i have used the same for form unique id and node create type type

Advertisement

Answer

Baikho‘s answer is nice. It’s still better to avoid the use of static calls (such as Node::create()) ; we can easily do this injecting dependencies in the constructor.

<?php

namespace Drupalbirth_detailsForm;

use DrupalCoreFormFormBase;
use DrupalCoreFormFormStateInterface;
use DrupalCoreEntityEntityTypeManager;
use DrupalCoreSessionAccountProxyInterface;
use SymfonyComponentDependencyInjectionContainerInterface;

class BirthDetails extends FormBase {

  /**
   * Current user account.
   *
   * @var DrupalCoreSessionAccountProxyInterface
   */
  protected $currentUser;

  /**
   * Node storage.
   *
   * @var DrupalnodeNodeStorageInterface
   */
  protected $nodeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(
    EntityTypeManager $entity_type_manager,
    AccountProxyInterface $current_user
  ) {
    $this->currentUser = $current_user;
    $this->nodeManager = $entity_type_manager->getStorage('node');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('current_user')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId(){
    return 'birth_data';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['title'] =  [
      '#type' => 'textfield',
      '#description' => $this->t('Enter your name here!'),
    ];
    $form['field_birth_date'] =  [
      '#type' => 'textfield',
      '#description' => $this->t('Enter your field_birth_date here!'),
    ];
    $form['field_birth_location'] =  [
      '#type' => 'textfield',
      '#description' => $this->t('Enter your field_birth_location here!'),
    ];
    $form['field_email_id'] =  [
      '#type' => 'textfield',
      '#description' => $this->t('Enter your field_email_id here!'),
    ];
    $form['field_gender'] =  [
      '#type' => 'textfield',
      '#description' => $this->t('Enter your field_gender here!'),
    ];

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save data'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $node = $this->nodeManager->create([
      'type' => 'birth_data',
      'title' => $values['title'],
      'uid' => $this->currentUser->id(),
      'status' => 1,
    ]);

    $node->field_birth_date->value = "23 NOV 2020 11:11:11";
    $node->field_birth_location->value = "Osaka";
    $node->field_email_id->value = "test@myid.com";
    $node->field_gender->value = "Male";
    
    $node->save();
  }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement