drupal #default_value not applied in select option in drupal_render - drupal-7

I try to print a drupal 'select option' element in a form .I think drupal_render not applying #default_value.every thing is ok except #default_value not applied.
where is the problem?anybody know how i can do this?
do #default_value accept string value?
this is pseudo of my codes:
function test_menu(){
$items=array();
$items['admin/config/regional/test']=array(
'title' => 'test',
'description' => t('test'),
'page callback' =>'drupal_get_form',
'page arguments' => array('test_function'),
);
$items[]=array();
return $items;
}
function test_function(){
$header = array
(
'test1' => t('test1'),
'test2'=> t('test2'),
);
$a=(1,2,3);
$$options=array();
foreach($a as $i=>$v)
{
$f['type'] = array(
'#type' => 'select',
'#options' => array(1,2,3,4),
'#default_value'=>1,
);
$options += array($name=>array( 'test1' => $v,
'test2'=> drupal_render($f['type']) ,
}
$form['table'] = array
(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
'#multiple' => FALSE
//'#empty' => t('No users found'),
);
$form['submit'] = array
(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
I test textfield but its also not work and not accept #default_value in drupal_render
$f['test3']=array(
'#type'=>'textfield',
'#title'=>'test3',
'#default_value' =>'aaa',
);
I suppose this is beacuse using drupal_render .anybody have a solution?

In Drupal_render 's used in drupal_get_form , #default_value not set use must use #value instaed of it.
$f['type'] = array(
'#type' => 'select',
'#options' => drupal_map_assoc(array('1','2','3','4')),
'#value'=> '1',
);

The following code doesn`t work:
$form['title'] = array(
'#type' => 'select',
'#options' => drupal_map_assoc(array(t('opt1'), t('opt3'), t('opt4'), t('opt5'), t('opt6'))),
'#default_value' => array($default_value_key));
$form['title1'] = array(
'#type' => 'select',
'#options' => drupal_map_assoc(array(t('opt1'), t('opt3'), t('opt4'), t('opt5'), t('opt6'))),
'#default_value' => array($default_value_key));
return $form;
But then i did the following:
$form['group'] = array('#tree' => TRUE);
$form['group']['title'] = array(
'#type' => 'select',
'#options' => drupal_map_assoc(array(t('opt1'), t('opt3'), t('opt4'), t('opt5'), t('opt6'))),
'#default_value' => array($default_value_key));
$form['group']['title1'] = array(
'#type' => 'select',
'#options' => drupal_map_assoc(array(t('opt1'), t('opt3'), t('opt4'), t('opt5'), t('opt6'))),
'#default_value' => array($default_value_key));
return $form;
And default values now works.

I have the same problem. finally, i found one method. As you said, the default_value does not work. So make the default_value fixed as 0. and change the options array, put the default value on the top.

If you look at the example from Drupal's Form API, you'll see that the #options setting takes a key-value pair array and in the #default_value, you should specify the key of the default value, not the string value.
Also, according to documentation for the #options setting, #options is expecting String values. So your select should be more like:
$f['type'] = array(
'#type' => 'select',
'#options' => drupal_map_assoc(array('1','2','3','4')),
'#default_value'=> '1',
);

Related

Drupal 7 - set input value depending select value

I create a hook_form_alter and i want to change the input value depending on a select option.
I catch the name value :
global $user;
$user_fields = user_load($user->uid);
$name = $user_fields->field_user_name['und']['0']['value'];
Actually i use form states :
$form['field_name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#default_value' => $name,
'#weight' => 4,
'#states' => array(
'visible' => array(
'select[name="who_is_registering"]' => array('value' => REGISTRATION_REGISTRANT_TYPE_ANON),
'#default_value' => '',
),
'required' => array(
'select[name="who_is_registering"]' => array('value' => REGISTRATION_REGISTRANT_TYPE_ANON),
),
),
);
the goal is to set the name if the select value is different from anon (REGISTRATION_REGISTRANT_TYPE_ANON) and hide the input ... and to show an empty field on the other case.

drupal 7 ajax framework example does not work

I want to add one form in user profile page. So i created user-profiled.tpl.php. In that template,i just copied the example from ajax framework for testing. Here is the whole codes:
function ajax_example_simplest($form, &$form_state) {
$form = array();
$form['changethis'] = array(
'#type' => 'select',
'#options' => array(
'one' => 'one',
'two' => 'two',
'three' => 'three',
),
'#ajax' => array(
'callback' => 'ajax_example_simplest_callback',
'wrapper' => 'replace_textfield_div',
),
);
$form['replace_textfield'] = array(
'#type' => 'textfield',
'#title' => t("The default value will be changed"),
'#description' => t("Say something about why you chose") . "'" .
(!empty($form_state['values']['changethis'])
? $form_state['values']['changethis'] : t("Not changed yet")) . "'",
'#prefix' => '<div id="replace_textfield_div">',
'#suffix' => '</div>',
);
return $form;
}
function ajax_example_simplest_callback($form, $form_state) {
return $form['replace_textfield'];
}
I am confusing now. After i clicked the checkbox, nothing change in textfield. My jquery version is 1.9. Is there any other constraints?
The change is in description and not in textfield(I did the same error first as you did). However I have updated the code so it also shows the value in 'textfield'.
function ajax_example_simplest($form, &$form_state)
{
$form = array();
$form['changethis'] = array(
'#type' => 'select',
'#options' => array(
'one' => 'one',
'two' => 'two',
'three' => 'three',
),
'#ajax' => array(
'callback' => 'ajax_example_simplest_callback2',
'wrapper' => 'replace_textfield_div',
),
);
$number = (!empty($form_state['values']['changethis']) ? $form_state['values']['changethis'] : t("Not changed yet"));
$form['replace_textfield'] = array(
'#type' => 'textfield',
'#title' => t("The default value will be changed"),
// Not that value was changed in the description
'#description' => t("Say something about why you chose") . " '" . $number . "'",
// Also add next line if you want to see it in the text box
'#value' => $number,
'#prefix' => '<div id="replace_textfield_div">',
'#suffix' => '</div>',
);
return $form;
}
function ajax_example_simplest_callback2($form, $form_state) {
return $form['replace_textfield'];
}

form submission in Drupal

i have made a custom module for form in drupal using dupal API,and made a table in my database
What i want is to save the value of drop down box instead of it's index into database...my .module file is:
<?php
function form_test_menu() {
$items['formtest'] = array(
'title' => 'Form Test',
'page callback' => 'drupal_get_form',
'page arguments' => array('form_test_form'),
'access callback' => TRUE,
);
return $items;
}
function form_test_form($form,&$form_submit) {
$form['name'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['college'] = array(
'#title' => t('College/University'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['education'] = array(
'#title' => t('Education'),
'#type' => 'select',
'#description' => 'Select your higher education .',
'#options' => array(t('--- SELECT ---'), t('B.tech'), t('MCA'), t('MBA'),t('Graduate')),
'#required' => TRUE,
);
$form['percentage'] = array(
'#title' => t('Percentage/CGPA'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['application'] = array(
'#title' => t('Job Applied'),
'#type' => 'select',
'#options' => array(t('---select---'),t('Web Developer'),t('Web Designer'),t('SEO'),t('Marketing')),
'#required' => TRUE,
);
$form['submit'] = array(
'#value' => 'Submit',
'#type' => 'submit',
);
return $form;
}
function form_test_form_submit($form, $form_state) {
global $user;
// Here u can insert Your custom form values into your custom table.
db_insert('drupal')
->fields(array(
'name' => $form_state['values']['name'],
'college' => $form_state['values']['college'],
'education' => $form_state['values']['education'],
'percentage' => $form_state['values']['percentage'],
'application' => $form_state['values']['application'],
))->execute();
drupal_set_message("successfully saved data");
}
?>
All are in one file(.module)....any help will be appreciated.
Thank you.
The solution is to pass options array from one function to another. To achieve that use the second argument of "form_test_form" and "form_test_form_submit" functions.
function form_test_form($form,&$form_submit) {
$form_submit['myoptions'] = array(' select', 'option1' .....
}
Then
function form_test_form_submit($form,&$form_state) {
$myoptions = $form_state['myoptions']; etc ...
}

CakeDC Search and Tag plugin - search for multiple tags

Hopefully I'm missing something simple here. I'm using the CakeDC Search and Tags plugin for my cake (2.3.4) app.
Along with generic search by field functionality I want the user to be able to search by tags. I've almost got this working but the search will only display results if you search for a single tag not multiples. For example, if I add an article with the following tags - black, white, red. The article will only show in the search results if I search for a single tag (say, black) and not all 3, or even 2... What am I missing?
Heres my code:
Article.php model
class Article extends AppModel {
public $actsAs = array(
'Upload.Upload' => array(
'screenshot1' => array (
'fields' => array (
'dir' => 'dir'
),
'thumbnailMethod' => 'php',
'thumbnailSizes' => array(
'xvga' => '1024x768',
'vga' => '640x480',
'thumb' => '80x80'
),
),
),
'Search.Searchable',
'Tags.Taggable'
);
// Search plugin filters
public $filterArgs = array(
'title' => array('type' => 'like'),
'environment' => array('type' => 'like'),
'description' => array('type' => 'like'),
'error' => array('type' => 'like'),
'cause' => array('type' => 'like'),
'resolution' => array('type' => 'like'),
'live' => array('type' => 'value'),
'synced' => array('type' => 'value'),
'tags' => array('type' => 'subquery', 'method' => 'findByTags', 'field' => 'Article.id'),
array('name' => 'search', 'type' => 'query', 'method' => 'filterQuery'),
);
// This is the OR query that runs when the user uses the client side signle field search
public function filterQuery($data = array()) {
if(empty($data['search'])) { // search is the name of my search field
return array();
}
$query = '%'.$data['search'].'%';
return array(
'OR' => array(
'Article.title LIKE' => $query,
'Article.description LIKE' => $query,
'Article.error LIKE' => $query,
)
);
}
// Find by tags method
public function findByTags($data = array()) {
$this->Tagged->Behaviors->attach('Containable', array('autoFields' => false));
$this->Tagged->Behaviors->attach('Search.Searchable');
$query = $this->Tagged->getQuery('all', array(
'conditions' => array('Tag.name' => $data['tags']),
'fields' => array('foreign_key'),
'contain' => array('Tag')
));
return $query;
}
public $hasAndBelongsToMany = array(
'Category' => array(
'className' => 'Category',
'joinTable' => 'articles_categories',
'foreignKey' => 'article_id',
'associationForeignKey' => 'category_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
),
'Tag' => array('with' => 'Tagged')
);
Controller method
public function admin_advancedSearch() {
// Disable validation for this action
$this->Article->validate = array();
// For search plugin
$this->Prg->commonProcess();
// Set searched for details
$this->set('searchedFor', $this->passedArgs);
// If passed args are all empty
if ($this->passedArgs) {
if (empty($this->passedArgs['title']) AND
empty($this->passedArgs['environment']) AND
empty($this->passedArgs['description']) AND
empty($this->passedArgs['error']) AND
empty($this->passedArgs['cause']) AND
empty($this->passedArgs['resolution']) AND
empty($this->passedArgs['live']) AND
empty($this->passedArgs['synced']) AND
empty($this->passedArgs['tags'])) {
$this->Session->setFlash('Please enter at least one search criteria', 'flash_failure');
// Set this var for checks in view
$this->set('emptySeach', true);
} else {
$paginateConditions = $this->Article->parseCriteria($this->passedArgs);
$this->paginate = array('conditions' => array(
$paginateConditions),
'limit' => 10,
'order' => array('Article.modified' => 'DESC'));
$this->set('articles', $this->paginate());
// Count number of results
$count = 0;
foreach ($this->paginate() as $result) {
$count++;
}
$this->set('resultsCount', $count);
// Search was not empty - set flag for view
$this->set('emptySeach', false);
}
}
// Set layout
$this->layout = 'admin';
//debug($this->passedArgs);
}
All plugins are loaded successfully from bootstrap, searches work fine without tags. Searches with tags only work if one tag is entered....
*EDIT *
If I debug $query from the findByTags method I get this:
'SELECT `Tagged`.`foreign_key` FROM `knowledgebase`.`tagged` AS `Tagged` LEFT JOIN `knowledgebase`.`tags` AS `Tag` ON (`Tagged`.`tag_id` = `Tag`.`id`) WHERE `Tag`.`name` = 'kia, rio, red''
So it looks like its trying to find a single tag with all the searched for tags in its name. How can I make the WHERE part an IN?
For example:
WHERE `Tag`.`name` IN ('kia', 'rio', 'red')
Thanks
Use the "method" https://github.com/cakedc/search#behavior-and-model-configuration key her to pass the search args to a customized method.
The example here shows you exactly how this works https://github.com/cakedc/search#full-example-for-modelcontroller-configuration-with-overriding
public $filterArgs = array(
'some_related_table_id' => array('type' => 'value'),
'search'=> array('type' => 'like', 'encode' => true, 'before' => false, 'after' => false, 'field' => array('ThisModel.name', 'OtherModel.name')),
'name'=> array('type' => 'query', 'method' => 'searchNameCondition')
);
public function searchNameCondition($data = array()) {
$filter = $data['name'];
$cond = array(
'OR' => array(
$this->alias . '.name LIKE' => '' . $this->formatLike($filter) . '',
$this->alias . '.invoice_number LIKE' => '' . $this->formatLike($filter) . '',
));
return $cond;
}
Inside your custom method explode() the tags and make them an array so that CakePHP is using them as IN() or better (in can become slow) make it a chain of AND or OR.

drupal admin.inc, loop list_modules as form settings

I need to loop the values of this
$blocks = array();
$blocks['list_modules']
with this:
$form['advanced']['custom_acc'] = array(
'#type' => 'select',
'#title' => t('module title'),
'#options' => array(
0 => t('No control'),
1 => t('Controlled'),
),
);
so it should become something like this
while (list(, $value) = each($blocks)) {
echo "
$form['advanced']['custom_->blocks array value'] = array(
'#type' => 'select',
'#title' => t('->blocks array value'),
'#options' => array(
0 => t('No control'),
1 => t('Controlled'),
),
);
";
}
but of course this is not working, got any ideas? I guess I have to use an foreach, I hope you can see what Im trying to achieve,
thanks in advance!
fixed it myself :)
$blocks = array();
$blocks = module_list();
foreach ($blocks as $key => $title) {
$form['advanced'][$title] = array(
'#type' => 'select',
'#title' => t($title),
'#options' => array(
0 => t('No control'),
1 => t('Controlled'),
),
);
}

Resources