Search code examples
phpdrupal-8drupal-modulesdrupal-9

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: '\Drupal\birth_details\Form\BirthDetails'
  requirements: 
    _permission: 'access content'

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

<?php
    namespace Drupal\birth_details\Form;

    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;

    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' => '[email protected]',
              '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


Solution

  • 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 Drupal\birth_details\Form;
    
    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\Core\Entity\EntityTypeManager;
    use Drupal\Core\Session\AccountProxyInterface;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    class BirthDetails extends FormBase {
    
      /**
       * Current user account.
       *
       * @var \Drupal\Core\Session\AccountProxyInterface
       */
      protected $currentUser;
    
      /**
       * Node storage.
       *
       * @var \Drupal\node\NodeStorageInterface
       */
      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 = "[email protected]";
        $node->field_gender->value = "Male";
        
        $node->save();
      }
    }