Score:0

Creating link option in form and modifying it's url in form alter hook

us flag

I'm searching to modify a node add form, so far i added a personal field "link" to display as a button to add another node type if the user wants to, that link has this code in hook_form_alter, im catching a value from another select earlier and passing that value to my route::

    $selected_advertiser = isset($form_state->getUserInput()['field_advertiser'])? $form_state->getUserInput()['field_advertiser'] : "0";
    $url = Url::fromRoute('product.product_form', ['advertiser' => $selected_advertiser]);
    $form['product_modal'] = [
        '#type' => 'link',
        '#name' => 'product_modal',
        '#title' => t('New Product'),
        '#url' => $url,
        '#attributes' => [
            'class' => [
                'use-ajax',
                'button',
            ],
            'data-dialog-type' => 'modal',
            'data-dialog-options' => '{"width":800, "height": 500}',
            'disable-refocus' => true,
            'style'=>'display: inline-block',
        ],
        "#weight" => 5,
    ];

routing.yml

  product.product_form:
  path: /product/product_form/{advertiser}
  defaults:
    _controller: '\Drupal\my_module\Controller\mycontrollerController::openModalProduct'
    _title: 'Popup for product form'
  requirements:
    _permission: 'administer site configuration'

so the first time this runs it sets the $selected_advertiser to "0" but next time is setting properly to whatever id i have selected from previous select option, but the route to the button is still matched as default value "0", my debugger is showing the correct new route with the correct new id but the form button is not, im guessing this has something to do with unstated changes in form or something like that?

Hodba Khalaf avatar
eg flag
Why not create a new selected_advertiser field and hide, then use the value of the field to modify the $URL?
Ernesto Alfredo avatar
us flag
@HodbaKhalaf i think i understand the idea, i think looks good, let me try that
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.