'Drupal9: Saving form as node in SQL (custom module example)
i develop a custom module with forms to save data in SQL-Datebase. I want to use for that the node-structure.
Normal SQL-savings for example table works but not for the node-tables. Any idea what is going wrong?
This ist my Code for saving, which works in non-node-tables:
public function submitForm(array &$form, FormStateInterface $form_state) { $connection = \Drupal::service('database');
$result = $connection->insert('node.node__body')
->fields(['body_value'])
->values([
'body_value' => 'text for body',
])
->execute();
$form_state->setRedirect('modulname.form');
}
Solution 1:[1]
Use Entity API in Drupal to manipulate or create a node.
In your case,
$node = \Drupal::entityTypeManager()->getStorage('node')->create(
[
'type' => 'page',
'title' => 'New Basic Page',
'body' => 'text for body'
]
);
Here, type
is the content type machine name. Don't forget to update with your own. Also you probably want to inject the entity_type.manager service and use in the code.
Get more info here: Working with entities in Drupal
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Harish ST |