I currently have index, view, add and edit from my tickets/views and am planning to add another view called current. I want to display only the "Resolved" tickets on that view but have no idea how to do it. I've been trying to figure this out for the past couple of days with no luck. Where should I put the "find" code and what should I include on my tickets/current view code? Here's what I have tried so far:
/controllers/tickets_controller
function current() {
$current = $this->set('tickets', $this->Ticket->find('all', array(
'conditions' => array('Ticket.status' => 'Resolved'),
'order' => array('Ticket.created' => 'desc')
)));
$this->set('tickets', $this->paginate());
}
/views/tickets/current.ctp
<?php
$i = 0;
foreach ($tickets as $ticket):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
This code displays the same as /views/tickets/index.ctp (with all the records from the table).
Thanks,
Lyman
You were almost there. $this->set('foo') in Cake is one way you can pass variables to the view.
What the code below does is set a variable called current the return value of the find method which has a custom condition, which can be accessed from the view. (It's an array in this case; but you can set anything)
You don't need the paginate() here unless you plan to use pagination in this view.
So something like this should do the trick ($curr is a bad variable name but I wasn't feeling inventive. (resolved_tickets would make more sense (why current?))
//controllers/tickets_controller
function current() {
$this->set('current', $this->Ticket->find('all',
array('conditions' => array('Ticket.status' => 'Resolved'),
'order' => array('Ticket.created' => 'desc')
)));
}
/views/tickets/current.ctp
<?php
$i = 0;
// adjust the variable in the foreach
foreach ($current as $curr):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
echo $curr['Ticket']['id']; // example
?>
Related
I am a newbie in Drupal. Please accept my ignorance. I have a page with a custom hook to override the view and display list of posts with default sorting or no sorting. I want to sort the array based on the node create date. But not sure where to plug the sorting argument. Can anyone please help? I have this code block in my_view.module file.
function _sites_by_park_page_get_node_references($fieldName, $property, $park_id) {
$results = array();
$parks = _sites_by_park_page_get_sites($park_id);
foreach ($parks['features'] as $feature) {
foreach($feature['properties'][$property] as $key => $value) {
if (!array_key_exists($key, $results)) {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->fieldCondition($fieldName, 'value', $value);
$result = $query->execute();
$node = node_load(array_shift(array_keys($result['node'])));
$results[$key] = $node->title;
}
}
}
return $results;
}
/**
* Return GeoJSON formatted park data
*/
function _sites_by_park_page_get_sites($park_id) {
// Uses a lot of memory thanks to views and GD image resizing, could use some garbage collection opimisation
ini_set('memory_limit', '512M');
$data_view = views_get_view('sites_by_park_data');
$data_view->set_arguments(array($park_id));
$data_view->execute('page');
// Build our own, more lightweight geojson structure for faster page loads (Leaflet module generated 2MB of data vs this custom module's 40kb-ish for 140 parks)
$results = array(
'type' => 'FeatureCollection',
'features' => array(),
);
foreach($data_view->result as $result) {
// Initialise some arrays that may be merged between result sets (for instance when multiple activities contribute to a site's overall data)
if (!isset($results['features'][$result->nid])) {
$results['features'][$result->nid] = array(
'type' => 'Feature',
'properties' => array()
);
}
}
$results['features'] = array_values($results['features']);
return $results;
}
As per MilanG's suggestion I have done this through admin section. Change the sorting order and it works fine now.
I'm fairly new to Drupal, and I need your help on this issue:
I have built a module on Drupal 7 which makes a database query to extract the name and the email of all users. The code is this:
<?php
/**
*
*/
function myexample_block_info() {
$blocks['myblock'] = array(
'info' => t('My Custom Modue'),
);
return $blocks;
}
function myexample_block_view($delta = '') {
$block = array();
$results = db_select('users','a')
->fields('a', array('name', 'mail'))
->execute();
$header = array(t('NAME'), t('MAIL'));
$rows = array();
foreach ($results as $node) {
$rows[] = array(
$node->name,
$node->mail,
);
}
$block['content'] = theme('table', array('header' => $header, 'rows' => $rows));
return $block;
}
I put the block into "Side-bar first"-Bartik theme. The code works and it retrieves what I want. But the problem with the display. I'm getting the results repeated 3 times:
Results
Why am I getting the results repeated three times. I cant seem to find anything wrong with the code. Could anyone help me please? Thanks in advance.
What are you trying to achieve ? If you are just trying to extract data from the DB this is not the way to go. You should extract data via mysql client directly.
I am looking to except single element from array. My array is:
Array
(
[0] => Array
(
[0] => Array
(
[COUNT(ID)] => 0
)
)
)
I have already use PHP functions basename and array_shift, but they didn't give me proper value. I want only single string COUNT(ID) value.
Here is my function using in cakephp model:
$res = $this->query("select COUNT(ID) from users where Username = '".$Username['Username']."'");
if ($res[0][0]['COUNT(ID)'] >= 1)
{
return false;
}
else
{
return true;
}
I don't need $res[0][0], I need only COUNT[ID]. Is there any easy way to find only COUNT[ID].
If you are using CakePHP, it's good to use model and inbuilt functions to get answer what you want...
$this->loadModel('User'); //If you are in controller
$total = $this->User->find('count', array(
'conditions' => array('Username' => $Username['Username'])
));
You'll get answer in single variable..!!
Your output is produced by code like this
$data = array(
array(
array(
'COUNT(ID)' => 0
)
)
);
You can access its value by calling directly
$data[0][0]['COUNT(ID)']
This could be wrong problem you are solving, as it seems like database query result that should not look like that and could be done with more ease. You should show your original function/problem, that this script is part of.
Let's say you array's name is $myArray, than you can assign the value of $myArray[0][0]['COUNT(ID)'] to $value in the way you usually assign a value: $value = $myArray[0][0]['COUNT(ID)'];.
If you want to delete an index from an array, use unset() like this: unset($myArray[0][0]['COUNT(ID)']). I hope this answers your question.
If you know the exact count of nesting in array you can just access it with indexes
$array[0][0]['COUNT(ID)']
If no, you might want to use the function which will recursively find you the first nested element that is not an array
function getStringFromArray($array) {
if (is_array($array)) {
foreach ($array as $key => $value) {
if (is_array($value)) {
return getStringFromArray($value);
} else {
return $value;
}
}
} else {
throw new Exception("Not an array given");
}
}
If you are sure that array structure will remain same then this could be useful :-
function array_values_recursive($ary)
{
$lst = array();
foreach( array_keys($ary) as $k ){
$v = $ary[$k];
if (is_scalar($v)) {
$lst[] = $v;
} elseif (is_array($v)) {
$lst = array_merge( $lst,
array_values_recursive($v)
);
}
}
return $lst;
}
$arr=array(array(array('COUNT(ID)'=>5)));
$res=array_values_recursive($arr);
echo '<pre>';print_r($res);
output :-
Array
(
[0] => 5
)
You can probably fetch it by associative array to reduce dimension but you can remove index. May be you can use foreach to automatically use indexs.
Try this code:
public $uses = array('User');
$count = $this->User->find('count', array(
'conditions' => array('Username' => $Username['Username'])
));
if ($count >= 1) {
return false;
} else {
return true;
}
You can use following technique for your solution. i did not get you what you want to do with your array but you can try below solution
$arr = Set::extract("/0/COUNT(ID)",$data);
where $data is your input array.
you will get following output
Array
(
[0] => 5
)
you can refer below link
Remove array key from array in cakephp
I have a table with data from the database, I would like it to have a Pager, I have all the code from an example (of buildamodule.com) among other sites, and my table get's rendered, but it doesn't generate a pager, although I have more rows then the limit:
the function:
function get_loyaltycodes(){
$headers = array(
array(
'data' => t('Code')
),
array(
'data' => t('Info')
),
array(
'data' => t('Points')
),
array(
'data' => t('Consumed by')
),
);
$limit = variable_get('codes_per_page',5);
$query = db_select('loyalty_codes','lc');
$query -> fields('lc',array('code','info','points','uid'))
-> orderBy('lc.info','ASC')
-> extend('PagerDefault')
-> limit($limit);
//to see all codes for a certain amount of points, just append the number of points to the URL
$arg = arg(2);
if($arg != '' && is_numeric($arg))
{
$query->condition('points', $arg);
}
// Fetch the result set.
$result = $query->execute();
$rows = array();
// Loop through each item and add to the $rows array.
foreach ($result as $row) {
$rows[] = array(
$row->code,
$row->info,
$row->points,
$row->uid,
);
}
// Format output.
$output = theme('table', array('header' => $headers, 'rows' => $rows)) . theme('pager');
return $output;
the $limit variable is set to 5 in the settings form, and it is 5 in the database too.
Anybody who has any idea in why the pager is not showing? perhaps something in the formatting off the output?
Help is very much appreciated!
apparently I can't log in right know because I'm behind a firewall, anyway I seem to have fixed it, stupid mistake though:
the ‘->extend(‘PagerDefault’) extension in the query had to be the first function in the daisy chain. If not there is no error but the function seems to not be called.
$query = db_select('loyalty_codes','lc')
->extend('PagerDefault')
-> fields('lc',array('code','info','points','uid'))
-> orderBy('lc.info','ASC')
-> limit(5);//$limit);
I have the following situation where I want to only display the search results when user search for something. Currrently, as I access my search page, all the search results is being displayed and if user search for a particular thing, it displays that accordingly. The following is the code in my search controller. I added a pagination for it to paginate.
function simple_search() {
$this->User->recursive = 1;
$this->Passion->recursive = 1;
$this->User->unBindModel(array('hasMany' => array('Topic','Post')),false);
$conditions = array();
$options;
$or_conditions = array();
$final_conditions = array();
$search_fields = array('User.firstName', 'User.lastName', 'User.email', 'User.displayName'); //fields to search 'Video.tags','Video.desc'
$this->layout = "mainLayout";
$value='';
if(!empty($this->params["url"]["value"])){
$value = $this->params["url"]["value"];
}
$searches = explode(" ", $value);
foreach ($search_fields as $f) {
array_push($conditions, array("$f Like" => "$value%"));
for ($i = 0; $i < count($searches); $i++) {
if ($searches[$i] != "") {
array_push($conditions, array("$f Like" => "$searches[$i]%"));
}
}
array_push($or_conditions, array('OR' => $conditions));
$conditions = array();
}
$final_conditions = array('OR' => $or_conditions);
$users = $this->User->find('all', $final_conditions);
$this->paginate = array(
'conditions' => $final_conditions,
'limit' => 10
);
$users = $this->paginate('User');
$this->set('search_fields', $users);
}
Why are you doing the find('all')? A few lines later paginate() overrides the result.
empty($this->params['url']['value'] check this and set your results to the view only in the case its not empty.
Follow the coding standard for CakePHP and use camelCased variable names instead of underscores. http://book.cakephp.org/2.0/en/contributing/cakephp-coding-conventions.html
Also you might want to take a look at this.
https://github.com/CakeDC/search
And at this (showing a custum find using search plugin)
https://github.com/CakeDC/users/blob/master/controllers/users_controller.php#L316
https://github.com/CakeDC/users/blob/master/models/user.php#L557