Custom Drupal Module, how to post query results to a Form - drupal

I have a custom module that is successfully displaying query results when a user navigates to a particular page, by doing a query that grabs 50 records. I want to use a form to collect user input to create a more specific query.
I have the Form working, it does collect data, it does run the query, but I can't get the results to display on the same form. I've Googled many hours on this and can't find a clear answer. The form looks like:
public function buildForm(array $form, FormStateInterface $form_state){
$form['employee_last_name'] = array(
'#type' => 'textfield',
'#title' => t('Last Name:'),
'#default_value' => (isset($record['LAST_NAME'])) ? $record['LAST_NAME']:'',
'#attributes' => array('class' => array('test')
)
);
When the form returns with a result, I'm trying to write to a form table, but it doesn't seem to work. Do I need to rebuild the form show the form table? I am hoping to display the results on the same page as the form fields. I am iterating on the result and putting it in the $rows variable used in the table declaration
form table:
$form['table'] = [
'#type' => 'table',
'#header' => $header_table,
'#rows' => $rows,
'#empty' => t('No users found'),
];
Thanks

I've just done the following which displays a table of results above a form.
The top of my buildForm function looks like this:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['results'] = $form_state->getValue("results_table");
On the first visit to the page $form_state->getValue("results_table") has no value and so nothing is displayed.
In my submitForm function I do some stuff with the form inputs and then pack the results into $form_state as follows:
public function submitForm(array &$form, FormStateInterface $form_state) {
// do stuff with form values and put results into table rows.
$table = [
'#type' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => "no values"
];
$form_state->setValue("results_table", $table);
$form_state->setRebuild(TRUE);
}
When I submit my filled form I get returned to the form view with a table of results above the form.

Related

Return Symfony Form submitted data as string, not array

I use Symfony 2.7.
Is it possible to get submitted data as string, not as array?
I have a custom form type for searching through records and I want it to have specific output. I want to use GET method on the form, so submitted data could be displayed and used in the querystring right away, without additional redirect:
Form is named search and has fields like
- firstName (text)
- lastName (text)
...
And if submit the form, I want the result NOT to be
search => array(
firstName => 'John',
lastName => 'Doe',
)
But I need it to look like
search => 'firstName:John lastName:Doe'
I tried to use data transformers for this, but no luck so far. Is it possible and how?
form build I am using right now:
$builder
->add('firstname')
->add('lastname')
->add('submit', 'submit')
;
$builder->addModelTransformer(new CallbackTransformer(
function($origData){
return $origData; //no need to set form fields for me
},
function($submitData){
$q = QueryResolver::buildQuery($submitData);
return $q;
}
));
The 'q' variable in second callback then really is
'firstname:john lastname:doe'
but the Request 'search' value is still an array:
'search' =>
'firstname' => 'john'
'lastname' => 'doe'
...
'submit' => ''
'_token' => 'S9k9ZBPaUVz13nNGXn8UoRarxa37IHNWU_AJZGt00H8'

Drupal fields: Passing a variable to view

I have a custom field plugin. It's widget looks somewhat like this:
function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
...
$main_widget = $element + array(
'#test' => 'test',
'#type' => 'textarea',
'#attributes' => array('item_capacity' => 3),
'#theme'=>'mymodule_theme'
);
...
}
I need to get a value of another field, attached to current node, and pass it to this widget's theme file. Can i somehow get at least an id of a node that contains current field from hook_field_widget_form()?
You can use the module Devel to print the value of the $form array which will contain the form information you are looking for.
Example:
dpm($form);
You will be able to easily see the content of the form and access it with php in array form.

How to access form data in hook_form_validate() in drupal 7

I have a form implemented from hook_form called simplequiz_form() I want to access its data after submit below is the code I have written but I can't seem to access its data once its submitted. What am I doing wrong ?
function simplequiz_form_validate($form, &$form_state) {
// here is where we will validate the data and save it in the db.
$thid = db_insert('simplequiz')
->fields(array(
'questions' => &$form_state['question'],
**I can't seem to access the value of a field questions**
))
->execute();
return $thid;
}
Below is my implementation of hook_form()
function simplequiz_form($form, &$form_submit)
{
$form['question'] = array(
'#title' => t('Please input your question'),
'#type' => 'text_format',
'#required' => FALSE,
'#description' => t('Here is where you can enter your questions'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
if I use $form_state['values']['question']
I get the below error:
PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1: INSERT INTO {simplequiz} (questions) VALUES (:db_insert_placeholder_0_value, :db_insert_placeholder_0_format); Array ( [:db_insert_placeholder_0_value] => [:db_insert_placeholder_0_format] => filtered_html ) in simplequiz_form_submit() (line 245 of /home/vishal/Dropbox/sites/dev/sites/all/modules/simplequiz/simplequiz.module).
it worked using $form_state['values']['question']['value']
It's best practice to use hook_form_validate, just for validation purposes, anything other than validation should be done in hook_form_submit.
Either way they both function almost the same way.
All the form data is stored in $form_state['values'], so to access $form['questions'] values, just use $form_state['values']['questions'].

Populate a textarea in a form before rendering with Drupal 7

I am new to writing Drupal forms, and having trouble in what seems the simplest thing of the whole process form namely putting data in a textarea on the form before rendering.
I am using drupal 7
I have all necessary files in the module: i.e. .module, and .info ..
I have used all of these function in my hook_submit() but to no avail.
Form_state['values'][$myElement=]= $myText;
Form_state[$myElement=]= $myText;
form_set_value($form[$myElement], t('$myText'), $form_state);
I flushed the cache before every single attempt:
Nothing seems to work. Here is what is in my submit handler:
mForm_submit(){
//$form_state['values']['sku_output_fieldset']['sku_output'] = t('$gen_sku_txt');
//$form_state['gen_sku']['sku_output_fieldset']['sku_output'] = t('$gen_sku_txt');
//$form['sku_output_fieldset']['sku_output']['#value'] = t('$gen_sku_txt');
//form_set_value($form['sku_output_fieldset']['sku_output'], t('$gen_sku_txt'), $form_state);
//form_set_value($form['sku_output'], t('$gen_sku_txt'), $form_state);
//form_set_value($form['sku_output'], array('rgb' => '123'), $form_state);
//form_set_value($form['sku_output_fieldset']['sku_output'], array('#default_value' => '123'), $form_state);
//form_set_value($form['sku_output_fieldset']['sku_output'], array('#value' => '123'), $form_state);
//form_set_value($form['sku_output_fieldset']['sku_output'], array('value' => '123'), $form_state);
//form_set_value($form['sku_output_fieldset']['sku_output'], array('default_value' => '123'), $form_state);
$form_state['rebuild'] = TRUE;
}
all commented code, is what i have tried and did not work.
Are you building the form with Drupal 7 Form API? This is how I've inserted default text into a textarea in a Drupal form:
$form['formname_fieldname'] = array(
'#default_value' => t('Some default text'),
'#title' => t('Field Title'),
'#type' => 'textarea',
'#required' => FALSE,
'#rows' => 10,
);
Your textarea will be prepopulated with "Some default text"
If you want to change it before rendering, you shouldn't have in a submit function.
You should use hook_form_alter(&$form, &$form_state, $form_id) where the $form being passed in is the variable you can use to edit the form.

How do i get the data?(Drupal 6.x)

I have this form which accepts user’s input. What I like to do is, base on that user input, I’d like to retrieve data and display it back to user.
So far, I have implemented hook_menu and registered respective url of the form, and implemented a submit function referred by “#submit” attribute of submit button. I’ve also implemented data retrieval code and works great.
Here’s my problem – I don’t know how to display retrieved data. I’ve tried several approaches in an attempt to find the solution.
First, with theme function, hoping that printing the return value of it would display the data. Second, setting “#action” element of form array with newly registered url, as I thought using the same url as form would only cause drupal to return that form instead and not my data. So, I creates a static variable and stores all the retrieved data in it;this is done inside submit function by the way. When I checked this variable inside menu callback, this variable is not set.
To summarize my problem, form has different access url than form submit, such as
Form url – http://....?q=mymodule/form
Submit url (value of ”#action”) – http://....?q=mymodule/execute
, and the data I’ve set inside submit function to static variable is not available in menu callback. How do I make the data available?
Here’s part of my code -
static $retrieved_data;
function mymodule_menu() {
$command = array();
$command['mymodule/form'] = array(
'title' => 'user input',
'page callback' => 'response',
'page arguments' => array('form'),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
$command['mymodule/execute'] = array(
'title' => 'Search',
'page callback' => 'response',
'page arguments' => array('execute'),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $command;
}
function _response($paRequest){
switch($paRequest){
case "form":
return drupal_get_form("_myform");
break;
case "execute":
return $retrieved_data;
break;
}
}
function _myform(&$form_state) {
$form['#action'] = url($base_path)."?mymodule/execute";
.....
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#submit' => array('_data_retrieve'),
);
return $form;
}
function _data_retrieve($form, &$form_state){
/*data retrieval code*/
........................
$retrieved_data = db_fetch_object($result);
}
Thanks a bunch
Your method seems a bit complicated there. When I make systems with a form, I tend to do it this way. In your MYMODULE_menu() I would change the 'page arguments' => array('form'), to 'page arguments' => array('NAME_OF_FORM_FUNCTION'), where NAME_OF_FORM_FUNCTION would be _myform in this case. I would rename it to MYMODULE_MYFORMNAME.
then create a function:
MYMODULE_MYFORMNAME_SUBMIT($form, &$state) {
// Enter code here to save the data from the form that is stored in $state
// to the database with an SQL query or a node_save($node) if you are
// creating a node.
}
After that you can retrieve the data from the database in your _data_retrieve function and call that on the page where you want to retrieve the data.

Resources