Skip to content

Instantly share code, notes, and snippets.

@pixel5
Last active August 29, 2015 14:21
Show Gist options
  • Save pixel5/884c27b98036b683709c to your computer and use it in GitHub Desktop.
Save pixel5/884c27b98036b683709c to your computer and use it in GitHub Desktop.
Form Example 2
<?php
// This is your page function, where your content is rendered.
// $id is a 'page argument' (see Drupal hook_menu documentation)
function MYMODULE_page_function($id) {
$output = '';
// MYMODULE_get_values represents a function for a query that
// retrieves values from the database and accepts $id as an
// argument to be used as a query condition.
$values = MYMODULE_get_values($id);
// Pass $values to your form
$form = drupal_get_form('MYMODULE_example_form',$values);
$output .= drupal_render($form);
return $output;
}
function MYMODULE_get_values($id) {
// Let's assume there is a query here returning this array:
$values = array(
'name' => 'Joe',
'flavor' => 0,
);
return $values;
}
// Accept $values as an argument in your form function, but set
// it to NULL if nothing is passed.
function MYMODULE_example_form($form, &$form_state, $values = NULL) {
// If $values is NULL, you can assume you're not editing a
// set of values, but rather creating a new one.
$edit = ($values == NULL) ? FALSE : TRUE;
$form = array();
$form['name'] = array(
'#type' => 'textfield',
'#title' => t("Your Name"),
'#default_value' => $edit ? $values['name'] : NULL, // This is the key line!
);
$form['flavor'] = array(
'#type' => 'select',
'#title' => t("Favorite Flavor"),
'#options' => array(
0 => t("Vanilla"),
1 => t("Chocolate"),
2 => t("Aspertame"),
),
'#default_value' => $edit ? $values['flavor'] : NULL, // This is the key line!
);
// Change your submit to an update function if $edit is TRUE
$form['submit'] = array(
'#type' => 'submit',
'#value' => t("Submit"),
'#submit' => $edit ? array('MYMODULE_example_update') : array('MYMODULE_example_submit'),
);
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment