我正在使用 drupal 8.9.*,我想将数据从自定义模块保存到内容类型,以便我可以看到在 Drupal 的公共内容列表页面中输入的数据。
我不知道如何将数据保存到内容类型,我尝试过使用$node的对象来保存它(以及我尝试过的其他一些方法,但后来才知道它已被弃用)。我还传递了内容类型的机器名称。我在哪里出错了,所有 Drupal 文档都被扭曲了,很难找到正确的 8 版本 || 9. 这是我的代码。
路由数据文件,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'
我的表格 BirthDetails.php,(硬编码一些值用于测试目的)
<?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;
}
}
最后自定义内容类型的机器名称是birth_data,我对表单唯一ID和节点创建类型使用相同