0

I have a form with 3 fields: viticultor, variedad and parcela. All this fields are webform_entity_select widgets. My goal is refresh the values (if possible, using the entity reference view configured) of parcela field when i change (or set) values for fields viticultor and variedad.

It's possible to RErender or refresh the parcela field entity reference arguments with an ajax callback?

I've wrapped the parcela field into a Div with the webform UI. This is my custom code:

function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

switch($form_id){
    case 'webform_submission_movimientos_de_uva_add_form':
    case 'webform_submission_movimientos_de_uva_edit_form':
        $form['elements']['parcela']['#access']=FALSE;
        $form['elements']['viticultor']['#ajax'] = [
            'callback' => 'ajax_select_parcela',
            'event' => 'change',
            'progress' => [
                'type' => 'throbber',
                'message' => 'Actualizando lista de parcelas...',]
        ];
        $form['elements']['variedad']['#ajax'] = [
            'callback' => 'ajax_select_parcela',
            'event' => 'change',
            'progress' => [
                'wrapper' => 'select-parcela-wrapper',
                'type' => 'throbber',
                'message' => 'Actualizando lista de parcelas...',]
        ];
        break;
}}

function ajax_select_parcela(array &$form, FormStateInterface $form_state) {
// get drupal rendering service
$renderer = \Drupal::service('renderer');

// instantiate new ajax response object
$response = new AjaxResponse();

//WHAT TO DO HERE??
return $response;}

I'm using Drupal 9.

Update:

This is my ajax function:

function crdo_movimientos_select_parcela(array &$form,  \Drupal\Core\Form\FormStateInterface $form_state) {
$form['elements']['parcela']['options']=[];
$form['elements']['parcela']['#selection_settings']['view']['arguments']=[
  $form_state->getValue('viticultor'),$form_state->getValue('variedad_de_uva')
];

return $form['elements']['parcela'];}

Field parcela is displayed in the form, but with options none... How to rebuild the field's options with the new arguments?

Update 2:

I've rewrited the field_definition from the export webform devel Form API option, passing it the updated arguments, and even with specific arguments. But the field is rendered without options... I can't find the way for rebuild the #options. Any help will be apreciated.

This is the ajax function:

function crdo_movimientos_select_parcela(array &$form,  \Drupal\Core\Form\FormStateInterface $form_state) {
//if there are the two values (viticultor and variedad_de_uva), we unset and rebuild the parcela field element
if((!empty($form_state->getValue('viticultor'))) && (!empty($form_state->getValue('variedad_de_uva')))){
    unset($form['elements']['parcela']);
    \Drupal::messenger()->addMessage('Regeneramos campo parcela');
    $form['elements']['parcela'] = [
        '#type' => 'webform_entity_select',
        '#title' => t('Parcela'),
        '#target_type' => 'node',
        '#selection_handler' => 'views',
        '#selection_settings' => [
            'view' => [
                'view_name' => 'variedades_parcela_viticultor',
                'display_name' => 'entity_reference_1',
                'arguments' => [
                    '535',
                    '2',
                ],
            ],
        ],
        '#prefix' =>'<div id="select-parcela-wrapper">',
        '#suffix' =>'</div>',
    ];
}
// If we want to execute AJAX commands our callback needs to return
// an AjaxResponse object. let's create it and add our commands.
$response = new AjaxResponse();
// Issue a command that replaces the element #edit-output
// with the rendered markup of the field created above.
dpm($form['elements']['parcela']);
$response->addCommand(new ReplaceCommand('#select-parcela-wrapper', $form['elements']['parcela']));
// Finally return the AjaxResponse object.
return $response;}

I've tried to render the form element field before include it in the ReplaceCommand, but i obtain the same result...

0

Final Update (Closing): I get it! The key is rewrite the arguments in the hook_form_alter. This function is called ever when the ajax callback returns.

I obtain the solution from here: Entity reference view depending on other field

Final code:

function crdo_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

switch($form_id){
    case 'user_form'://Añadimos una función adicional al enviar el formulario de reseteo de contraseña
        //Enviamos un request a la aplicación velneo para actualizar su contraseña
        $form['actions']['submit']['#submit'][]= 'crdo_user_pass_submit';
        break;

    case 'webform_submission_movimientos_de_uva_add_form':
    case 'webform_submission_movimientos_de_uva_edit_form':
        //Añadimos un div contenedor alrededor del campo parcela, para usar como objetivo de la llamada Ajax
        $form['elements']['parcela']['#prefix'] = '<div id="select-parcela-wrapper">';
        $form['elements']['parcela']['#suffix'] = '</div>';

        $form['elements']['viticultor']['#ajax'] = [
            'callback' => 'crdo_movimientos_select_parcela',
            'event' => 'change',
            'wrapper' => 'select-parcela-wrapper',
            'progress' => [
                'type' => 'throbber',
                'message' => 'Actualizando lista de parcelas...',]
        ];
        $form['elements']['variedad_de_uva']['#ajax'] = [
            'callback' => 'crdo_movimientos_select_parcela',
            'event' => 'change',
            'wrapper' => 'select-parcela-wrapper',
            'progress' => [
                'type' => 'throbber',
                'message' => 'Actualizando lista de parcelas...',]
        ];
        if((!empty($form_state->getValue('viticultor'))) && (!empty($form_state->getValue('variedad_de_uva')))) {
            //\Drupal::messenger()->addMessage('Regeneramos campo parcela');
            $form['elements']['parcela']['#selection_settings']['view']['arguments'] = [
                $form_state->getValue('viticultor'),
                $form_state->getValue('variedad_de_uva')
            ];
            //dpm($form['elements']['parcela']);
        }
        break;
}}

function crdo_movimientos_select_parcela(array &$form,\Drupal\Core\Form\FormStateInterface $form_state) {
    return $form['elements']['parcela'];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.