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