0

I have this form enter image description here

created by this code:

public function buildForm(array $form, FormStateInterface $form_state, $contractId = NULL) {

    some initialisation code...

    $database = \Drupal::database();

    //  From database to populate $form['designation']
    $query_am = $database->select('member', 'am');
    $query_am->fields('am', ['id', 'designation']);
    $query_am->condition('status', [2, 3, 4], 'IN')
        ->orderBy('designation', 'ASC');
    $aMembers = $query_am->execute()->fetchAllKeyed();
    $aMembers = ["0" => ""] + $aMembers;


    $memberId = $form_state->getValue('designation');
    if ($memberId) {
        $query = $database->select('contract_subscription', 'cs')
            ->fields('cs')
            ->condition('contract_id', $contractId)
            ->condition('member_id', $memberId);
        $subscription = $query->execute()->fetchAssoc();
    }

    $wrapper = 'formWrapper';
    $form['#prefix'] = '<div id="' . $wrapper . '">';
    $form['#suffix'] = '</div>';

    $form['designation'] = [
        '#type' => 'select',
        '#options' => $aMembers,
        '#title' => $this->t('Member'),
        '#required' => TRUE,
        '#default_value' => $memberId,
        '#ajax' => [
            'callback' => '::memberCallback',
            'wrapper' => 'theSubscription',
        ],
    ];

    $form['theSubscription'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'theSubscription'],
        '#quantities' => $iNumberOfQuantities,
    ];

        $value = $subscription['quantity01'];
        $form['theSubscription']['quantity01'] = [
            '#type' => 'number',
            '#title' => $aContractTypeHeader[$i - 1],
            '#min' => 0.00,
            '#max' => 99.95,
            '#step' => 0.05,
            '#value' => $value,
        ];
    }

    $form['theSubscription']['comment'] = [
        '#type' => 'textarea',
        '#title' => t('Comment'),
        '#rows' => 1,
        '#value' => $subscription['comment'],
    ];

    $fileId = (int) $subscription['file__target_id'];
    $form['theSubscription']['file'] = [
        '#type' => 'managed_file',
        '#description' => $this->t('Limited to @size MB.', ['@size' => $upload_max_inMB]) . '<br>' . $this->t('Allowed types: pdf.'),
        '#upload_location' => 'private://contracts/subscriptions/',
        '#upload_validators' => [
            'file_validate_extensions' => ['pdf'],
            'file_validate_size' => [$upload_max],
        ],
        '#default_value' => [$fileId],
    ];

    if ($sContractIsOpenForSubscription) {
        $form['save'] = [
            '#type' => 'submit',
            '#name' => 'save',
            '#value' => $this->t('Save'),
            '#ajax' => [
                'wrapper' => $wrapper,
                'callback' => '::ajaxSave',
            ],
        ];
    }

    $form['leave'] = [
        '#type' => 'submit',
        '#name' => 'leave',
        '#value' => $this->t('Leave'),
    ];

    $form['#attached']['library'][] = 'amap/amap';

    return $form;
}

public function memberCallback($form, FormStateInterface $form_state) {
    return $form['theSubscription'];
}

When I select an item in the select box, Ajax memberCallbackis called, $database->select('contract_subscription', 'cs') is executed and the form is updated with the values retrieved from the database.
That works for all the fields except for the file which is never displayed (only the default empty managed_file field shows up): enter image description here

I wanted to check and I executed the form with $memberId = 64; hardcoded to force a first display without using Ajax and it works! enter image description here

What is wrong with my code?

1 Answer 1

0

Tried to use field name of file like this:

$form['theSubscription']['file'][$fileId] 
or either
$form['theSubscription'][$fileId] 

instead of

 $form['theSubscription']['file']

Analysis: By passing "$fileId" variable in field name , it makes field name dynamic & cache 'll not maintain of rendering "file_widget" hooks, it 'll render dynamic value of "managed_file" field on ajax call.

3
  • 1
    It seems to work with $form['theSubscription'][$fileId]. Thanks! By the way, where am I supposed to find this kind of information?
    – gbmapo
    Oct 20, 2023 at 13:31
  • Nice qus, It was just basic debugging & analysis skills that helps to fix issue however I did not found any link to resolve this issue.:)
    – mini
    Oct 20, 2023 at 14:45
  • Few days ago, I tried to alter the some contrib code functionality I figured out some hooks maintain their cache,similar pattern found here. so I tried to pass dynamic variable in field_name with thought of if it's cache issue of 'file_widget' hooks then it should work, finally solution works and reached at solution by analysis.
    – mini
    Oct 20, 2023 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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