I am now learning drupal 8 and I am struggling about 2 weeks to find an answer to this. I am trying to give to a reference field of the comment a default dynamic value. This value is the same with the referenced field of the article that the comment belongs. There are 2 ways to do this:
1) The easiest and cleaner way is to create a view that will show the specific article's field value that the current comment belongs. Easy but the issue is that although the view has only one result, that result cannot be set as default value. The user has to choose it or type in the autocomplete box in order for the value to appear. Is there any way to make that field been automatically completed and make it hidden? I would like the user not to be aware of that field
2) Here is another solution more difficult to me. https://www.drupal.org/node/1797100#comment-11792569 I should create a text widget for my field. I tried this but it is not working. The field has been created from the dashboard. I would like to keep things as cleaner as possible and not to create the field from the beggining with code. I believe that the text base,text widget and text formatter have already been created by core and that's why my text widget is not working. Should I in this case override (alter) the text widget and not create a new one and if yes how could I do that? https://api.drupal.org/api/drupal/core!modules!field!field.api.php/function/hook_field_widget_form_alter/8.2.x
function hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
// Add a css class to widget form elements for all fields of type mytype.
$field_definition = $context['items']->getFieldDefinition();
if ($field_definition->getType() == 'mytype') {
// Be sure not to overwrite existing attributes.
$element['#attributes']['class'][] = 'myclass';
}
}
where should I place the above function?
If you have an answer to 1) or 2) please leave a comment, I am totally desperate as this is very basic for the functionality of my website and I cannot find a solution...
Thank you