I can't find the right hook to override the Entity Reference field settings on Edit Entity form, using Views Entity Reference, regarding to Views arguments, before the Views is executed for loading available items. Can anybody suggest me the right method?
As example on Default Drupal setup, on "Basic page" node I have the "Select list" entity reference to "Article" Node (which have "Tags" field), and have configured in it the Entity Reference Views that filter articles, with a single argument (Tags id = 1), like this:
Screenshot of the field settings »
So, I need to replace the View argument from "1" to "2" programmatically, before the form loads the available values. Ideally it should be loaded from another field of "Basic page" entity, an placed to first Views argument in Entity Reference field.
Screenshot of the Add Node form with this fields »
So basically I need to reload "Related article" drowdown with View argument = 2 via Ajax, when in the "Articles with this tag only" field the value is changed from "Tag1" to "Tag2".
This can be done via altering the "Field third party settings" of the field and changing the Views argument value from "1" to "2" programmatically, but it should be done before the Views is executed, not after.
I've already tried hook_form_alter(), hook_field_widget_form_alter(), hook_field_widget_complete_form_alter(), but all of them have the "Select list" values already loaded!
Here is the example of implementation using hook_form_alter():
<?php
function murz_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if($form_id !== 'node_page_edit_form') return;
$form['field_articles_tag']["widget"]["#ajax"] = array(
"callback" => "_murz_form_ajax_alter",
"event" => "change",
"wrapper" => $form['#id'],
);
$form['field_article']['widget'][0]['target_id']['#selection_settings']['view']['arguments'][0] = 2;
}
function _murz_form_ajax_alter($form, FormStateInterface $form_state) {
$form['field_article']['widget'][0]['target_id']['#selection_settings']['view']['arguments'][0] = 2;
return $form;
}But it doesn't work, because in the time of the hook Drupal has already executed the Views and have put the available values to the Select dropdown.
I also can use hook_views_pre_execute() but in it the whole context of the entity form is lost, but I need to get values from other form fields. So the solutions via loading node from the Request or database don't suite, because I need to get the unsaved values, entered into the Form, via FormState of the EntityForm.
Which other hook can I try to replace the View argument?
Comments
Alternatively, you can
Alternatively, you can implement dependent fields without using a view. See the example below.
The screenshot of the "Manage fields" page: https://www.drupal.org/files/dependent_entity_reference_fields_example-1...