Codeigniter, using set_checkbox in a controller - codeigniter

I've got a loop that generates checkboxes, I have it working within the view, but I would like to move it into the controller and then pass the resulting string to the view. The problem is set_checkbox() doesn't seem to remember the values when it's placed in a controller. It does however seem to set the default value.
Edit: This is only an issue when validation fails and I want checkboxes to retain the users selections. Otherwise code is working as expected. I also have a validation rule set.
$languages_by_name = $this->event_model->get_spoken_languages_by_name();
// Generate array from model data for form_dropdown()
$i = 1;
$list_languages = '';
foreach ($languages_by_name as $row) {
$i == 1 ? $first = TRUE : $first = FALSE; // Check if this is the first radio and precheck it.
$list_languages .= '<label>' . form_checkbox('spokenLanguages[]', $row->event_spoken_id, set_checkbox('spokenLanguages', $row->event_spoken_id, $first)) . ' ' . $row->name . '</label> ';
$i++;
}
// Pass $list_languages to view
$this->data['list_languages'] = $list_languages;

Here's working code for the controller. There might be a more elegant way to do this.
// Generate array from model data for form_dropdown()
$i = 1;
$list_languages = '';
foreach ($languages_by_name as $row) {
// Check if there is post data
if(!$this->input->post('spokenLanguages')) {
// Set first element to checked
$i == 1 ? $selection = TRUE : $selection = FALSE; // Check if this is the first radio and precheck it.
} else {
// Check if this input is checked
if(in_array($row->event_spoken_id, $this->input->post('spokenLanguages'))) {
$selection = TRUE;
} else {
$selection = FALSE;
}
}
$list_languages .= '<label>' . form_checkbox('spokenLanguages[]', $row->event_spoken_id, set_checkbox('spokenLanguages', $row->event_spoken_id, $selection)) . ' ' . $row->name . '</label> ';
$i++;
}
// Pass $list_languages to view
$this->data['list_languages'] = $list_languages;

Related

Code contain error as unexpected 'if' (T_IF)

I am creating dependent dropdown in which i want stay dropdown value after page reloading. & i found above error in controller file
public function get_reason_details(Request $req)
{
$reason_detail_id=Session::get('reason_detail_id');
$html = '';
$get_product_details =
DB::table("reason_details")->select("reason_details.*")->where('reason_id',$req->reason_id)->get();
foreach ($get_product_details as $product) {
$html .= '<option value="'.$product->reason_detail_id.'"'if($reason_detail_id==$product->reason_detail_id){selected="selected"} '>'.$product->reason_detail.'</option>';
}
return response()->json(['html' => $html]);
}
You are writing your if condition inside a php variable that is why you are getting this error.
To solve this you can write your if condition outside K variable and use a variable to select the dropdown. For e.g
foreach ($get_product_details as $product) {
$selected = "false";
if($reason_detail_id==$product->reason_detail_id) {
$selected="true";
}
$html .= '<option value="'.$product->reason_detail_id.'" selected="'.$selected.'" >'.$product->reason_detail.'</option>';
}

ebay-api "findItemsByKeywords" pagination in codigniter 3

Can anyone help me with this issue?
I'm making an API call with 50 entries per page.
I get results, but how can i display the next page ?
How to use pagination ? i don't have a clue where to start.
I really need some help here.
Thanks
This is the controller
if (!empty($_POST['submit'])) {
$aaa = $_POST['kikozasearch'];
}else {
$aaa = $_POST['kikozasearch'];
}
// API request variables
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1'; // URL to call
$version = '1.0.0'; // API version supported by your application
$appid = ''; // Replace with your own AppID
$globalid = 'EBAY-US'; // Global ID of the eBay site you want to search (e.g., EBAY-DE)
$query = $aaa; // You may want to supply your own query
$safequery = urlencode($query); // Make the query URL-friendly
$i = '0'; // Initialize the item filter index to 0
$apicall = "$endpoint?";
$apicall .= "OPERATION-NAME=findItemsByKeywords";
$apicall .= "&SERVICE-VERSION=$version";
$apicall .= "&SECURITY-APPNAME=$appid";
$apicall .= "&GLOBAL-ID=$globalid";
$apicall .= "&keywords=$safequery";
$apicall .= "&paginationInput.pageNumber=$currentpage";
$apicall .= "&paginationInput.entriesPerPage=50";
//$apicall .= "&paginationOutput.totalPages";
$apicall .= "$urlfilter";
// Load the call and capture the document returned by eBay API
$resp = simplexml_load_file($apicall);
// Check to see if the request was successful, else print an error
if ($resp->ack == "Success") {
$results = '';
// If the response was loaded, parse it and build links
foreach($resp->searchResult->item as $item) {
$pic = $item->galleryURL;
$link = $item->viewItemURL;
$title = $item->title;
// For each SearchResultItem node, build a link and append it to $results
$results .= "<div><img src=\"$pic\"></td><td>$title$pag</div>";
}
}
// If the response does not indicate 'Success,' print an error
else {
$results = "<div class='alert alert-danger'><h4>Oops! The request was not successful. Make sure you are using a valid ";
$results .= "AppID for the Production environment.</h4></div>";
}
echo "We found: ".$resp->paginationOutput->totalEntries . " resaults!";
echo "<div class='alert alert-info'>".$results."</div>";
// echo $resp->paginationOutput->entriesPerPage;
// echo "<br>";
// echo $resp->paginationOutput->totalEntries;
// echo "<br>";
// echo $resp->paginationOutput->totalPages;
echo $currentpage;
echo "/".$resp->paginationOutput->totalPages;
echo "<br />";
$totalpages = $resp->paginationOutput->totalPages;
Here is the post request
<script>
$(document).ready(function(){
$('#form').on('submit', function(info){
info.preventDefault();
$.post('<?php echo base_url();?>index.php/ebayapps/searchitem',
$('#form').serialize(),
function(data){
$('#resaults').html(data);
}
);
}); // keyup
});
</script>
If I understand correctly, you want to load more than one page of results. In this case, you will need to make numerous API requests, depending on the total number of pages you wanted to retrieve in the first place.
So say you want four pages - you need to run your function four times and increment paginationInput.pageNumber in each loop.
I hope this helps.

Passing Two Arrays to View

OK, below is a get_members function in my controller that I pulled and manipulated from the interwebs... i can print out the information from $output in the controller, but I don't want to do that... I cannot figure out how to get it to be part of my view so I can list info from it freely...
I know it has something to do with the $data array in the index function... can anyone assist?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Phonedirectory extends CI_Controller {
function get_members($group=FALSE,$inclusive=FALSE) {
// Active Directory server
$ldap_host = "fps";
// Active Directory DN
$ldap_dn = "OU=Users,DC=xxx,DC=org";
// User attributes we want to keep
$keep = array(
"samaccountname",
"displayName",
"telephonenumber"
);
// Connect to AD
$ldap = ldap_connect($ldap_host) or die("Could not connect to LDAP");
ldap_set_option ($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($ldap, "CN=LDAP Reader,OU=Users - Special,DC=xxx,DC=org", "xxx") or die("Could not bind to LDAP");
// Begin building query
if($group) $query = "(&"; else $query = "";
$query .= "(&(objectClass=user)(objectCategory=person))";
// Filter by memberOf, if group is set
if(is_array($group)) {
// Looking for a members amongst multiple groups
if($inclusive) {
// Inclusive - get users that are in any of the groups
// Add OR operator
$query .= "(|";
} else {
// Exclusive - only get users that are in all of the groups
// Add AND operator
$query .= "(&";
}
// Append each group
foreach($group as $g) $query .= "(memberOf=OU=$g,$ldap_dn)";
$query .= ")";
} elseif($group) {
// Just looking for membership of one group
$query .= "(memberOf=OU=$group,$ldap_dn)";
}
// Close query
if($group) $query .= ")"; else $query .= "";
// Uncomment to output queries onto page for debugging
// print_r($query);
// Search AD
$results = ldap_search($ldap,$ldap_dn,$query);
$entries = ldap_get_entries($ldap, $results);
// Remove first entry (it's always blank)
array_shift($entries);
$output = array(); // Declare the output array
$i = 0; // Counter
// Build output array
foreach($entries as $u) {
foreach($keep as $x) {
// Check for attribute
if(isset($u[$x][0])) $attrval = $u[$x][0]; else $attrval = NULL;
// Append attribute to output array
$output[$i][$x] = $attrval;
}
$i++;
}
return $output;
}
public function index() {
$data = array('title' => 'Phone Directory', 'main_content' => 'pages/phoneDirectory');
$this->load->view('template/main', $data);
}
}
Correct me if I'm wrong, but it sounds like you just want the output sent to the view?
If that's the case, then add this to the index function
public function index() {
$data = array('title' => 'Phone Directory', 'main_content' => 'pages/phoneDirectory');
$data['members'] = $this->get_members();
$this->load->view('template/main', $data);
}
or however you want to append that to your data array.
Then in the view you can do:
<?php echo print_r($members, TRUE); ?>

repopulating the select list generated from database in codeigniter

Hi. I have the form in which I use form_validation If the user make any mistake (leave some required fields empty), user is redirected back to the form, and the form has been re-populated. All works, except my select , which is generated from the database.
Here is my code from the view:
echo "<select name='parentid'" . set_value("parentid"). ">";
echo '<option value = "0">None</option>';
foreach ($faq_categories as $row => $option) {
echo "<option value=" . $option['catid'] . ">" . $option['categoryname']. "</option>";
}
echo '</select>';
Here is my controller code:
public function displayAddFaqCategoryForm($error = null)
{
$data['title'] = "Add new FAQ Category";
$data['main_content'] = 'addFaqCategory';
$selectWhat = array('tname' => 'faq_categories',
'sortby'=> 'catid',
'how' => 'asc'
);
$this->load->model('selectRecords');
$data['faq_categories'] = $this->selectRecords->selectAllRecords($selectWhat);
$this->load->vars($data);
$this->load->view('backOffice/template');
} // end of function displayAddFaqCategoryForm
And here is the model code:
public function selectAllRecords($selectWhat = array())
{
$data = array();
$tname = $selectWhat['tname'];
$sortby = $selectWhat['sortby'];
$how = $selectWhat['how'];
$this->db->order_by($sortby,$how);
$query = $this->db->get($tname);
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
} // end of function selectAllRecords
I am not getting any error messages, just the select is not repopulated with last used. Any help will be deeply appreciated.
You're using set_value() incorrectly
echo "<select name='parentid'" . set_value("parentid"). ">";
It's meant to output the actual value (for text inputs). This would produce something like:
<select name='parentid'ActualValue>
Which is not how a <select> element is populated, and is invalid HTML. See the correct usage in the Form Helper docs.
You can use set_select(), and it goes on your <option>:
foreach ($faq_categories as $row => $option) {
echo "<option value=".form_prep($option['catid']).'"';
echo set_select('parentid', $option['catid']); // outputs selected="selected"
echo ">".html_escape($option['categoryname'])."</option>";
}
I've taken a few other liberties with your code here as you can see, to be on the safe side (always).
If this is too much of a mess, you might be interested in the form_dropdown() function.

Can't get getChildCategories to work when looping through parents

Trying to print out a two tier navigation menu of my categories. For each parent category I would like to print out a list of it's child categories. All the demos I see use Mage::getModel, but trying to get it to work with getChildCategories. Check out the code below, the areas commented out are what is breaking it. Any help would be great.
$nl = chr(10);
$obj = new Mage_Catalog_Block_Navigation();
$main_cats = $obj->getStoreCategories();
echo '<ul>';
foreach ($main_cats as $main) {
// $sub_cats = $this->getChildCategories($main);
$main_class = ($this->isCategoryActive($main)) ? 'current' : '';
echo '<li class="'.$main_class.'">'.$main->getName().''.$nl;
/*
if ($sub_cats->count())) {
echo '<ul>';
foreach ($sub_cats as $sub) {
$sub_class = ($this->isCategoryActive($sub)) ? 'current' : '';
echo '<li class="'.$sub_class.'">'.$sub->getName().'</li>'.$nl;
}
echo '</ul>'.$nl;
}
*/
echo '</li>';
}
echo '</ul>';
What do you think about this?
getting_and_using_categories_and_subcategories

Resources