dbtng_example.module

  1. examples
    1. 7 dbtng_example/dbtng_example.module
    2. 8 dbtng_example/dbtng_example.module

This is an example outlining how a module can make use of the new DBTNG database API in Drupal 7.

@todo Demonstrate transaction usage.

General documentation is available at Database abstraction layer documentation and at .

Functions & methods

NameDescription
dbtng_example_advanced_listRender a filtered list of entries in the database.
dbtng_example_entry_deleteDelete an entry from the database.
dbtng_example_entry_insertSave an entry in the database.
dbtng_example_entry_loadRead from the database using a filter array.
dbtng_example_entry_updateUpdate an entry in the database.
dbtng_example_form_addPrepare a simple form to add an entry, with all the interesting fields.
dbtng_example_form_add_submitSubmit handler for 'add entry' form.
dbtng_example_form_updateSample UI to update a record.
dbtng_example_form_update_callbackAJAX callback handler for the pid select.
dbtng_example_form_update_submitSubmit handler for 'update entry' form.
dbtng_example_helpImplements hook_help().
dbtng_example_listRender a list of entries in the database.
dbtng_example_menuImplements hook_menu().

File

dbtng_example/dbtng_example.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * This is an example outlining how a module can make use of the new DBTNG
  5. * database API in Drupal 7.
  6. *
  7. * @todo Demonstrate transaction usage.
  8. *
  9. * General documentation is available at
  10. * @link database Database abstraction layer documentation @endlink and
  11. * at @link http://drupal.org/node/310069 @endlink.
  12. */
  13. /**
  14. * @defgroup dbtng_example Example: Database (DBTNG)
  15. * @ingroup examples
  16. * @{
  17. * Database examples, including DBTNG.
  18. *
  19. * 'DBTNG' means 'Database: The Next Generation.' Yes, Drupallers are nerds.
  20. *
  21. * General documentation is available at
  22. * @link database.inc database abstraction layer documentation @endlink and
  23. * at @link http://drupal.org/node/310069 Database API @endlink.
  24. *
  25. * The several examples here demonstrate basic database usage.
  26. *
  27. * In Drupal 6, the recommended method to save or update an entry in the
  28. * database was drupal_write_record() or db_query().
  29. *
  30. * In Drupal 7 and forward, the usage of db_query()
  31. * for INSERT, UPDATE, or DELETE is deprecated, because it is
  32. * database-dependent. Instead specific functions are provided to perform these
  33. * operations: db_insert(), db_update(), and db_delete() do the job now.
  34. * (Note that drupal_write_record() is also deprecated.)
  35. *
  36. * db_insert() example:
  37. * @code
  38. * // INSERT INTO {dbtng_example} (name, surname) VALUES('John, 'Doe')
  39. * db_insert('dbtng_example')
  40. * ->fields(array('name' => 'John', 'surname' => 'Doe'))
  41. * ->execute();
  42. * @endcode
  43. *
  44. * db_update() example:
  45. * @code
  46. * // UPDATE {dbtng_example} SET name = 'Jane' WHERE name = 'John'
  47. * db_update('dbtng_example')
  48. * ->fields(array('name' => 'Jane'))
  49. * ->condition('name', 'John')
  50. * ->execute();
  51. * @endcode
  52. *
  53. * db_delete() example:
  54. * @code
  55. * // DELETE FROM {dbtng_example} WHERE name = 'Jane'
  56. * db_delete('dbtng_example')
  57. * ->condition('name', 'Jane')
  58. * ->execute();
  59. * @endcode
  60. *
  61. * See @link database Database Abstraction Layer @endlink
  62. * @see db_insert()
  63. * @see db_update()
  64. * @see db_delete()
  65. * @see drupal_write_record()
  66. */
  67. /**
  68. * Save an entry in the database.
  69. *
  70. * The underlying DBTNG function is db_insert().
  71. *
  72. * In Drupal 6, this would have been:
  73. * @code
  74. * db_query(
  75. * "INSERT INTO {dbtng_example} (name, surname, age)
  76. * VALUES ('%s', '%s', '%d')",
  77. * $entry['name'],
  78. * $entry['surname'],
  79. * $entry['age']
  80. * );
  81. * @endcode
  82. *
  83. * Exception handling is shown in this example. It could be simplified
  84. * without the try/catch blocks, but since an insert will throw an exception
  85. * and terminate your application if the exception is not handled, it is best
  86. * to employ try/catch.
  87. *
  88. * @param $entry
  89. * An array containing all the fields of the database record.
  90. *
  91. * @see db_insert()
  92. */
  93. function dbtng_example_entry_insert($entry) {
  94. $return_value = NULL;
  95. try {
  96. $return_value = db_insert('dbtng_example')
  97. ->fields($entry)
  98. ->execute();
  99. }
  100. catch (Exception $e) {
  101. drupal_set_message(t('db_insert failed. Message = %message, query= %query',
  102. array('%message' => $e->getMessage(), '%query' => $e->query_string)), 'error');
  103. }
  104. return $return_value;
  105. }
  106. /**
  107. * Update an entry in the database.
  108. *
  109. * The former, deprecated techniques used db_query() or drupal_write_record():
  110. * @code
  111. * drupal_write_record('dbtng_example', $entry, $entry['pid']);
  112. * @endcode
  113. *
  114. * @code
  115. * db_query(
  116. * "UPDATE {dbtng_example}
  117. * SET name = '%s', surname = '%s', age = '%d'
  118. * WHERE pid = %d",
  119. * $entry['pid']
  120. * );
  121. * @endcode
  122. *
  123. * @param $entry
  124. * An array containing all the fields of the item to be updated.
  125. *
  126. * @see db_update()
  127. */
  128. function dbtng_example_entry_update($entry) {
  129. try {
  130. // db_update()...->execute() returns the number of rows updated.
  131. $count = db_update('dbtng_example')
  132. ->fields($entry)
  133. ->condition('pid', $entry['pid'])
  134. ->execute();
  135. }
  136. catch (Exception $e) {
  137. drupal_set_message(t('db_update failed. Message = %message, query= %query',
  138. array('%message' => $e->getMessage(), '%query' => $e->query_string)), 'error');
  139. }
  140. return $count;
  141. }
  142. /**
  143. * Delete an entry from the database.
  144. *
  145. * The usage of db_query is deprecated except for static queries.
  146. * Formerly, a deletion might have been accomplished like this:
  147. * @code
  148. * db_query("DELETE FROM {dbtng_example} WHERE pid = %d", $entry['pid]);
  149. * @endcode
  150. *
  151. * @param $entry
  152. * An array containing at least the person identifier 'pid' element of the
  153. * entry to delete.
  154. *
  155. * @see db_delete()
  156. */
  157. function dbtng_example_entry_delete($entry) {
  158. db_delete('dbtng_example')
  159. ->condition('pid', $entry['pid'])
  160. ->execute();
  161. }
  162. /**
  163. * Read from the database using a filter array.
  164. *
  165. * In Drupal 6, the standard function to perform reads was db_query(), and
  166. * for static queries, it still is.
  167. *
  168. * db_query() used an SQL query with placeholders and arguments as parameters.
  169. *
  170. * @code
  171. * // Old way
  172. * $query = "SELECT * FROM {dbtng_example} n WHERE n.uid = %d AND name = '%s'";
  173. * $result = db_query($query, $uid, $name);
  174. * @endcode
  175. *
  176. * Drupal 7 DBTNG provides an abstracted interface that will work with a wide
  177. * variety of database engines.
  178. *
  179. * db_query() is deprecated except when doing a static query. The following is
  180. * perfectly acceptable in Drupal 7. See
  181. * @link http://drupal.org/node/310072 the handbook page on static queries @endlink
  182. *
  183. * @code
  184. * // SELECT * FROM {dbtng_example} WHERE uid = 0 AND name = 'John'
  185. * db_query(
  186. * "SELECT * FROM {dbtng_example} WHERE uid = :uid and name = :name",
  187. * array(':uid' => 0, ':name' => 'John')
  188. * )->execute();
  189. * @endcode
  190. *
  191. * But for more dynamic queries, Drupal provides the db_select()
  192. * API method, so there are several ways to perform the same SQL query.
  193. * See the @link http://drupal.org/node/310075 handbook page on dynamic queries. @endlink
  194. *
  195. * @code
  196. * // SELECT * FROM {dbtng_example} WHERE uid = 0 AND name = 'John'
  197. * db_select('dbtng_example')
  198. * ->fields('dbtng_example')
  199. * ->condition('uid', 0)
  200. * ->condition('name', 'John')
  201. * ->execute();
  202. * @endcode
  203. *
  204. * Here is db_select with named placeholders:
  205. * @code
  206. * // SELECT * FROM {dbtng_example} WHERE uid = 0 AND name = 'John'
  207. * $arguments = array(':name' => 'John', ':uid' => 0);
  208. * db_select('dbtng_example')
  209. * ->fields('dbtng_example')
  210. * ->where('uid = :uid AND name = :name', $arguments)
  211. * ->execute();
  212. * @endcode
  213. *
  214. * Conditions are stacked and evaluated as AND and OR depending on the type of
  215. * query. For more information, read the conditional queries handbook page at:
  216. * http://drupal.org/node/310086
  217. *
  218. * The condition argument is an 'equal' evaluation by default, but this can be
  219. * altered:
  220. * @code
  221. * // SELECT * FROM {dbtng_example} WHERE age > 18
  222. * db_select('dbtng_example')
  223. * ->fields('dbtng_example')
  224. * ->condition('age', 18, '>')
  225. * ->execute();
  226. * @endcode
  227. *
  228. * @param $entry
  229. * An array containing all the fields used to search the entries in the table.
  230. * @return
  231. * An object containing the loaded entries if found.
  232. *
  233. * @see db_select()
  234. * @see db_query()
  235. * @see http://drupal.org/node/310072
  236. * @see http://drupal.org/node/310075
  237. *
  238. */
  239. function dbtng_example_entry_load($entry = array()) {
  240. // Read all fields from the dbtng_example table.
  241. $select = db_select('dbtng_example', 'example');
  242. $select->fields('example');
  243. // Add each field and value as a condition to this query.
  244. foreach ($entry as $field => $value) {
  245. $select->condition($field, $value);
  246. }
  247. // Return the result in object format.
  248. return $select->execute()->fetchAll();
  249. }
  250. /**
  251. * Render a filtered list of entries in the database.
  252. *
  253. * DBTNG also helps processing queries that return several rows, providing the
  254. * found objects in the same query execution call.
  255. *
  256. * This function queries the database using a JOIN between users table and the
  257. * example entries, to provide the username that created the entry, and creates
  258. * a table with the results, processing each row.
  259. *
  260. * SELECT
  261. * e.pid as pid, e.name as name, e.surname as surname, e.age as age
  262. * u.name as username
  263. * FROM
  264. * {dbtng_example} e
  265. * JOIN
  266. * users u ON e.uid = u.uid
  267. * WHERE
  268. * e.name = 'John' AND e.age > 18
  269. *
  270. * @see db_select()
  271. * @see http://drupal.org/node/310075
  272. */
  273. function dbtng_example_advanced_list() {
  274. $output = '';
  275. $select = db_select('dbtng_example', 'e');
  276. // Join the users table, so we can get the entry creator's username.
  277. $select->join('users', 'u', 'e.uid = u.uid');
  278. // Select these specific fields for the output.
  279. $select->addField('e', 'pid');
  280. $select->addField('u', 'name', 'username');
  281. $select->addField('e', 'name');
  282. $select->addField('e', 'surname');
  283. $select->addField('e', 'age');
  284. // Filter only persons named "John".
  285. $select->condition('e.name', 'John');
  286. // Filter only persons older than 18 years.
  287. $select->condition('e.age', 18, '>');
  288. // Make sure we only get items 0-49, for scalability reasons.
  289. $select->range(0, 50);
  290. // Now, loop all these entries and show them in a table. Note that there is no
  291. // db_fetch_* object or array function being called here. Also note that the
  292. // following line could have been written as
  293. // $entries = $select->execute()->fetchAll() which would return each selected
  294. // record as an object instead of an array.
  295. $entries = $select->execute()->fetchAll(PDO::FETCH_ASSOC);
  296. if (!empty($entries)) {
  297. $rows = array();
  298. foreach ($entries as $entry) {
  299. // Sanitize the data before handing it off to the theme layer.
  300. $rows[] = array_map('check_plain', $entry);
  301. }
  302. // Make a table for them.
  303. $header = array(t('Id'), t('Created by'), t('Name'), t('Surname'), t('Age'));
  304. $output .= theme('table', array('header' => $header, 'rows' => $rows));
  305. }
  306. else {
  307. drupal_set_message(t('No entries meet the filter criteria (Name = "John" and Age > 18).'));
  308. }
  309. return $output;
  310. }
  311. //// Helper functions ////
  312. /**
  313. * Implements hook_help().
  314. *
  315. * Show some help on each form provided by this module.
  316. */
  317. function dbtng_example_help($path) {
  318. $output = '';
  319. switch ($path) {
  320. case 'examples/dbtng':
  321. $output = t('Generate a list of all entries in the database. There is no filter in the query.');
  322. break;
  323. case 'examples/dbtng/advanced':
  324. $output = t('A more complex list of entries in the database.') . ' ';
  325. $output .= t('Only the entries with name = "John" and age older than 18 years are shown, the username of the person who created the entry is also shown.');
  326. break;
  327. case 'examples/dbtng/update':
  328. $output = t('Demonstrates a database update operation.');
  329. break;
  330. case 'examples/dbtng/add':
  331. $output = t('Add an entry to the dbtng_example table.');
  332. break;
  333. }
  334. return $output;
  335. }
  336. /**
  337. * Implements hook_menu().
  338. *
  339. * Set up calls to drupal_get_form() for all our example cases.
  340. */
  341. function dbtng_example_menu() {
  342. $items = array();
  343. $items['examples/dbtng'] = array(
  344. 'title' => 'DBTNG Example',
  345. 'page callback' => 'dbtng_example_list',
  346. 'access callback' => TRUE,
  347. );
  348. $items['examples/dbtng/list'] = array(
  349. 'title' => 'List',
  350. 'type' => MENU_DEFAULT_LOCAL_TASK,
  351. 'weight' => -10,
  352. );
  353. $items['examples/dbtng/add'] = array(
  354. 'title' => 'Add entry',
  355. 'page callback' => 'drupal_get_form',
  356. 'page arguments' => array('dbtng_example_form_add'),
  357. 'access callback' => TRUE,
  358. 'type' => MENU_LOCAL_TASK,
  359. 'weight' => -9,
  360. );
  361. $items['examples/dbtng/update'] = array(
  362. 'title' => 'Update entry',
  363. 'page callback' => 'drupal_get_form',
  364. 'page arguments' => array('dbtng_example_form_update'),
  365. 'type' => MENU_LOCAL_TASK,
  366. 'access callback' => TRUE,
  367. 'weight' => -5,
  368. );
  369. $items['examples/dbtng/advanced'] = array(
  370. 'title' => 'Advanced list',
  371. 'page callback' => 'dbtng_example_advanced_list',
  372. 'access callback' => TRUE,
  373. 'type' => MENU_LOCAL_TASK,
  374. );
  375. return $items;
  376. }
  377. /**
  378. * Render a list of entries in the database.
  379. */
  380. function dbtng_example_list() {
  381. $output = '';
  382. // Get all entries in the dbtng_example table.
  383. if ($entries = dbtng_example_entry_load()) {
  384. $rows = array();
  385. foreach ($entries as $entry) {
  386. // Sanitize the data before handing it off to the theme layer.
  387. $rows[] = array_map('check_plain', (array) $entry);
  388. }
  389. // Make a table for them.
  390. $header = array(t('Id'), t('uid'), t('Name'), t('Surname'), t('Age'));
  391. $output .= theme('table', array('header' => $header, 'rows' => $rows));
  392. }
  393. else {
  394. drupal_set_message(t('No entries have been added yet.'));
  395. }
  396. return $output;
  397. }
  398. /**
  399. * Prepare a simple form to add an entry, with all the interesting fields.
  400. */
  401. function dbtng_example_form_add($form, &$form_state) {
  402. $form = array();
  403. $form['add'] = array(
  404. '#type' => 'fieldset',
  405. '#title' => t('Add a person entry'),
  406. );
  407. $form['add']['name'] = array(
  408. '#type' => 'textfield',
  409. '#title' => t('Name'),
  410. '#size' => 15,
  411. );
  412. $form['add']['surname'] = array(
  413. '#type' => 'textfield',
  414. '#title' => t('Surname'),
  415. '#size' => 15,
  416. );
  417. $form['add']['age'] = array(
  418. '#type' => 'textfield',
  419. '#title' => t('Age'),
  420. '#size' => 5,
  421. '#description' => t("Values greater than 127 will cause an exception. Try it - it's a great example why exception handling is needed with DTBNG."),
  422. );
  423. $form['add']['submit'] = array(
  424. '#type' => 'submit',
  425. '#value' => t('Add'),
  426. );
  427. return $form;
  428. }
  429. /**
  430. * Submit handler for 'add entry' form.
  431. */
  432. function dbtng_example_form_add_submit($form, &$form_state) {
  433. global $user;
  434. // Save the submitted entry.
  435. $entry = array(
  436. 'name' => $form_state['values']['name'],
  437. 'surname' => $form_state['values']['surname'],
  438. 'age' => $form_state['values']['age'],
  439. 'uid' => $user->uid,
  440. );
  441. $return = dbtng_example_entry_insert($entry);
  442. if ($return) {
  443. drupal_set_message(t("Created entry @entry", array('@entry' => print_r($entry, TRUE))));
  444. }
  445. }
  446. /**
  447. * Sample UI to update a record.
  448. */
  449. function dbtng_example_form_update($form, &$form_state) {
  450. $form = array(
  451. '#prefix' => '<div id="updateform">',
  452. '#suffix' => '</div>',
  453. );
  454. $entries = dbtng_example_entry_load();
  455. $keyed_entries = array();
  456. if (empty($entries)) {
  457. $form['no_values'] = array(
  458. '#value' => t("No entries exist in the table dbtng_example table."),
  459. );
  460. return $form;
  461. }
  462. foreach ($entries as $entry) {
  463. $options[$entry->pid] = t("@pid: @name @surname (@age)", array('@pid' => $entry->pid, '@name' => $entry->name, '@surname' => $entry->surname, '@age' => $entry->age));
  464. $keyed_entries[$entry->pid] = $entry;
  465. }
  466. $default_entry = !empty($form_state['values']['pid']) ? $keyed_entries[$form_state['values']['pid']] : $entries[0];
  467. $form_state['entries'] = $keyed_entries;
  468. $form['pid'] = array(
  469. '#type' => 'select',
  470. '#options' => $options,
  471. '#title' => t('Choose entry to update'),
  472. '#default_value' => $default_entry->pid,
  473. '#ajax' => array(
  474. 'wrapper' => 'updateform',
  475. 'callback' => 'dbtng_example_form_update_callback',
  476. ),
  477. );
  478. $form['name'] = array(
  479. '#type' => 'textfield',
  480. '#title' => t('Updated first name'),
  481. '#size' => 15,
  482. '#default_value' => $default_entry->name,
  483. );
  484. $form['surname'] = array(
  485. '#type' => 'textfield',
  486. '#title' => t('Updated last name'),
  487. '#size' => 15,
  488. '#default_value' => $default_entry->surname,
  489. );
  490. $form['age'] = array(
  491. '#type' => 'textfield',
  492. '#title' => t('Updated age'),
  493. '#size' => 4,
  494. '#default_value' => $default_entry->age,
  495. '#description' => t("Values greater than 127 will cause an exception"),
  496. );
  497. $form['submit'] = array(
  498. '#type' => 'submit',
  499. '#value' => t('Update'),
  500. );
  501. return $form;
  502. }
  503. /**
  504. * AJAX callback handler for the pid select.
  505. *
  506. * When the pid changes, populates the defaults from the database in the form.
  507. */
  508. function dbtng_example_form_update_callback($form, $form_state) {
  509. $entry = $form_state['entries'][$form_state['values']['pid']];
  510. // Setting the #value of items is the only way I was able to figure out
  511. // to get replaced defaults on these items. #default_value will not do it
  512. // and shouldn't.
  513. foreach (array('name', 'surname', 'age') as $item) {
  514. $form[$item]['#value'] = $entry->$item;
  515. }
  516. return $form;
  517. }
  518. /**
  519. * Submit handler for 'update entry' form.
  520. */
  521. function dbtng_example_form_update_submit($form, &$form_state) {
  522. global $user;
  523. // Save the submitted entry.
  524. $entry = array(
  525. 'pid' => $form_state['values']['pid'],
  526. 'name' => $form_state['values']['name'],
  527. 'surname' => $form_state['values']['surname'],
  528. 'age' => $form_state['values']['age'],
  529. 'uid' => $user->uid,
  530. );
  531. $count = dbtng_example_entry_update($entry);
  532. drupal_set_message(t("Updated entry @entry (@count row updated)", array('@count' => $count, '@entry' => print_r($entry, TRUE))));
  533. }
  534. /**
  535. * @} End of "defgroup dbtng_example".
  536. */
Login or register to post comments