Autor: Sven Culley am Thu, 07.07.2011 - 15:51
Wie speichert man ein Formular in Drupal?
Aufgrund meiner Piwik Statistik im Bereich Suchbegriffe möchte ich auf dieses Thema im Folgenden näher eingehen. Mit einem entsprechenden Custom Modul ist dieses sehr leicht zu realisieren.
Als erstes benötigen wir natürlich die entsprechende Ordnerstruktur.
Dazu legen wir im Ordner "sites/all/modules" einen Ordner mit Namen "example" und der folgenden Struktur an:
example (Ordner)
- example.info
- example.install
- example.module
Inhalt der example.info Datei
name = Example
description = Example form page and saving to database
version = 7.x-1.0
core = 7.x
Inhalt der example.install Datei
/**
* Implements hook_schema().
*/
function example_schema() {
$schema['example'] = array(
'fields' => array(
'id' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
'name' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''),
'phone' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''),
'mail' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''),
),
'primary key' => array('id'),
);
return $schema;
}
Inhalt der example.module Datei
/**
* Implements hook_menu().
**/
function example_menu() {
$items = array();
$items['example'] = array(
'title' => 'Example form',
'page callback' => 'drupal_get_form',
'page arguments' => array('example_page_form'),
'access arguments' => array('access content'),
);
return $items;
}
/**
* Example form
**/
function example_page_form($form_id, &$form_state) {
$form = array();
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#required' => TRUE,
);
$form['phone'] = array(
'#type' => 'textfield',
'#title' => t('Address'),
'#required' => TRUE,
);
$form['mail'] = array(
'#type' => 'textfield',
'#title' => t('E-mail address'),
'#required' => TRUE,
);
// more fields ...
// do not forget to apply to db schema in install file
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
return $form;
}
/**
* Implements hook_form_submit().
**/
function example_page_form_submit($form_id, &$form_state) {
drupal_write_record('example', $form_state['values']);
}