Drupal Select option in form - php

I am trying to create a select list in drupal that is populated from a custom table in my db.
The table consists of a name and an id number. They are both unique.
I used this to collect the data from the db and to populate two arrays.
$query = "SELECT `id`, title` from {svm_mail_esp}";
$result = db_query($query);
$i=0;
while($row = db_fetch_array($result)) {
$listName[$i] = $row['title'];
$listID[$i] = $row['id'];
$i++;
}
Here is the $form array I used:
$form['esp_refferer'] = array(
'#type' => 'select',
'#title' => 'Service Provider',
'#required' => TRUE,
'#options' => $list,
'#cols' => 10,
'#default_value' => '- Choose -', //TODO: This needs to be fixed and the form cannot be processed while this is selected
'#multiple' => FALSE,
);
This is where my problem is coming in, I want to display the name, but when the form is submitted I need the $node->esp_refferer to be the id number and not the name.
How do I do this?

while($row = db_fetch_array($result)) {
$list[$row['id']] = $row['title'];
}
You need to create an array $list, Keys of that array will be ids and value of each will be respective title.

Related

Insert jQuery repeater row in PHP database

I have 1 row having 5 form fields. User can add/remove rows. Its repeatable row.
Now i want to store these fields into database with PDO php.
For normal values i am using this code but i am confused for repeater field.
$data = array(
'bill_no' => trim($_REQUEST['bill_no']),
'from_name' => trim($_REQUEST['from_name']),
'to_name' => trim($_REQUEST['to_name']),
'date' => trim($_REQUEST['date_bill']),
'mr_or_ms' => trim($_REQUEST['mr_or_ms']),
);
if($crud->InsertData("bill",$data)) {
header("Location: add-bill.php");
}
Insert Function:
public function InsertData($table,$fields) {
$field = array_keys($fields);
$single_field = implode(",", $field);
$val = implode("','", $fields);
try {
$query = $this->db->prepare("INSERT INTO ".$table."(".$single_field.") VALUES('".$val."')");
$query->execute();
return true;
} catch(PDOException $e) {
echo "unable to insert data";
}
}
Please help me to insert fields. Thanks
Change the names of your form fields, add [] to the end to get PHP arrays. For example change bill_no to bill_no[]. Something like this:
foreach($_REQUEST['bill_no'] as $row_number => $row_content){
$data = array(
'bill_no' => trim($_REQUEST['bill_no'][$row_number]),
'from_name' => trim($_REQUEST['from_name'][$row_number]),
'to_name' => trim($_REQUEST['to_name'][$row_number]),
'date' => trim($_REQUEST['date_bill'][$row_number]),
'mr_or_ms' => trim($_REQUEST['mr_or_ms'][$row_number]),
);
$crud->InsertData("bill",$data);
}
This assumes the browser is not mixing up the order of the fields, so maybe it's better to add unique names to the form fields when adding rows.
Also, there's no input data validation at all, please ensure you are escaping all data properly.
I did it with this method.
$total=count($_POST['description']);
for($i=0; $i<$total; $i++){
$data1 = array(
'bill_no' => trim($_POST['bill_no']),
'description' => trim($_POST['description'][$i]),
'nos' => trim($_POST['nos'][$i]),
'nos_day' => trim($_POST['nos_day'][$i]),
'pay' => trim($_POST['pay'][$i]),
'weekly_off' => trim($_POST['weekly'][$i]),
'hra' => trim($_POST['hra'][$i]),
'rs' => trim($_POST['rs'][$i]),
'ps' => trim($_POST['ps'][$i]),
);
$crud->InsertData("bill_details",$data1);
}

PHP & sqlsrv - create array from results, without knowing column names?

Using the below, I echo a JSON array of the results. But this requires that I identify the column names which I'd like to return from the SQL query:
$new_sql = "SELECT TOP 200 * FROM STracker ORDER BY [ID] DESC";
$check_statement = sqlsrv_query($conn, $new_sql);
$data = array();
while($row = sqlsrv_fetch_array($check_statement, SQLSRV_FETCH_ASSOC)) {
$data['data'][] = array(
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
);
}
Is there any way to create that array information, but return all of the columns returned by the query dynamically? So by using SELECT * FROM, all of the column data is returned in the array but without me needing to write out all of these individually? (the below)
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
Ok I forgot to add that I'd tried this:
$data['data'][] = array($row);
Which is clearly wrong, and after using the following, it works perfectly!
$data['data'][] = $row;

how to edit checkbox values in drupal 7

Initially i am inserting multiple ids through multiple checkboxes. Now i want to open that page again for edit but i want some of the checkbox checked based on id i have inserted priviously.
$courses contains all the nodes which i need to desplay and $checkedarray are the nodes which comes from database[id which got inserted after submission].
here is the code to uderstand the work..
$vocabulary = taxonomy_vocabulary_machine_name_load('xxx list');
$terms = taxonomy_get_tree($vocabulary->vid);
$courses = array();
foreach($terms as $term) {
if($term->parents[0]==0){
$courses[$term->tid] = $term->name."<br />";
}
else{
$parents = taxonomy_get_parents($term->tid);
$parentsName = $parents[$term->parents[0]]->name.' / ';
$courses[$term->tid] = $parentsName.$term->name."<br />";
}
}
$form['addlicense']['categories'] = array(
'#type' => 'checkboxes',
'#title' => t('Series'),
'#options' => $courses,
'#attributes' => array('class' => array('series-list')),
'#required' => TRUE,
);
$checkedarray = array(5,6,7,8,9,10);
Now i have list of node which need to be appered as checked checkboxes which is in $checkedarray array... any help whould be appreciated
Did you tried using the #default_value attribute and setting it to $checkdarray ?

Auto populate dropDownListRow form field in yii from database

I have a form having some multi select dropdowns in yii. I have to auto populate the selected values in that multi select box when comes to edit the data. I am fetching the data and passing it inot view file, but am not sure how can i populate the values in the dropdown. please help me
Here is the code for the multi select drop down
echo $form->dropDownListRow($modelDomain, 'domain_id', $domain, array('title' => Yii::t('main', 'SELECT_DOAMIN'),'multiple'=>true ,'style' => 'width:250px;height:150px;'));
For multiple select you need to use 'options' parameter:
echo $form->dropDownListRow($modelDomain, 'domain_id', $domain, array('title' => Yii::t('main', 'SELECT_DOAMIN'),'multiple'=>true ,'style' => 'width:250px;height:150px;', 'options' => array(
1 => array('selected' => 'selected'),
2 => array('selected' => 'selected'),
)));
Where 1 and 2 are domain ids taken from the $_POST;
You can do this in the action:
$post = $this->getRequest()->getPost('ModelName');
$selectedDomains = $post['domain_id']; // this should be an array or selected values
$selected = array_fill(0, count($selectedDomains), array('selected' => 'selected')); // this constructs the 'options' value from view
$selectedOptions = array_combine($selectedDomains, $selected) // this is the 'options' array with selected values as keys and htmlOptions as values
Also, the code is untested and you need to do your validations and other logic stuff yourself.

How do I use a lookup table?

I use the code below to get all the categories from the am_category table into a dropdownbox in a form. It works. But when submitting the form I need the category.ID and not the name. How does one usually work with lookup tables like this one?
$category_result = db_query("SELECT id, name FROM {am_category}");
$categories = array();
foreach($category_result as $row)
{
$categories[$row->id] = t($row->name);
}
$form['category_options'] = array(
'#type' => 'value',
'#value' => $categories
);
$form['category']['category'] = array(
'#title' => t('Category'),
'#type' => 'select',
'#description' => t('Please select the category of this achievement.'),
'#options' => $form['category_options']['#value']
);
The value passed through to the $form_state array in your submit function will be the ID and not the name, it will be the key of the options in the drop down, not the value.
If you want to shorten your code slightly you could use the fetchAllKeyed() method of the database query to build that array of categories automatically. You don't need the category_options element as you'll already have access to that array in the $form variable in your submission function.
Also I'd be careful giving the outer and and inner elements the same name (category), that might cause some problems.
This code should help:
function mymodule_myform($form, &$form_state) {
$categories = db_query("SELECT id, name FROM {am_category}")->fetchAllKeyed();
$form['category_wrapper']['category'] = array(
'#type' => 'select',
'#title' => t('Category'),
'#description' => t('Please select the category of this achievement.'),
'#options' => $categories
);
return $form;
}
function mymodule_myform_submit(&$form, &$form_state) {
$selected_category_id = $form_state['values']['category'];
// Just in case you wanted to know, this would get the corresponding name for the selected category:
$selected_category_name = $form['category_wrapper']['category']['#options'][$selected_category_id];
}

Categories