Edit form in drupal module? - forms

I have a problem making Drupal module .
I created a form for adding into database but i am having no luck with creating form to edit some record here is my problem.
The problem is when i load values into form load from database and change them and then click submit button form refresh before it submit new values. So it updates into database same thing as it was. Here is a code :
function edit_form($form, &$form_state) {
$query = db_select('activity', 'f')
->fields('f')
->condition('IDA', $_GET['edit']);
$thefile = $query->execute();
$title = "";
$desc = "";
$file = "";
$privacy = "";
while($record = $thefile->fetchAssoc())
{
$title = $record['title'];
$desc = $record['description'];ick submit button form refresh before it submit new values. So it updates into database same thing as it was. Here is a good :
function edit_form($form, &$form_state) {
$query = db_select('activity', 'f') ->fields('f') ->co
$file = $record['trainingresource'];
$privacy = $record['privacy'];
}
$form['activity'] = array(
'#type' => 'fieldset',
'#title' => t('Create a new activity'),
'#tree' => TRUE,
);
$form['activity']['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#description' => t('Please enter the title here.'),
'#value' => t($title),
);
$form['activity']['description'] = array(
'#type' => 'textarea',
'#title' => t('Enter Description'),
'#value' => t($desc),
'#description' => t('Please put description here.'),
);
/* $form['activity']['date'] = array(
'#type' => 'date',
'#title' => t('Enter activity date'),
'#description' => t('Please put activity date in here.'),
); */
$form['activity']['file'] = array(
'#type' => 'file',
'#title' => t('Submit activity file'),
'#value' => t($file),
'#description' => t('Please files in here.'),
);
$form['activity']['security'] = array(
'#type' => 'radios',
'#title' => t('Privacy'),
'#value' => t($privacy),
'#options' => array('True'=>t('True'),'False'=>t('False')),
);
// Description
$form['hidden'] = array('#type' => 'value', '#value' => 'is_it_here');
$form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
return $form;
}
And here is a submit form code:
function edit_form_submit($form, $form_state) {
$idt = $_GET['edit'];
$title = trim($form_state['values']['activity']['title']);
$desc = trim($form_state['values']['activity']['description']);
//$date = trim($form_state['values']['activity']['date']['year']."-".$form_state['values']['activity']['date']['month']."-".$form_state['values']['activity']['date']['day']);
$file = "file";
$privacy = trim($form_state['values']['activity']['security']['#value']);
$nid = db_update('activity') // Table name no longer needs {}
->fields(array(
'title' => $title,
'description' => $desc,
//'date' => $date,
'trainingresource' => $file,
'privacy' => $privacy,
))
->condition('IDA', $idt,'=')
->execute();
drupal_set_message($idt);
drupal_set_message("Added into database");
drupal_goto('activity', array('query'=>array(
'activ'=>$_GET['activ'],
)));
}
If someone have the same problem or know how to solve this problem , please help me .
Thanks in advance.

First of all i would like to point out your example code has been pasted wrongly. I see two declaration of same function edit_form.
Am assuming the first declaration was a wrong paste and continuing to answer this.
The major issue i have seeen in your form declaration is that you are using "#value" to store the a default value. Please use "#default_value".
If you use #value, it ignores the user submitted values.
Read more about use of #value.
Read more about use of #default_value
For example change,
$form['activity']['description'] = array(
'#type' => 'textarea',
'#title' => t('Enter Description'),
'#value' => t($desc),
'#description' => t('Please put description here.'),
);
to
$form['activity']['description'] = array(
'#type' => 'textarea',
'#title' => t('Enter Description'),
'#default_value' => t($desc),
'#description' => t('Please put description here.'),
);
Also i strongly recommend you to check this link which is a module that provides lots of examples to interact with Drupal.

Related

Drupal7 managed_file form

I have this managed_file form in a Drupal customized module, with this form a user can upload an image and saved it under sites/default/files.
$form['Background_image'] = array(
'#type' => 'managed_file',
'#title' => t('Image'),
'#progress_message' => t('Please wait...'),
'#progress_indicator' => 'bar',
'#description' => t('Click "Browse..." to select an image to upload.'),
'#required' => TRUE,
///'#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
'#upload_location' => 'public://backgroundimage/'
'#default_value' => $this->options['Background image'],
);
how to add a function to get the uploaded file?
I tried this but it didnt work.
$image = file_load($form_state['values']['Background_image']);
You should be able to just create the form element, and then use the $form_state['values'] array to get the fid. like this:
function my_module_form() {
$form = array();
$form['background_image'] = array(
'#type' => 'managed_file',
'#title' => t('Image'),
'#progress_message' => t('Please wait...'),
'#progress_indicator' => 'bar',
'#description' => t('Click "Browse..." to select an image to upload.'),
'#required' => TRUE,
'#upload_location' => 'public://backgroundimage/',
'#default_value' => $this->options['background image'] //fid
);
return $form;
}
function my_module_form_submit($form, &$form_state) {
$file = file_load($form_state['values']['background_image']);
$file->status = FILE_STATUS_PERMANENT;
file_usage_add($file, 'module_name', 'entity_name', $entity_id);
file_save($file);
}
I just wrote that on the fly so I'm sure there are syntax errors :) but that's the idea. If you are not getting the file id from $form_state['values']['background_image'], I would try dying in your submit handler and dumping the contents of $form_state['values']:
function my_module_form_submit($form, &$form_state) {
die(var_dump($form_state['values']['background_image']));
}
That should tell you a few things about whats being returned from your form.

#value not being changed in custom drupal form

I have created a custom drupal 7 form with a submit button. when submit is pressed the values in $form_state['values'] are not changed. see the code below:
$form[$tag] = array(
'#title' => t($tag),
'#type' => 'textfield',
'#default_value' => !empty($form_state['values'][$tag]) ? $form_state['values'][$tag] : $value,
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#weight' => 5,
'#submit' => array('xml_form_builder_edit_datastream_form_submit'),
);
Then the submit function is:
function xml_form_builder_edit_datastream_form_submit($form, &$form_state){
dsm('SUBMITTED');
dpm($form);
dpm($form_state);
dsm('SUBEND');
}
the $form_id is 'xml_form_builder_edit_datastream_form'.
Ive been trying to figure this out for a good few hours.
Anyone got any ideas?
Try $form_state['input'][$tag] , that should have the user input value.

How to load a drupal form with data from an external webservice

I am relatively new to Drupal (7) and PHP so this may be a bit of a basic question through I have not managed to find
out what I needed in the questions so far, hence the post.
I have a drupal site that will connect to a simple CRUD REST webservice(.net 4) to retreive and post data.
I have been finding it difficult to determine how to load the data obtained from the website into a simple drupal form.
The data will be transfered via JSON format but I an not sure how to retreive the data from the response array and populate
the fields of the form with the data obtained from the website. Assume the JSON fields returned match the form field names.
In my example I have the http_request in the submit function through really it should be in a page load function.
So the questions are :
how to you populate the fields of the form from the retreived data ?
What is the syntax to get the data out of the json_array?
The data needs to be retrieved when the page loads, what is the best way of acheiveing this ?
Here is the example code , I have been playing around in the submit. I have put a rebuilt in , is this the best way to
persist the data on the screen ? I have tried to reset the 'Surname' field to a new value but no joy..
<?php
/**
* #file
* Test activation form
*/
/**
* Implements hook_menu()
*/
function activation_menu() {
$items['activation'] = array(
'title' => 'Registration form',
'page callback' => 'drupal_get_form',
'page arguments' => array('activation_nameform'),
'access callback' => TRUE,
// 'access_callback' => TRUE,
'type' => MENU_NORMAL_ITEM
);
return $items;
}
/**
* Define the form
*/
function activation_nameform() {
$form['Firstname'] = array(
'#Firstname' => t('Firstname'),
'#type' => 'textfield',
'#maxlength'=> 50,
'#description' => t('Please enter your First name.'),
);
$form['Surname'] = array(
'#Surname' => t('Surname'),
'#type' => 'textfield',
'#maxlength'=> 50,
'#description' => t('Please enter your Surname.'),
);
$form['Username'] = array(
'#Username' => t('Username'),
'#type' => 'textfield',
'#maxlength'=> 100,
'#description' => t('Please enter your Username.'),
);
$form['Password'] = array(
'#Password' => t('Password'),
'#type' => 'textfield',
'#maxlength'=> 8,
'#description' => t('Please enter your Surname.'),
);
$form['Organisation'] = array(
'#Organisation' => t('Organisation'),
'#type' => 'textfield',
'#maxlength'=> 50,
'#description' => t('Please enter your Organisation.'),
);
$form['Address1'] = array(
'#Address1' => t('Address1'),
'#type' => 'textfield',
'#maxlength'=> 150,
'#description' => t('Please enter your first full line of Address.'),
);
$form['Address2'] = array(
'#Address2' => t('Address'),
'#type' => 'textfield',
'#maxlength'=> 150,
'#description' => t('Please enter your second full line of Address.'),
);
$form['Town_city'] = array(
'#Town_city' => t('Town_city'),
'#type' => 'textfield',
'#maxlength'=> 50,
'#description' => t('Please enter your Town or City.'),
);
$form['Region'] = array(
'#Region' => t('Region'),
'#type' => 'textfield',
'#maxlength'=> 50,
'#description' => t('Please enter your Region.'),
);
$form['PostCode'] = array(
'#PostCode' => t('PostCode'),
'#type' => 'textfield',
'#maxlength'=> 10,
'#description' => t('Please enter your PostCode.'),
);
$form['Postcode'] = array(
'#Postcode' => t('Postcode'),
'#type' => 'textfield',
'#maxlength'=> 15,
'#description' => t('Please enter your Postcode or ZIP code.'),
);
$form['Country_options'] = array(
'#type' => 'value',
'#value'=> array(t('UK'),t('Europe'),t('USA')),
);
$form['Country']['favourite_country'] = array(
'#title' => t('Favourite Country'),
'#type' => 'select',
'#value'=> array(t('UK'),t('Europe'),t('USA')),
'#description' => t('Please enter your Country'),
'#options' => $form['Country_options']['#value']
);
$form['Status'] = array(
'#Status' => t('Status'),
'#type' => 'textfield',
'#maxlength'=> 150,
'#description' => t('Please enter your first full line of Address.'),
);
$form['Add_credits'] = array(
'#Add_credits' => t('Add_credits'),
'#type' => 'textfield',
'#maxlength'=> 15,
'#description' => t('Please enter additional credits'),
);
$form['TandC'] = array(
'#TandC' => t('TandC'),
'#type' => 'textfield',
'#maxlength'=> 5,
'#description' => t('TandC'),
'#value'=> 30
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
return $form;
}
/**
* Handle post - validation form submission
*/
function activation_nameform_submit($form,&$form_state) {
$name = $form_state['values']['Firstname'];
drupal_set_message(t('Thanks ,%name',
array('%name' => $name)));
$request = drupal_http_request('http://somewebsite.com/Customers/?ID=10');
$jsonarray =drupal_json_decode($request->data);
$form_state['rebuild']=TRUE;
$form['Surname']['#value']='Hello mother';
}
Continuation of answer
by using
echo '<pre>';var_dump($request); echo '</pre>'
I can now see the request information:
["data"]=>
string(346) "?{"CustomerID":10,"FirstName":"Howard Philip","LastName":"Lovecraft","Organisation":"superglue","AddressID":null,"Status":0,"Credits":0,"Type":0,"ExpiryDate":"0001-01-01T00:00:00","UserName":"xxx#hotmail.com","Password":"","CustomerIconURL":"","CountryCode":"","LastUpdated":null,"DateCreated":"2013-04-18T07:43:10.123","ApplicationID":null}"
["protocol"]=>
string(8) "HTTP/1.1"
["status_message"]=>
string(2) "OK"
["headers"]=>
array(6) {
["content-length"]=>
string(3) "346"
["content-type"]=>
string(31) "application/json; charset=utf-8"
["server"]=>
string(17) "Microsoft-IIS/7.5"
["x-powered-by"]=>
string(7) "ASP.NET"
["date"]=>
string(29) "Fri, 14 Jun 2013 12:00:35 GMT"
["connection"]=>
string(5) "close"
}
["code"]=>
string(3) "200"
}
So will now implement the suggestion below ...
..So full answer to the question is , code for populating the fields shown below/**
* Define the form
*/
function activation_nameform() {
$request = drupal_http_request('http://somewebsite.com/ML5/MLSvrSvc.svc/Customers/?ID=10');
$jsonarray = $request->data;
//$jsonarray =json_decode('{"CustomerID":10,"FirstName":"Howard Philip","LastName":"Lovecraft","Organisation":"superglue","AddressID":null,"Status":0,"Credits":0,"Type":0,"ExpiryDate":"0001-01-01T00:00:00","UserName":"xxx#hotmail.com","Password":"","CustomerIconURL":"","CountryCode":"","LastUpdated":null,"DateCreated":"2013-04-18T07:43:10.123","ApplicationID":null}',TRUE);
echo '<pre2>';var_dump($jsonarray); echo '</pre2>';
$form['Firstname'] = array(
'#Firstname' => t('FirstName'),
'#type' => 'textfield',
'#maxlength'=> 50,
'#description' => t('Please enter your First name.'),
'#default_value' => $jsonarray['FirstName'],
);
.
.
.etc
However there is a parsing issue with the json coming from the windows 7 /.net 64 bit system hence the test json string... Have tried most of the utf8 encoding functions and the preg_replace examples , but no joy still progress today... Perhaps another question, we'll see.
In my example I have the http_request in the submit function through really it should be in a page load function.
I would do it this way
1) Get the values when defining the form ie activation_nameform()
2) Use key default values to assign it.
'#default_value' => // your variable here
3) Do a printr function do xdebug session to make sure json object is getting converted. I rem I had some problems with that before.
If the above does not work then I would look into hook_form_alter function.
4) The return type is an array so you can acess it $var[1]
$request = drupal_http_request('https://api.twitter.com/1/users/show.json? screen_name=TwitterAPI&include_entities=true');
$var= drupal_json_decode($request->data);
print $var[1]; // this should contain your value and then you can place for the default value.
reference - http://webwash.net/articles/getting-started-json-drupal-7
https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_json_decode/7
http://in3.php.net/json_decode

Drupal form API checkboxes hierarchy

I am trying to setup a configuration page consisting of hierarchical checkboxes like the following:
-Parent#1
--option#1
--option#2
-Parent#2
--option#1
--option#2
To achieve the above layout, I am using the following code:
$form['categories']['templates']['parent1'] = array(
'#type' => 'checkboxes',
'#title' => t('Select the appropriate actions for the form based on the indicated template'),
'#options' => array("Parent#1"),
'#multiple' => TRUE,
);
$form['categories']['templates']['parent1']['actions'] = array(
'#type' => 'checkboxes',
'#options' => array("P1 - option#1", "P1 - option#2"),
'#multiple' => TRUE,
);
$form['categories']['templates']['parent2'] = array(
'#type' => 'checkboxes',
'#title' => t('Select the appropriate actions for the form based on the indicated template'),
'#options' => array("Parent#2"),
'#multiple' => TRUE,
);
$form['categories']['templates']['parent2']['actions'] = array(
'#type' => 'checkboxes',
'#options' => array("P2 - option#1", "P2 - option#2"),
'#multiple' => TRUE,
);
But the effect I am getting to not as desired. I attached an image of what the code is generating:
You can use the new Form API feature, #states to achieve this.
Note that, for ease of use, I'm wrapping the conditional checkboxes with a fieldset.
<?php
$form['categories']['templates']['parent1'] = array(
'#type' => 'checkboxes',
'#title' => t('Select the appropriate actions for the form based on the indicated template'),
'#options' => array(1 => 'Parent#1'), // Note this! You can't use 0 as a key in #options.
'#multiple' => TRUE,
);
$form['categories']['templates']['parent1']['wrapper'] = array(
'#type' => 'fieldset',
'#title' => t('Options for #option', array('#option' => 'Parent#1')),
'#states' => array(
'visible' => array(
':input[name="parent1[1]"]' => array('checked' => TRUE), // We use "parent1" and its Nth option. in above field, See #options in above checkboxes field.
),
),
);
$form['categories']['templates']['parent1']['wrapper']['actions'] = array(
'#type' => 'checkboxes',
'#options' => array("P1 - option#1", "P1 - option#2"), // This is also wrong. You must define a key => value pair for #options or somehow avoid using 0 as the key.
'#multiple' => TRUE,
);
?>
You might want to use #tree => TRUE in the fieldsets to avoid Drupal from merging same keys' values together.
Also, you won't need #multiple in checkboxes field type.
Update
Example with node types:
<?php
$node_types = node_type_get_names();
$form['categories']['templates']['parent1'] = array(
'#type' => 'checkboxes',
'#title' => t('Select the appropriate actions for the form based on the indicated template'),
'#options' => $node_types,
);
foreach ($node_types as $type => $label) {
$form['categories']['templates']['node-options'.$type] = array(
'#type' => 'checkboxes',
'#title' => t('Options for #type', array('#type' => $label)),
'#options' => array("Parent#1"),
'#multiple' => TRUE,
'#states' => array(
'visible' => array(
':input[name="parent1['.$type.']"]' => array('checked' => TRUE), // We use "parent1" and its Nth option. in above field, See #options in above checkboxes field.
),
),
);
}

Drupal - #states visible option not working with the date type

I am trying to create a filtering form for a Drupal module that show hours. I am trying to get a date field to only show if the user wants to filter by it. I have a text field further down in the code that is hiding. I am not sure what I should do. Here is my code for the field:
$form['filters']['start-do'] = array(
'#type' => 'checkbox',
'#title' => t('Filter by start date'),
);
$form['filters']['start'] = array(
'#type' => 'date',
'#title' => t('Start Date'),
'#description' => t('Show hours that started after this date.'),
'#states' => array(
'invisible' => array(
':input[name="start-do"]' => array('checked' => FALSE)
)
)
);
You have forgotten about "container" type form element in your example.
Try something like this:
$form['filters']['start-do'] = array(
'#type' => 'checkbox',
'#title' => t('Filter by start date'),
);
$form['filters']['container'] = array(
'#type' => 'container',
'#states' => array(
'invisible' => array(
'input[name="start-do"]' => array('checked' => FALSE)
)
)
);
$form['filters']['container']['start'] = array(
'#type' => 'date',
'#title' => t('Start Date'),
'#description' => t('Show hours that started after this date.'),
);
It's always worth to check Forms API reference: http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#states