Yii nested set to dropdown menu - php

I'm using Yii nested set behavior, which helps me to keep my categories nested as seen here (nevermind title rows, they are in russian):
And all I want to do is to have Bootstrap nested menu, which should be like this:
$criteria = new CDbCriteria;
$criteria->order = 'root, lft';
$categories = Category::model()->findAll($criteria);
foreach($categories as $i => $category) {
$items[$i]['label'] = $category->title;
$items[$i]['url'] = $category->url;
$items[$i]['active'] = false;
$items[$i]['items'] = array(
array('label'=>'123', 'url'=>'#'),
array('label'=>'123', 'url'=>'#'),
array('label'=>'123', 'url'=>'#', 'items'=>array(
array('label'=>'1234', 'url'=>'#'),
array('label'=>'1234', 'url'=>'#'),
array('label'=>'1234', 'url'=>'#', 'items'=>array(
array('label'=>'1234', 'url'=>'#'),
array('label'=>'1234', 'url'=>'#'),
array('label'=>'1234', 'url'=>'#'),
)),
)),
);
}
$this->widget('bootstrap.widgets.TbMenu', array(
'type'=>'pills',
'stacked'=>false, // whether this is a stacked menu
'items'=>$items
));
I don't understand how to get this done, btw I read this topic and just don't know how actually apply this function to my problem. Appreciate any help.

This is the function that I use to format as json object, you can modify it to generate a php array.
protected function formatJstree(){
$categories = $this->descendants()->findAll();
$level=0;
$parent = 0;
$data = array();
foreach( $categories as $n => $category )
{
$node = array(
'data'=> "{$category->title}",
'attr'=>array('id'=>"category_id_{$category->category_id}")
);
if($category->level == $level){
$data[$parent]["children"][] = $node;
}
else if($level != 0 && $category->level > $level){
if(!isset($data[$n]["children"])){
$data[$n]["children"] = array();
}
$data[$parent]["children"][] = $node;
}
else
{
$data[] = $node;
$parent = $n;
}
$level=$category->level;
}
return $data;
}

Finally, my own recursive solution (works with multiple roots):
public function getTreeRecursive() {
$criteria = new CDbCriteria;
$criteria->order = 'root, lft';
$criteria->condition = 'level = 1';
$categories = Category::model()->findAll($criteria);
foreach($categories as $n => $category) {
$category_r = array(
'label'=>$category->title,
'url'=>'#',
'level'=>$category->level,
);
$this->category_tree[$n] = $category_r;
$children = $category->children()->findAll();
if($children)
$this->category_tree[$n]['items'] = $this->getChildren($children);
}
return $this->category_tree;
}
private function getChildren($children) {
$result = array();
foreach($children as $i => $child) {
$category_r = array(
'label'=>$child->title,
'url'=>'#',
);
$result[$i] = $category_r;
$new_children = $child->children()->findAll();
if($new_children) {
$result[$i]['items'] = $this->getChildren($new_children);
}
}
return $result_items = $result;
}

Creating multi-level category system with PHP & Yii (MVC Framework) in not just a simple undertaking.
1. Create Function in models
`
function getRootCategory($cur_cat='') {
$sql='select id, course_name, parent_id from course where parent_id="0" and status=0';
$command=Yii::app()->db->createCommand($sql);
$return =$command->queryAll();
foreach($return as $rootCat){
if ($rootCat['id']==$cur_cat){
$test= 'selected=selected';
}else{
$test='';
}
$id=$rootCat['id'];
echo "".$rootCat['course_name'].'';
$this->sub_cat($rootCat['id'] , '', $cur_cat );
}
}
function sub_cat($parentID=0, $space='',$cur_cat ) {
$sql="select id, course_name, parent_id from course where parent_id='$parentID' and status=0";
$command=Yii::app()->db->createCommand($sql);
$return =$command->queryAll();
$count=count($return);
if($parentID==0){ $space=''; }else{ $space .=" - "; }
if($count > 0){
foreach($return as $subcat){
if ($subcat['id']==$cur_cat){$test='selected=selected';}else{$test='';}
$ids=$subcat['id'];
echo "".$space.$subcat['course_name'].'';
$this->sub_cat($subcat['id'],$space, $cur_cat );
}
}
}
`
Now create this code in view/file.php
<?php
echo ‘<select id=”parent_id” class=”select” name=”Course[parent_id]” >’;
echo “<option value=’0′ >–Select Exam–</option>”;
echo Course::model()->getRootCategory($model->parent_id);
// ($model->parent_id) means selected text box
echo ‘</select>’; ?>
More Details click on this url Visit http://it-expert.in/create-multi-level-category-using-recursive-function-in-yii/

Related

Drupal "You are not authorized to access this page"

I've taken over managing our site from MIA developers and have spent the day trying to find this answer.
After upgrading to v 7.56 there's just ONE specific page in a list of pages that I am unable to access as an admin. (and unfortunately it's probably the most needed report in our admin panel).
Here's what I know:
Drupal Version 7.56
PHP 7.0.20
No errors when status report is run
Chron - no errors
Here's what I've done:
added $cookie_domain = '.example.com'; to settings.php
cleared browser cache and cookies
ensured admin has access to everything
cleared site cache
made sure code on page(s) was exactly the same as it was before I did the update
Not sure what to do or where to go from here. Any help is much appreciated.
UPDATE: When logged in as super admin, received HTTP 500 error. After more research, I updated the php.ini to include memory_limit = 64M ;
Now I can view the page as the superadmin, but it still isn't available for other admins.
Image 1: viewing page as admin
Image 2: viewing page as superadmin
function custom_reports_menu() {
$items['administration/upcoming-classes'] = array(
'title' => 'Upcoming Classes',
'page callback' => 'custom_reports_upcoming_classes_page',
'access callback' => 'user_access',
'access arguments' => array('admin wdcc reports'),
'file' => 'includes/custom_reports.upcoming-classes.inc',
'type' => MENU_CALLBACK,
);
$items['administration/class-details'] = array(
'title' => 'Class Details',
'page callback' => 'custom_reports_class_details_page',
'access callback' => 'user_access',
'access arguments' => array('admin wdcc reports'),
'file' => 'includes/custom_reports.class-details.inc',
'type' => MENU_CALLBACK,
);
return $items;
}
function custom_reports_upcoming_classes_page() {
drupal_add_css(base_path().path_to_theme().'/assets/css/outburst-accounts.css', array('type' => 'external'));
global $user;
$uid = $user->uid;
$output = '';
$upcoming_classes = custom_reports_get_upcoming_classes();
$attendee_count = custom_reports_get_attendee_count();
// upcoming classes
$output .= '<h2>Upcoming Classes</h2>';
$output .= custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count);
return $output;
}
function custom_reports_permission() {
return array(
'admin wdcc reports' => array(
'title' => t('Admin WDCC Reports'),
'description' => t('Perform administration tasks for WDCC.'),
//'cache' => DRUPAL_NO_CACHE,
),
);
}
function custom_reports_get_upcoming_classes() {
$today = date('Y-m-d');
$x = 0;
$classes = '';
// get classes from new db tables
$today = date('Y-m-d H:i:s');
$result = db_query("SELECT n.nid FROM node n, field_data_field_date fdfd WHERE n.status = :status AND n.type = :type AND n.nid = fdfd.entity_id AND fdfd.field_date_value >= :today ORDER BY fdfd.field_date_value ASC", array(':status' => 1, ':type' => 'public_class_date', ':today' => $today));
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$nid = $row->nid;
$node = node_load($nid);
$product_id = $nid;
$product_title = $node->title;
$product_type = 'public_class_date';
$product_date = $node->field_date[$node->language][0]['value'];
$product_datestamp = strtotime($product_date);
//$product_datestamp = strtotime($product_date);
// set vars
$classes[$x]['product_id'] = $product_id;
$classes[$x]['product_title'] = $product_title;
$classes[$x]['product_type'] = $product_type;
$classes[$x]['product_date'] = $product_date;
$classes[$x]['product_datestamp'] = $product_datestamp;
$x++;
}
}
return $classes;
}
function custom_reports_get_attendee_count() {
$attendees = array();
$old_attendees = array();
$new_attendees = array();
$result = db_query("SELECT itemID, attendeeID, attendeeName FROM wdcc_old_attendee");
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$item_id = $row->itemID;
$attendee_id = 'B'.$row->attendeeID;
$attendee_name = $row->attendeeName;
$old_attendees[$item_id][$attendee_id]['old_attendee_id'] = $attendee_id;
if (strpos($attendee_name, '&') > 0 || strpos($attendee_name, ' and') > 0) { // couples
$old_attendees[$item_id][$attendee_id]['total_attendees'] = 2;
} else {
$old_attendees[$item_id][$attendee_id]['total_attendees'] = 1;
}
}
}
if (is_array($old_attendees)) {
$connect_class_ids = custom_accounts_connect_class_ids();
foreach ($old_attendees as $old_item_id => $attendee_list) {
if (isset($connect_class_ids[$old_item_id])) {
$product_id = $connect_class_ids[$old_item_id];
foreach ($attendee_list as $attendee_id => $attendee) {
$old_attendee_id = $attendee['old_attendee_id'];
$attendees[$product_id][$old_attendee_id]['total_attendees'] = $attendee['total_attendees'];
}
}
}
}
$result = db_query("SELECT id, product_id FROM wdcc_attendees WHERE transaction_id > 0");
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$attendee_id = $row->id;
$product_id = $row->product_id;
$attendees[$product_id][$attendee_id]['total_attendees'] = 1;
}
}
$cancelled_attendees = array();
$result = db_query("SELECT * FROM wdcc_attendees_cancelled");
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$attendee_id = $row->attendee_id;
$old_attendee_id = 'B'.$row->old_attendee_id;
if ($attendee_id > 0) {
$cancelled_attendees[] = $attendee_id;
} else {
$cancelled_attendees[] = $old_attendee_id;
}
}
}
foreach ($attendees as $product_id => $product_attendees) {
foreach ($product_attendees as $attendee_id => $attendee) {
if (in_array($attendee_id, $cancelled_attendees)) {
unset($attendees[$product_id][$attendee_id]);
}
}
}
$attendee_count = array();
foreach ($attendees as $product_id => $product_attendees) {
foreach ($product_attendees as $attendee_id => $attendee) {
if (!isset($attendee_count[$product_id])) {
$attendee_count[$product_id] = $attendee['total_attendees'];
} else {
$attendee_count[$product_id] = $attendee_count[$product_id] + $attendee['total_attendees'];
}
}
}
return $attendee_count;
}
function custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count) {
$output = '';
if (is_array($upcoming_classes)) {
$output .= '<div class="table-responsive table-container">';
$output .= '<table class="table">';
$output .= '<tr><td>Class</td><td>Guests</td><td>Actions</td></tr>';
foreach ($upcoming_classes as $class) {
$nid = $class['product_id'];
$node_url = url('node/'.$nid, array('absolute' => TRUE));
$attendees = 0;
if (isset($attendee_count[$nid])) {
$attendees = $attendee_count[$nid];
}
$output .= '<tr><td>'.$class['product_title'].'<br />'.date('m/d/Y - g:i A', $class['product_datestamp']).'</td><td>'.$attendees.'</td><td>View roster</td></tr>';
}
$output .= '</table>';
$output .= '</div>';
} else {
$output .= '<p>No upcoming classes found.</p>';
}
return $output;
}
Probably would need more info, but it seems like a case of custom or hardcoded permissions.
Here's potential cases to explore:
Assign all the roles to the admin user
Search custom modules for this page URL. See if page is only certain users are allowed to access this page.
If report is Drupal View, find this view and check the permissions section.
In the current menu items you are using access callback attribute in a wrong way. Your menu items do not require to specify access callback. Only access argument is sufficient.
Please add an access argument to which only admin has access.
"access callback": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user_access() unless a value is inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the user_access() default callback, you must specify the permission to check as 'access arguments' (see below).
Source: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x
Replace this below code in settings.php file
PHP variable name:
$cookie_domain = 'example.com'; (line 340)
I was getting this error while login Drupal. After lots of reacher I found that we mistakenly blocked some internal IP of Drupal which is trigger while login the Drupal. So my suggestion is here Your should have to check if you have block any IP at your end (index.php file or anywhere). And You can TRUNCATE the Table session and flood from DB it also help you out.

How to filter based on I18n content with pagination component?

I have comeup with strange problem in cakephp 3.4. I am running filter query on i18n content like this.
if($this->request->query("q")){
$this->paginate["conditions"][$this->ContractTypes->translationField('title').' LIKE'] = '%'.$this->request->query("q").'%';
}
but following call is ending up in Database error
$records = $this->paginate($this->ContractTypes);
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ContractTypes_title_translation.content' in 'where clause' SELECT (COUNT(*)) AS `count` FROM contract_types ContractTypes WHERE ContractTypes_title_translation.content like :c0
The paginator's count query is not joing i18n table. What is the best approach to solve this problem.
Thanks in advance,
I have solved this by creating my custom paginator component by editing the paginate function. My paginator contains following code incase somebody else is facing the same problem.
namespace Console\Controller\Component;
use Cake\Controller\Component\PaginatorComponent as BasePaginator;
class PaginatorComponent extends BasePaginator
{
public function paginate($object, array $settings = [])
{
$query = null;
if ($object instanceof QueryInterface) {
$query = $object;
$object = $query->repository();
}
$alias = $object->alias();
$options = $this->mergeOptions($alias, $settings);
$options = $this->validateSort($object, $options);
$options = $this->checkLimit($options);
$options += ['page' => 1, 'scope' => null];
$options['page'] = (int)$options['page'] < 1 ? 1 : (int)$options['page'];
list($finder, $options) = $this->_extractFinder($options);
if (empty($query)) {
$query = $object->find($finder, $options);
} else {
$query->applyOptions($options);
}
$cleanQuery = clone $query;
// My Modification Starts Here
$table = $cleanQuery->repository();
$results = $query->all();
$numResults = count($results);
$count = $numResults ? $cleanQuery->select([
"count"=>$cleanQuery
->func()
->count($table->alias().'.'.$table->primaryKey())
])->first()->count : 0;
// My Modification ends Here
$defaults = $this->getDefaults($alias, $settings);
unset($defaults[0]);
$page = $options['page'];
$limit = $options['limit'];
$pageCount = (int)ceil($count / $limit);
$requestedPage = $page;
$page = max(min($page, $pageCount), 1);
$request = $this->_registry->getController()->request;
$order = (array)$options['order'];
$sortDefault = $directionDefault = false;
if (!empty($defaults['order']) && count($defaults['order']) == 1) {
$sortDefault = key($defaults['order']);
$directionDefault = current($defaults['order']);
}
$paging = [
'finder' => $finder,
'page' => $page,
'current' => $numResults,
'count' => $count,
'perPage' => $limit,
'prevPage' => $page > 1,
'nextPage' => $count > ($page * $limit),
'pageCount' => $pageCount,
'sort' => key($order),
'direction' => current($order),
'limit' => $defaults['limit'] != $limit ? $limit : null,
'sortDefault' => $sortDefault,
'directionDefault' => $directionDefault,
'scope' => $options['scope'],
];
if (!$request->getParam('paging')) {
$request->params['paging'] = [];
}
$request->params['paging'] = [$alias => $paging] + (array)$request->getParam('paging');
if ($requestedPage > $page) {
throw new NotFoundException();
}
return $results;
}
}

Adding additional search for reference in Joomla component

I am using a real estate component that has a front-end admin area to view property listings. An additional field was added to a section called custom fields that is named Ref (Reference). In the admin listings I am trying to add an additional search that searches for that reference. There are three tables involved here:
1j0_cddir_jomestate Which holds the property listings information such as title and description.
1j0_cddir_fields which is the custom fields created.
1j0_cddir_content_has_fields and this holds the values of the custom fields
I would need to join 1j0_cddir_content_has_fields "fields_id" with 1j0_cddir_fields "id" and 1j0_cddir_jomestate "id" must join 1j0_cddir_content_has_fields "content_id"
I am struggling to figure out how to add this function to the models/admin_listings.php so that I may add that search input to the admin_listings view.
<?php
protected $text_prefix = 'COM_JOMESTATE';
protected $user;
function __construct()
{
parent::__construct();
$this->user=JFactory::getUser();
$this->planID=$this->getPlanID();
}
protected function getListQuery()
{
// Initialise variables.
$db = $this->getDbo();
$query = $db->getQuery(true);
if ($this->planID->profile=='company'){
$query->select(
$this->getState(
'list.select',
'a.id AS id, a.title AS title, a.date_created, a.featured, a.users_id, a.published, '.
'c.title as category_title,a.date_publish,a.date_publish_down,ag.first_name,ag.last_name'
)
);
}else{
$query->select(
$this->getState(
'list.select',
'a.id AS id, a.title AS title, a.featured, a.date_created, a.users_id, a.published, '.
'c.title as category_title,a.date_publish,a.date_publish_down'
)
);
}
$query->from($db->quoteName('#__cddir_jomestate').' AS a');
$query->select('COUNT(l.id) AS viewHow, SUM(l.view_item) AS viewSum');
$query->join('LEFT', '#__cddir_statistic AS l ON (l.item_id = a.id AND l.extension=\'com_jomestate\')');
// Join over the categories.
$query->join('LEFT', '#__cddir_categories AS c ON c.id = a.categories_id');
$query->join('LEFT', '#__cddir_categories AS e ON e.id = a.categories_address_id');
if ($this->planID->profile=='company'){
$query->join('LEFT', '#__cddir_agent AS ag ON a.users_id = ag.users_id');
$query->join('LEFT', '#__cddir_company AS co ON co.id = ag.company_id');
}
$query->join('LEFT', '#__users AS u ON u.id = a.users_id');
// Filter by published published
$published = $this->getState('filter.published');
if (is_numeric($published)) {
$query->where('a.published = '.(int) $published);
}
// Filter by category.
$categoryId = $this->getState('filter.categories_id');
if (is_numeric($categoryId) && $categoryId!=0) {
$cat_tbl = JTable::getInstance('Category', 'JomcomdevTable');
$cat_tbl->load($categoryId);
$rgt = $cat_tbl->rgt;
$lft = $cat_tbl->lft;
$baselevel = (int) $cat_tbl->level;
$query->where('c.lft >= '.(int) $lft);
$query->where('c.rgt <= '.(int) $rgt);
}
$search = $this->getState('filter.search');
if (!empty($search)) {
if (stripos($search, 'id:') === 0) {
$query->where('a.id = '.(int) substr($search, 3));
} else {
$search = $db->Quote('%'.$db->escape($search, true).'%');
$query->where('(a.title LIKE '.$search.' OR a.alias LIKE '.$search.')');
}
}
if ($this->planID->profile=='company'){
$query->where('(a.users_id ='.(int) $this->user->id.' or co.users_id='.(int) $this->user->id.')');
}
else $query->where('a.users_id ='.(int) $this->user->id);
$sort = $this->getState('list.sort');
switch($sort) {
case 'most_viewed':
$query->order($db->escape('viewSum DESC, a.date_publish DESC'));
break;
case 'alfa':
$query->order($db->escape('a.title, a.date_publish DESC'));
break;
case 'featured':
$query->order($db->escape('a.featured DESC, a.date_publish DESC'));
break;
case 'latest':
default:
$query->order($db->escape('a.date_publish DESC'));
}
$query->group($db->escape('a.id'));
return $query;
}
function getCategories()
{
$cat_array = array(array('v'=>'','t'=>JText::_('COM_JOMESTATE_ADM_ALL')));
$query = "SELECT title, id, level FROM #__cddir_categories WHERE extension='com_jomestate.jomestate' ORDER BY lft";
$data = $this->_getList($query);
foreach ($data as $row):
for ($i=1;$i<$row->level;$i++) $row->title="   ".$row->title;
$temp_array=array('v'=>$row->id,'t'=>$row->title);
array_push($cat_array,$temp_array);
endforeach;
return $cat_array;
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* #since 1.6
*/
protected function populateState($ordering = null, $direction = null)
{
// Initialise variables.
$app = JFactory::getApplication('site');
// Load the parameters.
// $params = $app->getParams();
$params = JComponentHelper::getParams('com_jomestate');
$menu = $app->getMenu();
$this->active = $menu->getActive();
if ($this->active) {
$menuParams = $this->active->params;
$global = $menuParams->get('global_option');
if(!$global) {
$paramsa = $menuParams->toArray();
$paramsb = $params->toArray();
foreach($paramsa AS $key=>$p) $paramsb[$key] = $p;
$newObject = (object) $paramsb;
$newObject->activeItemid = $this->active->id;
$params->loadObject($newObject);
}
}
$this->setState('params', $params);
$limit = $this->getUserStateFromRequest($this->context.'.list.limit', 'jdItemsPerPage', $params->get('listing_per_page'), 'uint');
$this->setState('list.limit', $limit);
$value = $app->getUserStateFromRequest($this->context . '.list.limitstart', 'limitstart', 0);
$limitstart = ($limit != 0 ? (floor($value / $limit) * $limit) : 0);
$this->setState('list.start', $limitstart);
$search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search', '', 'string');
$this->setState('filter.search', $search);
$categoryId = $this->getUserStateFromRequest($this->context.'.filter.categories_id', 'filter_category', '', 'string');
$this->setState('filter.categories_id', $categoryId);
$sort = $this->getUserStateFromRequest($this->context.'.list.sort', 'jdItemsSort', 'latest', 'string');
$this->setState('list.sort', $sort);
}
public function getUserStateFromRequest($key, $request, $default = null, $type = 'none', $resetPage = true)
{
$app = JFactory::getApplication();
$old_state = $app->getUserState($key);
$cur_state = (!is_null($old_state)) ? $old_state : $default;
$new_state = JRequest::getVar($request, $old_state, 'default', $type);
if (($cur_state != $new_state) && ($resetPage))
{
JRequest::setVar('limitstart', 0);
}
// Save the new value only if it is set in this request.
if ($new_state !== null)
{
$app->setUserState($key, $new_state);
}
else
{
$new_state = $cur_state;
}
return $new_state;
}
public function getUser()
{
return $this->user;
}
public function getToolbar()
{
$document = JFactory::getDocument();
$document->addStyleSheet('administrator/templates/system/css/system.css');
$document->addStyleSheet('components/com_jomestate/assets/css/backadmin.css');
$controller='admin_listings';
jimport('joomla.html.toolbar');
$bar = new JToolBar( 'toolbar' );
if(Joomla_Version::if3()) {
$bar->appendButton( 'standard', 'new', JText::_('COM_JOMESTATE_ADM_ADD'), $controller.'.add', false );
$bar->appendButton( 'standard', 'publish', JText::_('COM_JOMESTATE_ADM_PUBLISH'), $controller.'.publish', false );
$bar->appendButton( 'standard', 'unpublish', JText::_('COM_JOMESTATE_ADM_UNPUBLISH'), $controller.'.unpublish', false );
$bar->appendButton( 'standard', 'delete', JText::_('COM_JOMESTATE_ADM_DELETE'), $controller.'.delete', false );
} else {
$bar->appendButton( 'Frontend', 'new', JText::_('COM_JOMESTATE_ADM_ADD'), $controller.'.add', false );
$bar->appendButton( 'Frontend', 'publish', JText::_('COM_JOMESTATE_ADM_PUBLISH'), $controller.'.publish', false );
$bar->appendButton( 'Frontend', 'unpublish', JText::_('COM_JOMESTATE_ADM_UNPUBLISH'), $controller.'.unpublish', false );
$bar->appendButton( 'Frontend', 'delete', JText::_('COM_JOMESTATE_ADM_DELETE'), $controller.'.delete', false );
}
return $bar->render();
}

Cakephp pagination custom order

I need to set the pagination order of my register based on field ($results[$key]['Movimento']['status']) created in afterFind callback.
afterFind:
public function afterFind($results, $primary = false) {
foreach ($results as $key => $val) {
if(isset($val['Movimento']['data_vencimento'])) {
$data = $val['Movimento']['data_vencimento'];
$dtVc = strtotime($data);
$dtHj = strtotime(date('Y-m-d'));
$dtVencendo = strtotime("+7 day", $dtHj);
if ($dtVc < $dtHj) {
$results[$key]['Movimento']['status'] = 'vencido';
} elseif ($dtVc <= $dtVencendo) {
$results[$key]['Movimento']['status'] = 'vc15dias';
} else {
$results[$key]['Movimento']['status'] = 'aberto';
}
}
if(isset($val['Movimento']['data_pagamento'])) {
$results[$key]['Movimento']['status'] = 'quitado';
}
}
return $results;
Pagination:
$options = array(
...
'order' => array('Movimento.status' => 'ASC')
);
$this->controller->paginate = $options;
$movimentos = $this->controller->paginate('Movimento');
I know this does not work because the field is created after the paginator call.
Can I make it work?
as I understand, you want to sort by data_pagamento and than by data_vencimento (has it the mysql-type date?)
so you don't need your afterFind-function for ordering, simply use:
'order' => array(
'Movimento.data_pagamento DESC',//first all rows with not-empty data_pagamento
'Movimento.data_vencimento DESC',// first all dates in the furthest future
)

Show a SQL interogation in a custom block in Drupal

i have problems when i'm trying to display the result of the following query:
SELECT COUNT(`entity_id` ) icount, `field_tags_tid`, `taxonomy_term_data`.`name`
FROM `field_data_field_tags`
INNER JOIN `taxonomy_term_data`
ON `taxonomy_term_data`.`tid`=`field_data_field_tags`.`field_tags_tid`
GROUP BY `field_tags_tid`
ORDER BY icount DESC
LIMIT 0 , 30
in a custom block in Drupal.
Here is my my_tags.module file:
<?php
function my_tags_block_info() {
$blocks = array();
$blocks['my_first_block'] = array(
'info' => t('My custom block'),
// DRUPAL_CACHE_PER_ROLE will be assumed.
);
return $blocks;
}
function my_tags_block_view($delta = '') {
if (arg(0) == 'node' && is_numeric(arg(1))) {
$nid = arg(1);
};
$block = array();
switch ($delta) {
case 'my_first_block':
$result = db_query('SELECT COUNT(`entity_id` ) icount, `field_tags_tid`, `taxonomy_term_data`.`name`
FROM `field_data_field_tags`
INNER JOIN `taxonomy_term_data`
ON `taxonomy_term_data`.`tid`=`field_data_field_tags`.`field_tags_tid`
GROUP BY `field_tags_tid`
ORDER BY icount DESC
LIMIT 0 , 10');
$list = array(
'#theme' => 'links',
'#links' => array(),
);
foreach ($result as $record) {
$list['#links'][] = array('title' => $record->name , 'name' => $record->icount);
}
$block['subject'] = t('Popular tags');
$block['content'] = $list;
break;
}
return $block;
}
?>
And as a result it is shown only the 'name' field, but i need and the 'icount' field.
Thank you.
Just solved my problem this way:
function my_tags_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'my_first_block':
$result = db_query('SELECT COUNT(`entity_id` ) icount, `field_tags_tid`, `taxonomy_term_data`.`name`, `revision_id`
FROM `field_data_field_tags`
INNER JOIN `taxonomy_term_data`
ON `taxonomy_term_data`.`tid`=`field_data_field_tags`.`field_tags_tid`
GROUP BY `field_tags_tid`
ORDER BY icount DESC
LIMIT 0 , 10');
foreach ($result as $record) {
$list[] = l($record->name, 'taxonomy/term/'.$record->field_tags_tid);
}
dpm($list);
$block['subject'] = t('Popular tags');
$block['content'] = theme('item_list', array('items' => $list));;
break;
}

Categories