Drupal 7 Form in a Block or Node w/ PHP

A simple Drupal 7 Form in a Block example.

  • w/ basic form function
  • w/ validation and submission functions
  • errors return to the block area itself as well
  • note: Drupal 7 Form API ref
  • to remove error message from appearing w/in the element; remove the 2nd line w/ $temperrors and the following IF statement that uses it.

Alright Boys! Paste this PHP code into your block to get started:

$form = drupal_render(drupal_get_form('my_example_form'));
$temperrors = form_get_errors();
if (isset($temperrors["greenentry"])) {
     print ($temperrors["greenentry"]);
}
print $form;

function my_example_form($form, &$form_state) {
     $form['greenentry'] = array(
          '#type' => 'textfield', 
          '#title' => t('Enter'),
          '#description' => t('Please enter the word: green.'), 
          '#required' => TRUE,
     );
     $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Submit'),
     );
     return $form;
}

function my_example_form_validate($form, &$form_state) {
     // Validation logic.
     if (!( $form_state['values']['greenentry'] == 'green')) {
          form_set_error('greenentry', "Sorry, try entering the word green.");
     }else{
          drupal_set_message('you were validated', 'status');
     }
}

function my_example_form_submit($form, &$form_state) {
     // Submission logic.
     drupal_set_message('You were submitted by submitting green', 'status');
}