I'm trying to get the hang of Forms'N'Ajax in Drupal 8.
I have a classic problem with my selects in D8:
$form['manufactureYear'] = array(
'#type' => 'select',
'#title' => $this->t('Manufacture year'),
'#options' => $manufactureYears,
'#required' => TRUE,
'#ajax' => [
'callback' => array($this, 'populateDurationYears'),
'wrapper' => 'edit-loanDurationYears'
],
);
Then I have a second select:
$form['loanDurationYears'] = array(
'#type' => 'select',
'#title' => $this->t('Loan duration years'),
);
The function populateDurationYears is the one that are killing me. I've tried with the ReplaceCommand in a AjaxResponse, but when I submit the form the loanDurationYears select is empty.
Can somebody help me here?
EDIT: - If I change ReplaceCommand with AppendCommand it's almost correct. The code now looks like this:
<select id="edit-loandurationyears" class="form-select" name="loanDurationYears" data-drupal-selector="edit-loandurationyears">
<div>
<option value="3">3 years</option>
<option value="4">4 years</option>
<option value="5">5 years</option>
<option value="6">6 years</option>
<option value="7">7 years</option>
<option value="8">8 years</option>
<option value="9">9 years</option>
</div>
</select>
What's up with that <div>
? It messes up the select :-(
EDIT 2:
The populateDurationYears method looks like this:
$response = new AjaxResponse();
if($maxDurationYears != 0) {
for($i = $minLoanDurationYears-1; $i < $maxDurationYears; $i++) {
$option .= "<option value='" . (string)($i+1) . "'>" . (string)($i+1) . " år</option>";
}
$response->addCommand(new AppendCommand('#edit-loandurationyears', $option));
}
return $response;