I have see some post about that,but i still have no real answer.
In my form, user can select a register address in a select field. When he select an address, the ajax set value on some other fields :
The code :
if($form_state->getTriggeringElement()['#name']=="mes_adresses")
{
$listAdresse = $this->adresse_service->getUserAdresseById($form_state->getValue('mes_adresses'));
}
$form['containerGeneral']['livraison']['adresseComplete']['nom_livraison'] = array(
'#title' => 'Nom de livraison',
'#type' => 'textfield',
'#value' => $listAdresse['nom'],
);
$form['containerGeneral']['livraison']['adresseComplete']['prenom_livraison'] = array(
'#title' => 'Prénom de livraison',
'#type' => 'textfield',
'#value' => $listAdresse['prenom'],
);
$form['containerGeneral']['livraison']['adresseComplete']['pays_livraison'] = array(
'#title' => 'Pays de livraison',
'#type' => 'select',
'#required'=>true,
'#options'=>$this->taxonomy_service->getTermsByVid('pays_livraison'),
'#value' => $listAdresse['pays'],
);
$form['containerGeneral']['livraison']['adresseComplete']['adresse_livraison'] = array(
'#title' => 'Adresse de livraison',
'#type' => 'textfield',
'#value' => $listAdresse['adresse'],
);
$form['containerGeneral']['livraison']['adresseComplete']['adresse2_livraison'] = array(
'#title' => 'Adresse de livraison',
'#type' => 'textfield',
'#value' =>$listAdresse['adresse2'],
);
$form['containerGeneral']['livraison']['adresseComplete']['cp_livraison'] = array(
'#title' => 'Code postal de livraison',
'#maxlength'=>5,
'#type' => 'textfield',
'#value' => $listAdresse['code_postal'],
);
$form['containerGeneral']['livraison']['adresseComplete']['ville_livraison'] = array(
'#title' => 'Ville de livraison',
'#type' => 'textfield',
'#value' =>$listAdresse['ville'],
);
And the callback :
public function ajaxChangeAdresseCallback(array &$form, FormStateInterface $form_state)
{
$form_state->setRebuild(TRUE);
return $form['containerGeneral']['livraison']['adresseComplete'];
}
So there are 2 things :
#value
If you set value like that, user can never change the value because
$form_state->getValue()
ll keep the value set by the ajax.
#default_value
If you set the value like that, that doesn't work because the #default_value parameter if use just the first time the form is loaded.
The main problem is with $form_state.
If you kint when you submit your form $form_state->getValue() and $_POST, $_POST is good but not the $form_state.
But the issue are in the validate function too, if user select the option new address, ajax reload the form, set empty everywhere, and when you submit, the validate function ll tell you you have empty value.
I know on D7 some people unset the $form_state['values];
But on D8 ?
So how reset the $form_state value ?