Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By tarnus on
I'm building a custom form for one of my content types. I want to be able to import some of the existing fields and save out the node programmatically.
On drupal 7 I always used the field_attach_form function to do this for me. It looks like that function has been removed in Drupal 8. Can anyone give me some pointers on how I can do the same thing and include fields from a content type in my custom form?
I've scoured the internet looking for this all day, any help would be appreciated.
Thanks
Comments
You could use the following
You could use the following code:
This code works for me in
This code works for me in Drupal 9 apart from following i.e
a) Variable $node on line 2 should be replaced with $entity as called here
$items = $entity->get('body''); //Returns the FieldItemsList interface
b) Add this line at the end otherwise it throws strange error i.e
$form['#parents'] = [];
c) Also we can render most of our content type fields by using foreach loop e.g
// Content type field array.
$field_array = [
'title',
'field_registered_address',
'field_billing_address',
'field_shipping_address',
];
// Loop
foreach ($entity_form_display->getComponents() as $name => $component) {
if(in_array($name, $field_array)){
$widget = $entity_form_display->getRenderer($name);
if (!$widget) {
continue;
}
$items = $entity->get($name);
$items->filterEmptyItems();
$form[$name] = $widget->form($items, $form, $form_state);
$form[$name]['#access'] = $items->access('edit');
}
$form['#parents'] = [];
}
You use the form display
You use the form display object for that.
See EntityInlineForm in inline_entity_form for an example that has validation and submission as well.