0

I have a complex form. Which will let users to select some drop-down items to add a food diary record.

Currently, I'm using this

if (!form_get_errors()) {.....}

to decide whether to insert new record to database or not. (in "function adddiary_form_submit($form, &$form_state)" area).

If a user did not select all fields correctly, I use this

"$commands = array(); $commands[]=ajax_command_alert('Please select all fields!'); return array('#type' => 'ajax', '#commands' => $commands); }"

to show a alert window to notified the user.

However, my problem is that the error message produce by Drupal will not show directly on the add record page (diary/add) because I use a ajax on submit button, and instead it show on the page I assign to redirect to (diary/list).

$form['submit'] = array( '#type' => 'submit', '#value' => t('Submit'), '#executes_submit_callback' => FALSE, '#ajax' => array( 'callback' => 'adddiary_form_submit', ), );

I'm not good at coding. I also try to use ajax validate but not working.

Do anyone know how to make the error message disable? or reset? or show directly in the current page instead of showing up when a record is already insert into database.(kind of strange right?)

Or how to use ajax? to check every select list is selected...

I have no idea how to make this work correctly.

I tried my best to describe the situation. If you still not clear, you may ask for detail.

Hope someone may help me with this, I've already look up information to achieve this form for a week.

Thanks@@~!

<?php

function adddiary_menu(){
    return array(
        'diary/add' => array(
            'title' => 'Add Diary',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('adddiary_page'),
            'access arguments' => array('access content'), 
        )
    );
}


function adddiary_permission() {
  return array(
    'adddiary module' => array(
      'title' => t('Add diary module permission'),
  ));
}


function adddiary_page($form, &$form_state) {

    if (user_access('adddiary module')) {
    //Allowed

    $form['date'] = array(
    '#type' => 'date_popup',
    //'#title' => 'Date',
    '#default_value' => date('Y-m-d'),
    '#date_format' => 'Y-m-d',
    //'#date_label_position' => 'within',
    '#date_year_range' => '-0:+0',
    );

    $form['time'] = array(
    '#title' => t('Time'),
    '#type' => 'radios',
    '#options' => array(
        1 => t('Breakfast'),
        2 => t('Lunch'),
        3 => t('Dinner'),
       ),
    '#required' => TRUE,
    );

    $form['type'] = array(
    '#type' => 'select',
    '#title' => 'Food',
    '#options' => array(
        1 => t('Type1'),
        2 => t('Type2'),
        3 => t('Type3'),
        4 => t('Type4'),
        5 => t('Type5'),
        6 => t('Type6'),
       ),
    '#required' => TRUE,
    );

    //Type1
    $query1 = db_select('food_profile');
    $query1->fields('food_profile', array('ID', 'type','name'));
    $query1->condition('type', '1', '=');
    $query1->orderBy('name', 'ASC');
    $results1 = $query1->execute();

    $options1 = array();
    foreach ($results1 as $result1) {
    $options1[$result1->ID] = $result1->name;
    }

    $form['type1'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '1'),
        ),
    ),
    '#options' => $options1,
    );

    //Type2
    $query2 = db_select('food_profile');
    $query2->fields('food_profile', array('ID', 'type','name'));
    $query2->condition('type', '2', '=');
    $query2->orderBy('name', 'ASC');
    $results2 = $query2->execute();

    $options2 = array();
    foreach ($results2 as $result2) {
    $options2[$result2->ID] = $result2->name;
    }

    $form['type2'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '2'),
        ),
    ),
    '#options' => $options2,
    );

    //Type3
    $query3 = db_select('food_profile');
    $query3->fields('food_profile', array('ID', 'type','name'));
    $query3->condition('type', '3', '=');
    $query3->orderBy('name', 'ASC');
    $results3 = $query3->execute();

    $options3 = array();
    foreach ($results3 as $result3) {
    $options3[$result3->ID] = $result3->name;
    }

    $form['type3'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '3'),
        ),
    ),
    '#options' => $options3,
    );

    //Type4
    $query4 = db_select('food_profile');
    $query4->fields('food_profile', array('ID', 'type','name'));
    $query4->condition('type', '4', '=');
    $query4->orderBy('name', 'ASC');
    $results4 = $query4->execute();

    $options4 = array();
    foreach ($results4 as $result4) {
    $options4[$result4->ID] = $result4->name;
    }

    $form['type4'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '4'),
        ),
    ),
    '#options' => $options4,
    );

    //Type5
    $query5 = db_select('food_profile');
    $query5->fields('food_profile', array('ID', 'type','name'));
    $query5->condition('type', '5', '=');
    $query5->orderBy('name', 'ASC');
    $results5 = $query5->execute();

    $options5 = array();
    foreach ($results5 as $result5) {
    $options5[$result5->ID] = $result5->name;
    }

    $form['type5'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '5'),
        ),
    ),
    '#options' => $options5,
    );

    //Type6
    $query6 = db_select('food_profile');
    $query6->fields('food_profile', array('ID', 'type','name'));
    $query6->condition('type', '6', '=');
    $query6->orderBy('name', 'ASC');
    $results6 = $query6->execute();

    $options6 = array();
    foreach ($results6 as $result6) {
    $options6[$result6->ID] = $result6->name;
    }

    $form['type6'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '6'),
        ),
    ),
    '#options' => $options6,
    );

    $form['portion'] = array(
    '#title' => t('Portion'),
    '#type' => 'select',
    '#options' => array(
        1 => t('1'),
        2 => t('2'),
        3 => t('3'),
        4 => t('4'),
        5 => t('5'),
       ),
    '#required' => TRUE,
    );

    $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#executes_submit_callback' => FALSE,
    '#ajax' => array(
        'callback' => 'adddiary_form_submit',
         ),
    );

    return $form;
    } else {
    //Access denied
    drupal_goto("user/login");
  }
}

function adddiary_form_validate($form, &$form_state) {

}

function adddiary_form_submit($form, &$form_state) {
    if (!form_get_errors()) {
    $food_ID = form_result_helper($form_state);

    $result = db_query('SELECT name, calorie, protein, fat, fat_1, fat_2, fat_3, cho, cho_1, cho_2, mineral, mineral_1, mineral_2, mineral_3, mineral_4 FROM {food_profile} n WHERE ID = :food_ID', array(':food_ID' => $food_ID));
    foreach($result as $item) {
        $name = $item->name;
        $calorie = $item->calorie;
        $protein = $item->protein;
        $fat = $item->fat;
        $fat_1 = $item->fat_1;
        $fat_2 = $item->fat_2;
        $fat_3 = $item->fat_3;
        $cho = $item->cho;
        $cho_1 = $item->cho_1;
        $cho_2 = $item->cho_2;
        $mineral = $item->mineral;
        $mineral_1 = $item->mineral_1;
        $mineral_2 = $item->mineral_2;
        $mineral_3 = $item->mineral_3;
        $mineral_4 = $item->mineral_4;
    }

    global $user;
    $timestamp = strtotime($form_state['values']['date']);
    $query = db_insert('food_diary')
    ->fields(array(
      'user' => $user->name,
      'uid' => $user->uid,
      'date' => $timestamp,
      'time' => $form_state['values']['time'],
      'type' => $form_state['values']['type'],
      'food_ID' => $food_ID,
      'portion' => $form_state['values']['portion'],
      'food' => $name,
      'calorie' => $calorie,
      'protein' => $protein,
      'fat' => $fat,
      'fat_1' => $fat_1,
      'fat_2' => $fat_2,
      'fat_3' => $fat_3,
      'cho' => $cho,
      'cho_1' => $cho_1,
      'cho_2' => $cho_2,
      'mineral' => $mineral,
      'mineral_1' => $mineral_1,
      'mineral_2' => $mineral_2,
      'mineral_3' => $mineral_3,
      'mineral_4' => $mineral_4,
    ))
    ->execute();

    drupal_set_message(t('Record Added!!!!'));  

    //redirect to particular page
    ctools_include('ajax');
    $commands[] = ctools_ajax_command_redirect('diary/list');
    return array('#type' => 'ajax', '#commands' => $commands);
    }
    else {    
    $commands = array();
    $commands[]=ajax_command_alert('Please select all fields!');
    return array('#type' => 'ajax', '#commands' => $commands);
    }
}


function form_result_helper($form_state) {
  $type_name = $form_state['values']['type'];
  $food_ID = t('No food Selected');
  $food = '';
  switch ($type_name) {
    case 1 :
       $food = $form_state['values']['type1'];
       $food_ID = $form_state['values']['type1'];
    break;
    case 2 :
        $food = $form_state['values']['type2'];
        $food_ID = $form_state['values']['type2'];
    break;
    case 3 :
        $food = $form_state['values']['type3'];
        $food_ID = $form_state['values']['type3'];
    break;
    case 4 :
        $food = $form_state['values']['type4'];
        $food_ID = $form_state['values']['type4'];
    break;
    case 5 :
        $food = $form_state['values']['type5'];
        $food_ID = $form_state['values']['type5'];
    break;
    case 6 :
        $food = $form_state['values']['type6'];
        $food_ID = $form_state['values']['type6'];
    break;
  }
  return $food_ID;
}

1 Answer 1

1

So your issue is about displaying the system message on the page when an ajax submit is triggered right? So based on Ajax framework, you need to add the ff. to your $commands array like so:

$commands[] = ajax_command_prepend(NULL, theme('status_messages'));

Hope it works for you.

EDITED

I investigated more and found noticed that the form AJAX callbacks needs to return the whole form or a part of that form that needs to be updated and I remembered that when forms are submitted using AJAX, it displays the error and/or success messages inside the form because the form itself is the one being rebuilt. This is a simple example:

/**
 * Form adddiary_addform.
 */
function adddiary_addform($form, &$form_state) {
  // This wraps the form and will be the target for the submit callback.
  $form['#prefix'] = '<div id="box">';
  $form['#suffix'] = '</div>';

  $form['text'] = array(
    '#type' => 'textfield',
    '#title' => t('Text'),
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => '_adddiary_addform_submit_callback',
      // This targets the <div id="box"> and it's contents.
      'wrapper' => 'box',
    ),
    '#value' => t('Submit'),
  );

  return $form;
}

/**
 * Form validation for adddiary_addform.
 */
function adddiary_addform_validate($form, &$form_state) {
  if ($form_state['values']['text'] != 'leo') {
    form_set_error('text', t('It\'s supposed to be leo.'));
  }
}

/**
 * Form submit for adddiary_addform.
 */
function adddiary_addform_submit($form, &$form_state) {
  drupal_set_message('normal form submitted');
  // This will fire if JS is not enabled in the browser.
  // Just might come in handy but you can of course improve it.
  $form_state['redirect'] = 'node';
}

/**
 * Form submit callback for adddiary_addform.
 */
function _adddiary_addform_submit_callback($form, &$form_state) {
  if ($errors = form_get_errors()) {
    // We return the whole form so that the message from form_set_error or
    // drupal_set_message will be included in the form's AJAX content updating.
    return $form;
  }
  else {
    // If we have no errors, then we can redirect now to whatever page you want.
    ctools_include('ajax');
    ctools_add_js('ajax-responder');
    $commands[] = ctools_ajax_command_redirect('node');
    print ajax_render($commands);
    exit;
  }
}

Sorry for another edit again, I updated the ff. functions: adddiary_addform_submit and _adddiary_addform_submit_callback. Please take a look again. I think this would fit your needs now.

5
  • Hello! Thank you! Yeah, I want it to display~ I add this line to $commands array and the message still not show up... But it won't show on the redirect page too. So it's work I think! Thank you again^^!
    – Webster H.
    Aug 23, 2015 at 7:24
  • Hi! I added additional information cause I was really interested on the issue and it bugged me since I wasn't working with AJAX submitted forms for a while. Now, with the example I added all your validations and form success redirects can be placed inside the normal form submit function. Aug 23, 2015 at 20:53
  • Sorry I had another update to complete the functionality where you'll be redirected to another page after a successful form submission w/c also displays the message. Hope it's all going good on your end. :) Aug 23, 2015 at 21:16
  • Hello Leo! Wow!!! Amazing! The error message shows now! Then I don't have to use the annoying alert window! Thank you again! It's very kind of you^^
    – Webster H.
    Aug 24, 2015 at 5:40
  • Good day Weldon! That's awesome! You're very welcome! :) Aug 24, 2015 at 5:56

Your Answer

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

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