Posted by sahunt83 on December 14, 2012 at 8:19pm
Here is the working code I am testing with:
<?php
/**
* @file myform.module
*/
/**
* Implements hook_menu().
*/
function myform_menu() {
$items['myform'] = array(
'title' => 'myform',
'page callback' => 'drupal_get_form',
'page arguments' => array('myform'),
'access callback' => true,
'type' => MENU_NORMAL_ITEM
);
return $items;
}
/**
* Form
*/
function myform() {
$form['Value'] = array(
'#title' => t('Value'),
'#type' => 'textfield',
'#description' => t('You may not enter the same value twice. (unless you hit enter really fast).'),
'#required' => true,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
return $form;
}
/**
* Validate
*/
function myform_validate($form, &$form_state) {
if (isset($form_state['values']['Value']) && trim($form_state['values']['Value'])!=''){
// prevent duplicates
db_set_active('test');
$r = db_query("SELECT id FROM test WHERE value = '".$form_state['values']['Value']."'");
$n = $r->rowCount();
if ($n) {
form_set_error('Value', t('This value has already been submitted.'));
}
db_set_active();
}
}
/**
* Submit
*/
function myform_submit($form, &$form_state) {
for ($i=0; $i<=10000000; $i++) {
// do nothing
}
db_set_active('test');
db_insert('test')->fields(array('value'=>$form_state['values']['Value']))->execute();
db_set_active();
}
?>The validation hook prevents duplicate values from being inserted, unless I hit the enter key or submit button really fast in which case the same value is inserted into the database multiple times.
How do I prevent duplicate values from being inserted?
Comments
Interesting. I thought the
Interesting. I thought the FAPI had safeguards in place to prevent duplicate submissions- I'd investigate that first to see if something can be done, but alternately if you just want to prevent duplicate entries in the DB make that column unique. Then wrap the insert in a try/catch so you don't give the user the dsod.
I'm unique, just like everybody else.
If I helped, please pay it forward, backward or sidelong.
Thanks for the reply.
Thanks for the reply. Unfortunately the actual form I'm working needs to allow for resubmissions after a certain number of days without removing the original data (i think). Not sure if that's possible.
The example code was mainly to show the simplest possible example of the problem as I see it. Which is that I can post duplicate data into my database despite the validation that should stop the data from being posted. Granted I did need to turn off javascript to get the duplicates to go through.
I will look into the FAPI safeguards you speak of.