Adding values to checkboxes from db table - drupal-7

I am quite new to drupal 7. I need to add names which come from db table into checkboxes. How do i do that? I have written my callback form function below:
function page_second_callback_form($form){
$result = db_query('SELECT n.names FROM {my_test_tab} n');
$output ='';
foreach($result as $item) {
$output .= $item->names;
}
$opt = array($output => $output,);
$form['check'] = array(
'#type' => 'fieldset',
'#title' => 'some',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['check']['chk_box'] = array(
'#type' => 'checkboxes',
'#title' => 'check box title go here.',
'#required' => TRUE,
'#descrfiption' => 'some descriptions for checkboxes.',
'#options' => $opt,
);
$form['check']['submit'] = array(
'#type' => 'submit',
'#value' => 'Delete',
);
return $form;
}

You need to fill an array of the database options for the checkboxes, then pass this array to the #options property of the checkboxes.
Change your code to be:
$output =array(); // the $output should be an array to store the database values.
foreach($result as $item) {
$output[] = $item->names; // fill the $output array with the database values.
}
Then:
$form['check']['chk_box'] = array(
'#type' => 'checkboxes',
'#title' => 'check box title go here.',
'#required' => TRUE,
'#descrfiption' => 'some descriptions for checkboxes.',
'#options' => $output, // the changed line.
);

Related

Drupal: How to update database from Select Option

Hei guys, I'm really new to Drupal and am stuck right now by having selected all the data I need from my database and get to display it inside a drop down list.
Unfortunatly I have no clue on how I can update my database with this specific selected field, as I am not having any value....
$options = array();
foreach ($results as $result) {
$options["name"] = array(
$result->name,
);
}
$options2 = array();
foreach ($results_tour as $result2) {
$options2[$result2->sku] = array(
$result2->title,
);
}
$form['tour'] = array(
'#type' => 'select',
'#options' => $options2,
);
$form['tour_guide'] = array(
'#type' => 'select',
'#title' => t('Tour Guide'),
'#options' => $options,
'#description' => 'Please select a guide for this specific tour'
);
$form['save'] = array(
'#type' => 'submit',
'#value' => 'Speichern',
'#submit' => array('plantours_form_submit'),
);
return $form;
}
function plantours_form_submit($form, $form_state) {
db_update('commerce_line_item')
->fields(array(
'status' => $options["name"]
))
->execute();
}
Don't do it manually, by writing directly to database, but use Drupal commerce api (I guess you are using drupal commerce):
https://www.drupal.org/node/1288414

Cakephp Pagination in DropDown?

I'm looking for a way, to handle the Pagination-options in a dropdown menu.
I'd like my users to select the sorting order in the same form with my filtering options, so when they hit "Send", pagination-order is already set.orm
e.g. like:
$this->Form->input('paginationorder',array(
'label' => 'order',
'options' => array(
'sort:id/direction:desc' => 'New Items, desc',
'sort:id/direction:asc' => 'New Items,asc',
),
'div' => false
)
);
$(function() {
$('#sort-properties').change(function() { // replace the ID_OF_YOUR_SELECT_BOX with the id to your select box given by Cake
var price = $(this).val();
window.location = baseUrl + 'properties/property_view/'+price;
});
});
<?php
echo $this->Form->input('orderby', array(
'id' => 'sort-properties',
'options' => array(
'sort:sale_rent_price/direction:asc' => 'Sort by Price Low to High',
'sort:sale_rent_price/direction:desc' => 'Sort by Price High to Low',
'sort:created/direction:asc' => 'Sort by Date Old to New',
'sort:created/direction:desc' => 'Sort by Date New to Old'
),
'label' => false,
'empty' => 'Default Order'
));
?>
I would change the values of the options to e.g. fieldname.desc, like :
$this->Form->input('paginationorder',array(
'label' => 'order',
'options' => array(
'id.desc' => 'New Items, desc',
'id.asc' => 'New Items,asc',
),
'div' => false
)
);
Afterwards in the controller put the values to an array via the explode method:
$order = explode(".", $this->request->data['Model']['field']);
then you can use the values in your find condition, like:
$result = $this->Model->find('all', array(
'order' => array( $order[0] => $order[1] )
));
There is propably a more elegant way to make this, but this should work.

Drupal 7: File field causes error with Dependable Dropdowns

I'm building a Form in a module using the Form API. I've had a couple of dependent dropdowns that have been working just fine. The code is as follows:
$types = db_query('SELECT * FROM {touchpoints_metric_types}') -> fetchAllKeyed(0, 1);
$types = array('0' => '- Select -') + $types;
$selectedType = isset($form_state['values']['metrictype']) ? $form_state['values']['metrictype'] : 0;
$methods = _get_methods($selectedType);
$selectedMethod = isset($form_state['values']['measurementmethod']) ? $form_state['values']['measurementmethod'] : 0;
$form['metrictype'] = array(
'#type' => 'select',
'#title' => t('Metric Type'),
'#options' => $types,
'#default_value' => $selectedType,
'#ajax' => array(
'event' => 'change',
'wrapper' => 'method-wrapper',
'callback' => 'touchpoints_method_callback'
)
);
$form['measurementmethod'] = array(
'#type' => 'select',
'#title' => t('Measurement Method'),
'#prefix' => '<div id="method-wrapper">',
'#suffix' => '</div>',
'#options' => $methods,
'#default_value' => $selectedMethod,
);
Here are the _get_methods and touchpoints_method_callback functions:
function _get_methods($selected) {
if ($selected) {
$methods = db_query("SELECT * FROM {touchpoints_m_methods} WHERE mt_id=$selected") -> fetchAllKeyed(0, 2);
} else {
$methods = array();
}
$methods = array('0' => "- Select -") + $methods;
return $methods;
}
function touchpoints_method_callback($form, &$form_state) {
return $form['measurementmethod'];
}
This all worked fine until I added a file field to the form. Here is the code I used for that:
$form['metricfile'] = array(
'#type' => 'file',
'#title' => 'Attach a File',
);
Now that the file is added if I change the first dropdown it hangs with the 'Please wait' message next to it without ever loading the contents of the second dropdown. I also get the following error in my JavaScript console:
"Uncaught TypeError: Object function (a,b){return new p.fn.init(a,b,c)} has no method 'handleError'"
What am I doing wrong here?

How to add a new user in drupal 7 programmatically ?My custom module defines a form with custom fields

Hi being a newbie to drupal , kindly guide how to add a new user , i know user module with user_save can be used but how and where to implement it ?
Do i have to write this function in submit handler of my custom form below-
function registerme_newform($form, &$form_state)
{
$form = array();
$form['account details'] = array(
'#type' => 'fieldset',
'#title' => t('Account Details'),
'#description' => t('Enter Personal Credentials'),
);
$form['account details']['first name'] = array(
'#type' => 'textfield',
'#title' => t('First Name'),
'#default_value' => t('Be sure of your first name'),
'#attributes' => array(
'onblur' => "if (this.value == '') {this.value = 'Be sure of your first name'}",
'onfocus' => "if (this.value == 'Be sure of your first name') {this.value = ''}"
, ),
);
$form['account details']['last name'] = array(
'#type' => 'textfield',
'#title' => t('Last Name'),
'#default_value' => t('Be sure of your last name'),
'#attributes' => array(
'onblur' => "if (this.value == '') {this.value = 'Be sure of your last name'}",
'onfocus' => "if (this.value == 'Be sure of your last name') {this.value = ''}"
, ), );
$form['account details']['email'] = array(
'#type' => 'textfield',
'#title' => t('E-Mail'),
'#required' => TRUE,
'#default_value' => t('Email acts as username.Dont forget it!'),
'#attributes' => array(
'onblur' => "if (this.value == '') {this.value = 'Email acts as username.Dont forget
it!'}",
'onfocus' => "if (this.value == 'Email acts as username.Dont forget it!')
{this.value = ''}"
, ),
);
$form['account details']['password'] = array(
'#type' => 'password',
'#title' => t('Password'),
'#maxlength' => 60,
'#size' => 60,
'#required' => TRUE,
'#description' => t('Password should be atleast 6 characters long.'),
);
$form['home'] = array(
'#type' => 'fieldset',
'#title' => 'Home Address',
'#description' => t('Enter Personal Residential Credentials')
);
$form['home']['street'] = array(
'#type' => 'textfield',
'#title' => 'Street Address',
);
$form['home']['city'] = array(
'#type' => 'textfield',
'#title' => 'City',
);
$form['work'] = array(
'#type' => 'fieldset',
'#title' => 'Work Address',
'#description' => t('Enter Official Address')
);
$form['work']['street'] = array(
'#type' => 'textfield',
'#title' => 'Street Address',
);
$form['work']['city'] = array(
'#type' => 'textfield',
'#title' => 'City',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Register Me'),
);
return $form;
}
function registerme_newform_validate(&$form, &$form_state)
{
if($form_state['values']['account details']['first name']=='Be sure of your first
name')
{
form_set_error('first name',t('Please enter your first name'));
}
}
function registerme_newform_submit(&$form, &$form_state)
{
dsm($form_state);
}
Also would like to know how will values be entered in database , i mean how will these custom fields be added to database? Kindly guide thanks.
First of all please check if the first name is allowed user name. I recommend you providing another field to enter username as its not uncommon that username is already used by somebody else. Then also check that there are no users registered with the given email address.
function registerme_newform_validate(&$form, &$form_state) {
if($form_state['values']['account details']['first name']=='Be sure of your first
name') {
form_set_error('first name',t('Please enter your first name'));
}
// TODO: Provide user with a chance to enter a name ( drupal user name )
// Also do the following two checks and report an error.
// check using user_load_by_name($form_state['values']['account details']['first anme'])
// check using user_load_by_mail($form_state['values']['account details']['email'])
}
Next in your submit function map the form values to an array that could be passed to user_save as shown bellow. If you want to know exactly how other fields map, use the devel module to inspect the structure by vising an already existing user profile.
function registerme_newform_submit(&$form, &$form_state){
$new_user = array(
// The below name field must be unique.
'name' => $form_state['values']['account details']['name'],
'pass' => $form_state['values']['account details']['password'],
'mail' => $form_state['values']['account details']['email'],
'init' => $form_state['values']['account details']['email'],
'field_first_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['account details']['first name']))),
'field_last_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['account details']['last name']))),
// Map all the extra fields to user objects as shown above.
...
'status' => 1,
'access' => REQUEST_TIME,
'roles' => $roles,
);
// $account returns user object
$account = user_save(null, $new_user);
//after user_save you can use the following code to send notification email.
drupal_mail('user', 'register_no_approval_required', $account->mail, NULL, array('account' => $account), variable_get('site_mail', 'noreply#mysite.com'));
}
I have implemented a different approach to this problem. I created an entity form (https://drupal.org/project/entityform)
where I prompt for key user information. I have also installed the profile2 module allowing me to create alternate profiles. When the form is submitted it triggers a rule. That rule allows me to create the user, create a linked profile and then send an email to the administrator with a link to the new user entry allowing them to review and activate.
A nice alternative if you dont want to solve via PHP or want to create additional content on creation.

How to set selection in mulitiselect list box in cakephp

I want to set the multi selection to my multi list box.
I have two results in my view page.
$inr1 = 0;
$arr1 = array();
$str_arr = '';
foreach ($result as $rows){
$inr1 = $rows['Employees']['employee_id'];
$arr1[$inr1] = $rows['Employees']['first_name'].' '.$rows['Employees']['last_name'];
$str_arr = $str_arr.$inr1.',';
}
$str_arr = substr($str_arr,0,-1);
//print_r($arr1);
$inr = 0;
$arr = array();
foreach ($options as $option){
$inr = $option['Employee']['employee_id'];
$arr[$inr] = $option['Employee']['first_name'].' '.$option['Employee']['last_name'];
}
//print_r($arr);
echo $this->Form->input('emp_id_one', array( 'options' => array( $arr),
'empty' => '(choose one)',
'div'=>'formfield',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Team Members',
'type' => 'select', 'multiple' => true,
'selected' => $arr1,
'style' => 'width:210px; height:125px;',
));
But the values in $arr1 not selected in the list box.
The $arr1 have the selected values.
The $arr have the options to the list.
The problem is that the selction is not working..There have no selection...
How can i do this?
If there is any problem in my code..?
Finally i solved my problem by chaing some code:
Add the one line of code after this $str_arr = substr($str_arr,0,-1);'.
That is....
$str_arr = substr($str_arr,0,-1);
$sel = explode(',',$str_arr);
Then change the name of variable as like this :
echo $this->Form->input('emp_id_one', array( 'options' => array( $arr),
'empty' => '(choose one)',
'div'=>'formfield',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Team Members',
'type' => 'select', 'multiple' => true,
'selected' => $sel,
'style' => 'width:210px; height:125px;',
));
Now the values in $sel is selected in the multi list

Resources