2

I search the best way to get value from form field, and I would like to know if my code section below it's the only way to get value from field ($value = $var[0]['value']) or if it's possible to write this better:

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id){
  if ($form_id == 'node_bibliographie_form') {

    $form['#validate'][] = 'node_bibliographie_form_validate';

    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
       $form['actions'][$action]['#submit'][] = 'my_module_bibliographie_form_submit';
      }
    }
  }
}

function my_module_bibliographie_form_submit(&$form, FormStateInterface $form_state){
  // Get the submitted entity.
  $key        = $form_state->getValue('field_key');
  $id_dossier = $form_state->getValue('field_dossier_reference');

  if (isset($id_dossier) && isset($key) &&  !empty($key) && !empty($id_dossier)) {
    kint($id_dossier[0]['target_id']);
    //ugly ?
    $collection_key = $key[0]['value'];
   }
}
3

If you need to get the value of the array you can use below method.

 $values = $form_state->getValue(array('name_of the array', 'key'));
1

You are getting fine the value, but I see that you can improve the use of isset() and empty(), because in your code you don't need to use both of them.

empty()

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

function my_module_bibliographie_form_submit(&$form, FormStateInterface $form_state){
  // Get the submitted entity.
  $key        = $form_state->getValue('field_key');
  $id_dossier = $form_state->getValue('field_dossier_reference');
  //You don't need isset().
  if (!empty($key) && !empty($id_dossier)) {
    kint($id_dossier[0]['target_id']);
    // Why you see this ugly ?
    $collection_key = $key[0]['value'];
   }
}
  • Yep ! thanks for fix. It's the only way to get value from field ? – florian_drupal Aug 17 '17 at 15:15
  • @florian_drupal you can use $form_state->getValues() – Adrian Cid Almaguer Aug 17 '17 at 15:17
  • Or something like that : $node->get('field_date_derniere_modif')->getValue(); – florian_drupal Aug 24 '17 at 10:13

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.