I created a simple user form that allows the user to give a database name and when the user submitt the drupal site will be connected to the given databasename, I defined my database in the file settings.php: myDataBase and when I try
db_set_active('myDataBase');
it works fine but when I type myDataBase in the text field and submitt and then use the submitted value to connect to the database it didnt work.
<?php
function testform_menu() {
$items = array();
$items['test'] = array(
'title' => 'connect an external database',
'page callback' => 'drupal_get_form',
'page arguments' => array('testform'),
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function testform($form, &$form_state) {
$form = array();
$form['Databasename'] = array(
'#type' => 'textfield',
'#title' => t('enter the database name'),
'#description' => t('a user interface to switch between databases'),
'#size' => 28,
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function testform_validate($form, &$form_state) {
}
function testform_submit($form, &$form_state) {
if (db_set_active('myDataBase'))
{
drupal_set_message('database connected'); // works
}
// $database_name =$form_state['values']['Databasename']; // ius not working!!
// if ($database_name ) {
// db_set_active($database_name); // I even tried to parsing the submitted value to a string but didnt work in both case
// drupal_set_message(t('connected to the database'.' '.$database_name));
// }
db_set_active();
}
You need a function to manage your form submit, for example:
function testform_submit($form, &$form_state)
{
//Do your stuff
}
Or you can define the submit function using the #submit key in your form:
'#submit' => array('your_custom_function_name')
More info: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit_property
Inside this function you can process your form.
Related
I have been working on creating a custom form with an autocomplete field that will search the database for a specific content type's field values and bring back the results so the user can select one for that input box.
My main problem is actually knowing how to target the specific field in the database.
The database information resides in a content type called 'Parts' and within that content type there is a field called 'cross_reference'.
We have thousands of parts and each one has many cross reference values as the 'cross_reference' field is set to unlimited. I need the autocomplete of the custom form to look through these 'cross_reference' values.
Menu and Page
function frontcross_menu(){
$items['frontcross'] = array(
'title' => 'Front Cross',
'page callback' => 'frontcross_page_callback',
'access arguments' => array('access content'),
'description' => t('Front cross'),
'type' => MENU_CALLBACK,
);
$items['cross/autocomplete'] = array(
'title' => 'Autocomplete for cross',
'page callback' => '_cross_autocomplete',
'access arguments' => array('use autocomplete'),
'type' => MENU_CALLBACK
);
return $items;
}
function frontcross_page_callback(){
return drupal_get_form('frontcross_form');
}
Form
function frontcross_form($form,&$form_state){
$form = array(
'#method' => 'post','#default_value' => 'Status Message',
'#id' => 'frontcross_form',
'field_across_reference_value' => array(
'#type' => 'textfield',
'#required' => FALSE,
'#autocomplete_path' => 'cross/autocomplete',
),
'submit' => array(
'#type' => 'submit',
'#value' => t('Submit'),
'#name' => t('Submit'),
'#id' => t('Submit'),
),
);
$form["#submit"][] = 'frontcross_submit';
return $form;
}
Submit
This function puts the form information into a URL query string on the catalogue results page
function frontcross_submit($form,&$form_state){
$options = array('' => TRUE);
$options['query']['field_cross_reference_value'] = $frontcrossval;
$frontcrossval = trim($form_state['values']['field_across_reference_value']);
if($frontcrossval){
$options['query']['field_cross_reference_value'] = $frontcrossval;
}
$form_state['redirect'] = url($GLOBALS['base_url'].'/cross-reference',$options);
}
Autocomplete Function
This is the part that I am stuck on. It needs to look though the database for values that belong to content type 'Part' and its field 'cross_reference' which has multiple values.
I have left the below code as the example I found.
function _cross_autocomplete($string) {
$matches = array();
$result = db_select('cities', 'c')
->fields('c', array('city'))
->condition('city', '%' . db_like($string) . '%', 'LIKE')
->execute();
foreach ($result as $row) {
$matches[$row->city] = check_plain($row->city);
}
drupal_json_output($matches);
}
I hope my explanation is concise enough. Help will be greatly appreciated.
Thanks
Jo
I want to display custom form (which is custom module) in colorbox in each page.
I have created form in drupal 7 which is working fine if i run it by calling it in url but i need to call this module in colorbox.
my custom module(regform) code is
function regform_init() {
drupal_set_message('Our module is alive!');
}
function regform_menu() {
$items = array();
$items['regform'] = array(
'title' => 'Custom page',
'page callback' => 'drupal_get_form',
'page arguments' => array('regform_form'),
'access arguments' => array('access content'),
'access callback' => TRUE
);
return $items;
}
function regform_form($form, &$form_state) {
$form['#suffix'] = '<div id="test-ajax"></div>';
$form['email'] = array(
'#type' => 'textfield', //you can find a list of available types in the form api
'#title' => 'Enter Email',
'#size' => 50,
'#maxlength' => 50,
'#required' => TRUE, //make this field required
);
$form['submit_button'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#validate' => 'regform_form_validate',
'#ajax' => array(
'callback' => 'regform_form_ajax_callback',
'wrapper' => 'test-ajax'
),
'#submit' => array('regform_form_ajax_callback'),
);
return $form;
}
function regform_form_ajax_callback($form, &$form_state) {
/*Fire database query*/
/*Validation msg div block call here*/
return "<div id='test-ajax'></div>";
}
function regform_form_validate($form, &$form_state) {
if (trim($form_state['values']['email']) == ''){
form_set_error('email', t('Please Enter Email'));
}
if(!valid_email_address($form_state['values']['email'])){
form_set_error('email', t('Enter Valid Email'));
}
}
function regform_form_submit($form, &$form_state) {
$form_state['rebuild'] = TRUE;
$form_state['input'] = array();
}
This form is working fine.
Also I dont have any idea about how to use colorbox in drupal 7.
Any help will be appreciated.
Thanks in Advance.
I suggest to use chaos tools for modal popup form. Its easy to implement and integrate into Drupal 7.
A great example of Ctools modal form is given at here
For modal forms in Drupal, I highly suggest taking a look at chaos tools. It provides a great AJAX API (that can handle the form submission).
There is another module you can take a look at, modal forms. It's built on top of Ctools and provide an easy way to show forms in modal.
I'm trying to understand drupal forms by trial and error (not getting along famously with Drupal Documentation), and I'm a bit confused as why doesn't this work:
function sform() {
$form['password'] = array(
'#type' => 'password',
'#title' => 'enter 1234'
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => '1234 and then click',
);
$form['#method'] = 'post';
return $form;
}
function sform_submit($form_id, $form) {
if (isset($form['values']['password']) && $form['values]']['password'] == "1234") {
drupal_set_message(t('Success;'), '');
}
else {
drupal_set_message("({$form['values']['password']})", 'warning');
drupal_set_message(t('Failure'), 'error');
}
}
I know it all extremely basic and the idea isn't for it to stay in any way like this. As I said I'm just prodding the API to see what works and how.
But the thing is, the basic check is that the "password" field exists and is equal to "1234". And it fails every time. In the failure branch I spit out what value I've got from "password", and I see that it was "1234" nonetheless...
Is there some very obvious reason why the comparison between $form['values']['password'] and "1234" shouldn't be working as I intend here???
You have a typo on your if test:
$form['values]']['password']
//should be
$form['values']['password']
Also it looks like you have your functions setup incorrectly, take a look here: https://api.drupal.org/api/drupal/includes!form.inc/group/form_api/7
You should be passing $form and $form_state (by reference) when using forms.
Taken from link above:
function my_module_example_form($form, &$form_state) {
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function my_module_example_form_validate($form, &$form_state) {
// Validation logic.
}
function my_module_example_form_submit($form, &$form_state) {
// Submission logic.
}
Plus your menu hook should call drupal_get_form as the callback and your function name as the page arguements.
$items['sform'] = array(
'title' => 'My Form',
'page callback' => 'drupal_get_form',
'page arguments' => array('sform'),
'access arguments' => array('some rule'),
);
My custom module code:
<?php
function my_module_menu() {
$items = array();
$items['form-example'] = array(
'title' => 'My Module Form',
'description' => 'A form to mess around with.',
'page callback' => 'drupal_get_form',
'page arguments' => array('my_module_form'),
'access callback' => TRUE
);
return $items;
}
function my_module_form($form, &$form_state, $no_js_use = FALSE) {
$form['file'] = array(
'#type' => 'file',
'#title' => t('Image'),
'#description' => t('Upload an image'),
);
$form['menu'] = array(
'#markup' => '<b>Add More:</b>'
);
$form['#tree'] = TRUE;
$form['names_fieldset'] = array(
'#type' => 'fieldset',
'#title' => t('Add more images'),
'#prefix' => '<div id="names-fieldset-wrapper">',
'#suffix' => '</div>',
);
if (empty($form_state['num_names'])) {
$form_state['num_names'] = 1;
}
for ($i = 0; $i < $form_state['num_names']; $i++) {
$form['names_fieldset']['name'][$i][0]= array(
'#title' => t('Image'),
'#type' => 'file',
'#weight' => '5',
'#description' => t('Upload an image'),
);
}
$form['names_fieldset']['add_name'] = array(
'#type' => 'submit',
'#value' => t('Add one more'),
'#submit' => array('my_module_add_more_add_one'),
'#ajax' => array(
'callback' => 'my_module_add_more_callback',
'wrapper' => 'names-fieldset-wrapper',
),
);
if ($form_state['num_names'] > 1) {
$form['names_fieldset']['remove_name'] = array(
'#type' => 'submit',
'#value' => t('Remove one'),
'#submit' => array('my_module_add_more_remove_one'),
'#ajax' => array(
'callback' => 'my_module_add_more_callback',
'wrapper' => 'names-fieldset-wrapper',
),
);
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
$form['#submit'][] = 'my_module_add_more_submit';
if ($no_js_use) {
if (!empty($form['names_fieldset']['remove_name']['#ajax'])) {
unset($form['names_fieldset']['remove_name']['#ajax']);
}
unset($form['names_fieldset']['add_name']['#ajax']);
}
return $form;
}
function my_module_add_more_callback($form, $form_state) {
return $form['names_fieldset'];
}
function my_module_add_more_add_one($form, &$form_state) {
$form_state['num_names']++;
$form_state['rebuild'] = TRUE;
//$form_state['no_redirect'] = TRUE;
}
function my_module_add_more_remove_one($form, &$form_state) {
if ($form_state['num_names'] > 1) {
$form_state['num_names']--;
}
$form_state['rebuild'] = TRUE;
}
function my_module_add_more_submit($form, &$form_state) {
$file = $form_state['values']['file']."<br \>";
$validators = array();
$file = file_save_upload('file', $validators, 'public://uploads');
print_r($file);
exit();
}
When i submit the form, i am trying to get the details of images, that are added through Add More option. But i am not able to get them. However i am only able to get the details of the first image (and able to upload it).
I want to know two things here:
How can i retrieve the details of the images that are added with Add More option (fieldset), and how can i upload them ?
When i browse and select an image in the fieldset, it is not retained in the form, after adding another image field. How to retain the selected images in fieldset ?
Look at this article -- http://evolvingweb.ca/story/poutine-maker-introduction-field-api-drupal-7-part-1 -- as it has some information on something missing in your code. $delta. $delta is the id assigned to values of fields, even if your field only has 1 item.
What do you see when you var_dump the file field you created? If you get all the information along with those added using 'Add one more' button, you can learn the correct structure of the values using: echo "<pre>"; print_R($form_state['values']); echo "</pre>":
There are a couple of issues with your code.
The first issue is that your submit function only deals with the first upload field which is indeed called "file". But does absolutely nothing to handle the other fields.
A second issue is that it will upload and save the first field every time you click on "Add one more" which will duplicate your upload. You would not experience this issue without AJAX, but if you want to add that, you will.
I would make the following changes:
Remove the $form['#tree'] = TRUE and add it to the fieldset instead. $form['names_fieldsets']['#tree'] = TRUE; after you declare the fieldset of course.
Change the way you declare the file fields in the fieldset (inside the for loop) to this:
for ($i = 0; $i < $form_state['num_names']; $i++) {
$form['names_fieldset'][$i]['name']= array(
'#title' => t('Image'),
'#type' => 'file',
'#weight' => '5',
'#description' => t('Upload an image'),
// We need this to know which file element this is.
// By default drupal would name all as files[names_fieldset]
'#name' => 'files[names_fieldset_' . $i . '_name]',
);
}
I would change the submit function like this (note that I assume you also do my above suggested changes):
function my_module_add_more_submit($form, &$form_state) {
if ($form_state['values']['op'] == 'Submit') {
$validators = array();
$files = array();
if (!empty($_FILES['files']['name']['file'])) {
$files[] = file_save_upload('file', $validators, file_default_scheme() . '://uploads');
}
foreach ($form_state['values']['names_fieldset'] as $name => $field) {
if ($name != 'add_name') {
$file_name = implode('_', $form['names_fieldset'][$name]['name']['#parents']);
if (!empty($_FILES['files']['name'][$file_name])) {
$files[] = file_save_upload($file_name, $validators, file_default_scheme() . '://uploads');
}
}
}
}
}
With this changes we set a form field name aware that's inside a tree. We only trigger uploads when the "Submit" button is clicked and only for form fields that actually had a file added to them. Also we upload using the default scheme and don't use always the public one.
Of course the code need some messages for the user to know how many files did upload, names, or any other deemed worthy info.
I have a Drupal form wherein someone inputs information, and I need to do a database query to check if it is valid before submitting. I would like to either have a button the user can click to check the validity (or have it be done automatically after the user leaves that field), and then display some information about his selection.
I know I can use hook_form_submit to review a form when it is submitted and then stop the process if there are any errors, but I would like the user to be able to confirm they have selected the correct thing before submitting the form.
I haven't personally tried this module, but it might be what you're looking for:
http://drupal.org/project/ajax
If you're just looking for a way to do real-time lookups (e.g. entering the book barcode and getting the title), you can also use Drupal's autocomplete feature, but it will require you to write your own autocomplete function to handle the database lookups.
Take a look at: Basic form with validate handler. You really just need to add a function similar to mymodule_myform_validate($form, &$form_state) { ... }. From the linked page:
"This adds a new form field and a way to validate it with a validate function, also referred to as a validate handler."
<?php
function my_module_menu() {
$items = array();
$items['my_module/form'] = array(
'title' => t('My form'),
'page callback' => 'my_module_form',
'access arguments' => array('access content'),
'description' => t('My form'),
'type' => MENU_CALLBACK,
);
return $items;
}
function my_module_form() {
return drupal_get_form('my_module_my_form');
}
function my_module_my_form($form_state) {
$form['name'] = array(
'#type' => 'fieldset',
'#title' => t('Name'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['name']['first'] = array(
'#type' => 'textfield',
'#title' => t('First name'),
'#required' => TRUE,
'#default_value' => "First name",
'#description' => "Please enter your first name.",
'#size' => 20,
'#maxlength' => 20,
);
$form['name']['last'] = array(
'#type' => 'textfield',
'#title' => t('Last name'),
'#required' => TRUE,
);
// New form field added to permit entry of year of birth.
// The data entered into this field will be validated with
// the default validation function.
$form['year_of_birth'] = array(
'#type' => 'textfield',
'#title' => "Year of birth",
'#description' => 'Format is "YYYY"',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
// This adds a handler/function to validate the data entered into the
// "year of birth" field to make sure it's between the values of 1900
// and 2000. If not, it displays an error. The value report is // $form_state['values'] (see http://drupal.org/node/144132#form-state).
//
// Notice the name of the function. It is simply the name of the form
// followed by '_validate'. This is the default validation function.
function my_module_my_form_validate($form, &$form_state) {
$year_of_birth = $form_state['values']['year_of_birth'];
if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
}
}
?>