drupaldrupal-7drupal-modulesdrupal-fieldsdrupal-content-types

Define and use a field of other node type as my form element type in Drupal 7


I'm developing a Drupal 7's module. I defined a node type named 'Booth'. Now in my module, I created a form with some fields like name, phone, address and so on. One of these fields is Booth which is a Select type element. I wanna have the booths titles (that I added in "Add Content > Booth") as my Select Element options. How can I do that? How can I fill the options array, with title field of my booth content type? [Please look at the image below]

The first field must be filled with title of booth titles

$form['exbooth'] = array(
    '#type' => 'select',
    '#title' => t('Exhibition Booth'),
    '#options' => array(), // I want to fill this array with title fields of booth content type
    '#required' => TRUE,
);
$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => TRUE,
);
$form['lastname'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name'),
    '#required' => TRUE,

Solution

  • After some digging in drupal API, finally I found the solution.

    I used entity_load() function to retrieve all nodes of 'booth' content type and then I put result's titles in an array and set that array for the Select options:

    $entities = entity_load('node');
    $booths = array();
    foreach($entities as $entity) {
        if($entity->type == 'booth') {
            $i = 1;
            $booths[$i] = $entity->title;
        }
    }
    ....
    //inputs
    $form['exbooth'] = array(
        '#type' => 'select',
        '#title' => t('Exhibition Booth'),
        '#options' => $booths, // I set my array of booth nodes here
        '#required' => TRUE,
    );