2

Using hook_form_alter I have added a custom field in my node creation form

function custom_assignments_form_alter(&$form, $form_state, $form_id) {
//print_r($form_id);exit;
if($form_id == 'node_assignment_form'){

    $lecture_options = array();
    $lecture_values = db_query("SELECT nid, title FROM `node_field_data` WHERE nid IN (SELECT entity_id FROM 
                        `node__field_module` WHERE bundle='lectures' AND field_module_target_id=:tid)", 
                        array(':tid' => $selectedWeek))->fetchAll();
    foreach($lecture_values AS $key => $value){
        $lecture_options[$value->nid] = $value->title;
    }
    //print("<pre>");print_r($lecture_options);exit;


    $form['field_after_lecture']['#access'] = FALSE;
    $form['field_after_lecture_tmp'] = array(
            '#title' => t('After Lecture'),
            '#required' => true,
            '#type' => 'select',
            '#options' => $lecture_options,
            //'#default_value' => print_r($form_state->getBuildInfo()['args']);exit;,
            '#weight' => 100,
            '#prefix' => '<div id="custom">',
            '#suffix' => '</div>'
    );
}}

How to get the value of field_after_lecture_tmp in hook_node_presave I printed the node fields using $node->toArray() function. But this field is not there. In Drupal 7 I was able to access it.

1 Answer 1

2

You can't get the value in the hook_node_presave() because this is not a node field, as you says is a custom field that you create altering the form.

In this case you need to add a custom submit handler to use the value, something like this inside the hook implementation:

function custom_assignments_form_alter(&$form, $form_state, $form_id) {
// ...
  if (isset($form['actions']['save_continue']['#submit'])) {
    array_unshift($form['actions']['save_continue']['#submit'], '_node_revision_delete_form_node_type_submit');
  }
// ...
}

And in the function you can access to the value and perform your actions

function _node_revision_delete_form_node_type_submit(array &$form, FormStateInterface $form_state) {
// Getting the form values.
  $field_after_lecture_tmp = $form_state->getValue('field_after_lecture_tmp');
}

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.