0

I have tried the example I found on Dynamic select list in the form API (dependent dropdown list)? but I did not get it to work properly. The first list populates, but I can not fill the second one with values that are different depending on the first select.

function formtutorial_form(&$form_state) {
  // Connection settings here!!! Then two queries below.
  $stmt = $conn->prepare("SELECT productID, ProductName, oil_ID FROM tb_Products");

  if ($stmt->execute()) {
    $stmt->setFetchMode(PDO::FETCH_OBJ);
    $productlist = array();
    foreach ($stmt as $row) {
      $productlist[$row->productID] = $row->ProductName;
    }
  }

  $productIDselected = $form_state['values']['Products'];
  $stmt7 = $conn->prepare("SELECT oil_ID, OilName FROM tb_Oils WHERE oil_ID = $productIDselected ");
  if ($stmt7->execute()) {
    $stmt7->setFetchMode(PDO::FETCH_OBJ);
    $oillists = array();
    foreach ($stmt7 as $row) {
      $oillists[$row->oil_ID] = $row->OilName;
    }
  }

  $form['Products'] = array(
    '#type'=>'select',
    '#title' => t('Products'),
    '#options' => $productlist,
    '#multiple' => FALSE,
    '#attributes'=> array('size' => 0), 
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
    ),
  );

  $form['Oils'] = array(
    '#type' => 'select',
    '#title' => t('Oils'),
    '#options' => $oillists,
    '#multiple' => false,
    '#prefix' => '<div id="divaroundseconddropdown">',
    '#suffix' => '</div>',
    '#productlist' => array(
      'visible' =>array(
        'input[name="productname"]' => array(
          'value' => $productlist
        ),
      ),
    ),
  );

function _ajaxfunction($form, $form_state) {
  return $form['Oils'];
}
5
  • can you include you ajax function? also, besides the point you should consider adding your database to the drupal connection and use it rather than connecting through PDO, it is much easier with Drupal, see this post Commented Aug 6, 2013 at 3:44
  • @longboardnode I added the function at the bottom, I followed a stack exchange question see link in my question. Above is the code I shall use.
    – user19786
    Commented Aug 6, 2013 at 8:12
  • @longboardnode drupal.stackexchange.com/questions/75211/… trying this, it is the same question, but looks more like it will work
    – user19786
    Commented Aug 6, 2013 at 8:25
  • try this post drupal.stackexchange.com/questions/10112/… Commented Aug 7, 2013 at 4:13
  • The code you are showing is not complete (see the lines before function _ajaxfunction($form, $form_state)). If formtutorial_form(&$form_state) is a form building function, then it is missing an argument, and it should return a value.
    – avpaderno
    Commented Aug 8, 2013 at 10:06

0

Your Answer

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

Browse other questions tagged or ask your own question.