Query Join table to sort by menudindex - php

Here is my query:
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues WHERE tmplvarid=107");
I need to sort it by menuindex so i tried this:
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues JOIN modResource WHERE tmplvarid=107 ORDER BY menuindex DESC");
I'm not familiar at all whith this. Of course it doesn't work. Someone told me to use XPDO but i know nothing about it. Do i miss something? What should i do to make it work ?
Here is the full code :
<?php
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues WHERE tmplvarid=107");
// description tv: 108
// vignette tv: 121
if (!is_object($results)) {
return;
}
$breves = array();
while($r = $results->fetch(PDO::FETCH_COLUMN, 0)){
$breves[] = $r;
}
$queryIn = implode(',' , $breves);
$results_2 = $modx->query("SELECT contentid, tmplvarid, value FROM modx_site_tmplvar_contentvalues WHERE contentid IN ({$queryIn}) AND tmplvarid IN (108, 121)");
if (!is_object($results_2)) {
return;
}
$tvValues = array();
while($v = $results_2->fetch(PDO::FETCH_ASSOC)){
if($v['tmplvarid'] == 108){
$tvValues[$v['contentid']]['desc'] = $v['value'];
} else {
$tvValues[$v['contentid']]['vignette'] = $v['value'];
}
}
$output = "";
foreach ($breves as $res_id) {
$page = $modx->getObject('modResource', $res_id);
$alias = $page->get('alias');
$id = $page->get('id');
$page_title = $page->get('pagetitle');
$description = $tvValues[$res_id]['desc'];
if(!$description || $description == ""){
$description = $page->get('content');
}
$description = strip_tags($description);
$description = mb_strimwidth($description, 0, 150, "...");
$vignette = $tvValues[$res_id]['vignette'];
if($vignette){
$vignette = "/assets/upload/pln/" . $vignette;
} else {
$vignette = "https://www.commune-ploudaniel.fr/assets/templates/pln/default-b7824fcd998f51baf0f0af359a72e760.png";
}
$output .= <<<HTML
<div class="xpro-slider-item">
<div class="xp-news-classic-block">
<div class="xp-hover-image">
</div>
<a class="xp-view-lightbox" href="{$alias}.html" ><i class="fa fa-plus"></i></a>
<img src="{$vignette}" alt="{$alias}" style="width:375px; height:270px; object-fit: cover;"/>
</div>
<div class="xp-news-detail">
<h4>{$id}{$page_title}</h4>
<p>{$description}</p>
<div class='xp-news-footer'></div>
</div>
</div>
</div>
HTML;
$output .= PHP_EOL;
}
return $output;

Try this for MODX:
$q = $modx->newQuery('modTemplateVarResource');
$q->leftJoin('modResource', 'mr', 'mr.id = modTemplateVarResource.contentid');
$q->where(array(
'modTemplateVarResource.tmplvarid' => 107
));
$q->select(array(
'modTemplateVarResource.contentid'
));
$q->sortby('modResource.menuindex', 'DESC');
$q->prepare();
$q->stmt->execute();
$result = $q->stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);

Related

Insert archive loop insert another page

I have archive.php in my content management system which allows to search for articles like mywebsite.com/archive?s=test. Now i tried to show this posts of the search query in another page of my page. Like <?php insert('archive.php?s=test'); ?> .
I am not an expert on PHP coding. But maybe you can show me a way how i could import this post of a search query with archive.php loop. Or tell me that this is not possible :-) Thank you.
This is the code my archive page.
<?php if (!$t['page_heading']) : ?>
<?php endif; ?>
<?php if (has_items($t['latest_posts'])) : ?>
<div class="row">
<?php foreach ($t['latest_posts'] as $t['loop']) : ?>
<div class="col-12 mb-3">
<?php insert('partials/loop.php'); ?>
</div>
<?php endforeach; ?>
</div> </div> </div>
<?= $t['pagination_html']; ?>
<?php else : ?>
<?php
insert(
'partials/empty.php',
[
'empty_message' => __('nothing-found-archive', _T)
]
);
?>
<?php endif; ?>
This is the loop.php
<?= e(limit_string($t['loop.post_title'], 65), false); ?>
</h3></a>
<div class="post-footer text-muted">
<div id="hidden-xs"> <?= e(limit_string($t['loop.post_excerpt'], 145), false); ?></div>
<div class="mb-1 mt-1"> <span class="badge badge-cat"><i class="fas fa-newspaper"></i> <?= e_attr($t['loop.feed_name']) ?></span> <span class="badge badge-cat"><i class="far fa-folder-open"></i> <?= e_attr($t['loop.category_name']) ?></span>
<span class="badge badge-cat"><i class="far fa-clock"></i> vor <?= time_ago($t['loop.post_pubdate'], _T); ?></span>
search function
public function archive()
{
$app = app();
$postModel = new PostModel;
$feedModel = new FeedModel;
$engineModel = new EngineModel;
$categoryModel = new CategoryModel;
$data = [
'title' => __('archive', _T),
'meta.description' => __('archive-description', _T),
'body_class' => 'archive',
'searching_site' => false,
'by_feed' => false,
];
$query = sp_strip_tags(trim($app->request->get('s')), true);
$feedID = (int) $app->request->get('feed', 0);
$feedsTable = $feedModel->getTable();
$postsTable = $postModel->getTable();
$categoriesTable = $categoryModel->getTable();
// Current page number
$currentPage = (int) $app->request->get('page', 1);
$filters['sort'] = 'post-publish-date';
if (mb_strlen($query) > 3) {
$filters['where'][] = ["{$postsTable}.post_title", 'LIKE', "%$query%"];
$filters['where'][] = ["{$postsTable}.post_content", 'LIKE', "%$query%", 'OR'];
$data['site_search_query'] = $query;
$data['searching_site'] = true;
$data['page_heading'] = sprintf(__('search-results-for', _T), $query);
$data['title'] = sprintf(__('search-results-for-title', _T), $query);
$data['meta.description'] = sprintf(__('search-results-for-desc', _T), $query);
$data['body_class'] .= ' search-results';
}
if ($feedID) {
$feed = $feedModel->read($feedID, ['feed_id', 'feed_name']);
if ($feed) {
$filters['where'][] = ["{$postsTable}.post_feed_id", '=', $feed['feed_id']];
$data['by_feed'] = true;
$data['feed'] = $feed;
$data['title'] = $feed['feed_name'];
$data['page_heading'] = $feed['feed_name'];
}
}
$itemsPerPage = (int) get_option('latest_posts_count', 10);
// Total item count
$totalCount = $postModel->countRows(null, $filters);
$pageQuery = [];
if ($data['searching_site']) {
$pageQuery['s'] = $query;
}
if ($data['by_feed']) {
$pageQuery['feed'] = $feedID;
}
$queryStr = http_build_query($pageQuery);
if (!empty($queryStr)) {
$queryStr = "&{$queryStr}";
}
// Pagination instance
$pagination = new Pagination($totalCount, $currentPage, $itemsPerPage);
$pagination->setUrl("?page=#id#{$queryStr}");
// Generated HTML
$paginationHtml = $pagination->renderHtml();
// Offset value based on current page
$offset = $pagination->offset();
// Fields to query
$fields[] = "{$postsTable}.post_id, {$postsTable}.post_category_id, {$postsTable}.post_title, {$postsTable}.post_excerpt, {$postsTable}.post_featured_image, {$postsTable}.post_type, {$postsTable}.post_source, {$postsTable}.post_pubdate, {$postsTable}.created_at, {$postsTable}.post_hits";
$fields[] = "{$feedsTable}.feed_name, {$feedsTable}.feed_id, {$feedsTable}.feed_logo_url";
$fields[] = "{$categoriesTable}.category_name, {$categoriesTable}.category_slug, {$categoriesTable}.category_icon";
// Query to fetch the users and their respective role names
$sql = $postModel->select($fields)
->leftJoin(
$feedsTable,
"{$postsTable}.post_feed_id",
'=',
"{$feedsTable}.feed_id"
)->leftJoin(
$categoriesTable,
"{$postsTable}.post_category_id",
'=',
"{$categoriesTable}.category_id"
)->limit($itemsPerPage, $offset);
// Apply Filters
$sql = $postModel->applyModelFilters($sql, $filters);
$stmt = $sql->execute();
// List entries
$latestPosts = $stmt->fetchAll();
$maxSliderItems = get_option('max_slider_items', 10);
$sliderPosts = array_slice($latestPosts, 0, $maxSliderItems);
$engines = $engineModel->readMany(['engine_id', 'engine_name']);
$data['default_engine'] = (int) get_option('default_engine');
$data['engines'] = $engines;
$data['archive_active'] = 'active';
$data['slider_posts'] = $sliderPosts;
$data['latest_posts'] = $latestPosts;
$data['pagination_html'] = $paginationHtml;
return view('archive.php', $data);
}

display only if has group of numbers

I need to return list with prices only if there have groups i try already if else empty not !=
nothing help any suggestions ?
$usergroups = '11,9,10';
if (empty($usergroups)) {
return;
}
$fields = 'MIN(IF(prices.percentage_discount = 0, prices.price, prices.price - (prices.price * prices.percentage_discount)/100)) as price, prices.usergroup_id as usergroup_id, ud.usergroup as usergroup_name';
$condition = db_quote(' prices.product_id = ?i AND prices.usergroup_id IN (?p) AND ud.lang_code = ?s', $product['product_id'], $usergroups, DESCR_SL);
$group_by = 'usergroup_id';
$join = '?:usergroup_descriptions as ud ON ud.usergroup_id = prices.usergroup_id';
$opt_prices = db_get_array("SELECT ?p FROM ?:product_prices as prices LEFT JOIN ?p WHERE ?p GROUP BY ?p", $fields, $join, $condition, $group_by);
$currencies = Registry::get('currencies');
foreach ($opt_prices as &$price) {
$price['current'] = 0;
if (in_array($price['usergroup_id'], $auth['usergroup_ids'])) {
$price['current'] = 1;
$product['price'] = $price['price'];
}
$price['price'] = number_format($price['price'], 2, '.', ' ') . ' $';
}
$product['group_discounts'] = $opt_prices;
}
So i want display $product['group_discounts'] = $opt_prices;
only if there is $usergroups = '11,9,10';
Answer your comment:
You used that but ok here an example :
<?php
$usergroups = array('11','9','10');
$opt_prices='11';
if (in_array($opt_prices,$usergroups)){
echo 'yes';
}else{
echo 'no';
}
?>

Using an If statement in PHP but not working

What I want to do is When I enter all my information (for client ID 199 in the picture) In my account being submit it, it goes into the database. BUT I want it to change to something and so i added an if statement
Here the code im adding to the existing code already at the BOTTOM of the code
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
if the ($vpr_clid = 199)
i want the clname to be "Shelley Madsen And Associates" then what is show in the table below instead of "Nice and White Smiles" (that an example of the results look like)
but when i chcek the database it not changing it and still show "Nice and White Smiles :(
I dont see any error, so it might be the placement of the code i have to put the IF statement in the huge php file? Dont know how to fix this issue
Thanks (the code below is the base code before i added the If statement)
I also insert the if statement before the function were called but still didnt work example
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
<?php
session_start();
if ($_SESSION['company'] != "ACB") {
// redirect to the logout page
$redirect = 'logout.php';
include './includes/redirect.php';
}
class variables_obj {
var $vpr_plan = '';
var $vpr_id = '';
var $vpr_clid = '';
var $vpr_cl_name = '';
var $vpr_cl_phone = '';
var $vpr_call_start_date = '';
var $vpr_db_account = '';
var $vpr_db_fname = '';
var $vpr_db_mname = '';
var $vpr_db_lname = '';
var $vpr_rp_fname = '';
var $vpr_rp_mname = '';
var $vpr_rp_lname = '';
var $vpr_rp_address = '';
var $vpr_rp_city = '';
var $vpr_rp_state = '';
var $vpr_rp_zipcode = '';
var $vpr_rp_phonenum = '';
var $vpr_rp_phonetype = '';
var $vpr_date_entered = '';
var $newrecdt = '';
var $vpl_day_offset = '';
var $vpl_action = '';
var $vpr_promocode = '';
}
function ScrubPhone($old_phone_num) {
$phone_length = strlen($old_phone_num);
$new_phone_num = "";
for($i = 0; $i < $phone_length; $i = $i + 1) {
if(is_numeric($old_phone_num[$i])) {
$new_phone_num .= $old_phone_num[$i];
}
}
return $new_phone_num;
}
function ScheduleCreated($link, $vars) {
$query = "UPDATE v_payreminder SET vpr_schedule_created = '1' WHERE vpr_id='".$vars->vpr_id."'";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateScheduleRow($link, $vars){
// echo "vpl_day_offset: ".$vars->vpl_day_offset."<br>";
// echo "vpl_action: ".$vars->vpl_action."<br>";
$plus_days = " +".$vars->vpl_day_offset." days";
// echo "plus days: ".$plus_days."<br>";
$date_offset = strtotime(date("Y-m-d", strtotime($vars->vpr_date_entered)).$plus_days);
$date_offset = date("Y-m-d", $date_offset);
// echo "date_offset: ".$date_offset."<br>";
// $date_offset = strtotime(date("Y-m-d",strtotime($vars->vpr_date_entered))." +".$vars->vpl_day_offset." days");
// $date_offset = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");
// echo "date_offset: ".$date_offset."<br>";
$query = "INSERT INTO v_pr_schedule (
vpr_id,
vsc_plan,
vsc_date_entered,
vsc_action,
vsc_action_date,
vsc_status
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'$vars->vpl_action',
'$date_offset',
'VACT')";
//echo "query: ".$query."<br>";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateSchedule($link, &$vars) {
// CREATE SCHEDULE
$query = " SELECT vpl_day_offset, vpl_action, vpl_condition
FROM v_plan
WHERE vpl_plan = '".$vars->vpr_plan."'";
// echo "query: ".$query."<br>";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
while ($row = mysql_fetch_array($qresult, MYSQL_ASSOC)) {
$vars->vpl_day_offset = $row['vpl_day_offset'];
$vars->vpl_action = $row['vpl_action'];
if ($row['vpl_condition'] == 'OO') {
CreateScheduleRow($link, $vars);
}
}
}
return true;
}
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
//echo "Client Name: ".$vars->vpr_cl_name."<br><br>";
//exit();
$sql="INSERT INTO v_payreminder (
vpr_clid,
vpr_cl_name,
vpr_cl_phone,
vpr_call_start_date,
vpr_db_account,
vpr_db_fname,
vpr_db_mname,
vpr_db_lname,
vpr_rp_fname,
vpr_rp_mname,
vpr_rp_lname,
vpr_rp_phonenum,
vpr_rp_phonetype,
vpr_rp_address,
vpr_rp_city,
vpr_rp_state,
vpr_rp_zipcode,
vpr_promo,
vpr_date_entered) VALUES (
'$vars->vpr_clid',
'$vars->vpr_cl_name',
'$vars->vpr_cl_phone',
'$vars->vpr_call_start_date',
'$vars->vpr_db_account',
'$vars->vpr_db_fname',
'$vars->vpr_db_mname',
'$vars->vpr_db_lname',
'$vars->vpr_rp_fname',
'$vars->vpr_rp_mname',
'$vars->vpr_rp_lname',
'$vars->vpr_rp_phonenum',
'$vars->vpr_rp_phonetype',
'$vars->vpr_rp_address',
'$vars->vpr_rp_city',
'$vars->vpr_rp_state',
'$vars->vpr_rp_zipcode',
'$vars->vpr_promocode',
'$vars->vpr_date_entered')";
if (!mysql_query($sql,$link)) {
die('Error2: ' . mysql_error());
}
return true;
}
function GetVpr_Id($link, &$vars) {
// Find out what vpr_id is
$query = "SELECT vpr_id FROM v_payreminder ";
$query .= "WHERE vpr_clid = '".$vars->vpr_clid."' AND vpr_date_entered = '".$vars->vpr_date_entered."'";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
$row = mysql_fetch_array($qresult, MYSQL_ASSOC);
$vars->vpr_id = $row['vpr_id'];
}
}
function InsertInActivity($link, $vars) {
// ENTER INTO ACTIVITY
$vaction_desc = 'PATIENT ENTERED';
$sql = "INSERT INTO v_pr_activity (
vpr_id,
va_plan,
va_action_dttm,
va_action_code,
va_action_desc,
va_disposition_code,
va_disposition_desc,
va_status_code,
va_status_desc
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'VINIT',
'$vaction_desc',
'SUCCESS',
'SUCCESS',
'VACT',
'ACTIVE'
)";
if (!mysql_query($sql,$link)) {
die('Error: ' . mysql_error());
}
}
include './includes/dblogin.php';
$vars = new variables_obj();
$vars->vpr_plan = 'VP01';
$vars->vpr_clid = $_SESSION['userid'];
//-------------------------------------------------------
// No commas can be in client name or they will
// mess up the Global Connect CSV file.
//-------------------------------------------------------
$vpr_cl_name = $_SESSION['username'];
$vpr_cl_name = str_replace(",", " ", $vpr_cl_name);
$vars->vpr_cl_name = $vpr_cl_name;
//-------------------------------------------------------
//-------------------------------------------------------
$vars->vpr_cl_phone = ScrubPhone($_SESSION['uphone']);
$vars->vpr_call_start_date = '0000-00-00';
$vars->vpr_db_account = $_POST['ndaccnum'];
$vars->vpr_db_fname = $_POST['ndfreqname'];
$vars->vpr_db_mname = $_POST['ndmname'];
$vars->vpr_db_lname = $_POST['ndlreqname'];
$vars->vpr_rp_fname = $_POST['ndrfreqname'];
$vars->vpr_rp_mname = $_POST['ndrmname'];
$vars->vpr_rp_lname = $_POST['ndrlreqname'];
$vars->vpr_rp_address = '';
$vars->vpr_rp_city = '';
$vars->vpr_rp_state = $_POST['ndrstatereqname'];
$vars->vpr_rp_zipcode = $_POST['ndrreqzipcode'];
$phonenumber = $_POST['1ndrreqphone'].$_POST['2ndrreqphone'].$_POST['3ndrreqphone'];
$vars->vpr_rp_phonenum = $phonenumber;
$vars->vpr_rp_phonetype = $_POST['treqphone'];
$vars->vpr_date_entered = date('Y-m-d H:i:s');
$vars->newrecdt = date('Ymd');
$vars->vpr_promocode = $_POST['promocode'];
// echo "vpr_plan: ".$vars->vpr_plan."<br>";
// echo "vpr_date_entered: ".$vars->vpr_date_entered."<br>";
// echo "newrecdt: ".$vars->newrecdt."<br>";
// echo "vpr_clid: ".$vars->vpr_clid."<br>";
// echo "vpr_id: ".$vars->vpr_id."<br>";
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
$result = InsertInActivity($link, $vars);
$result = CreateSchedule($link, $vars);
$result = ScheduleCreated($link, $vars);
// echo "vpr_id: ".$vars->vpr_id."<br>";
mysql_close($link);
// redirect
$redirect = 'vpayremind.php';
include './includes/redirect.php';
?>
okay referencing the following lines..
if ( $vpr_clid == 199 ) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
...and then:
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
so on and so forth... }
it doesnt seem as if you are actually setting the value of the class object. You seem to be setting some arbitrary php variable to the name you want, and then passing a totally different ' $vars ' object into the function. I don't see any reason to believe that the ' $vars ' you are passing into the function call contains the name value you want it to contain. You should be assigning the value of ' $vars ' before passing it in.
For instance:
if ( $vpr_clid == 199 ) {
$vars[ 'vpr_cl_name' ] = "Shelley Madsen And Associates";
}
then you can get rid of this line all together:
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");

Exclude value from foreach loop output

I am looking to exclude a specific value from my foreach output where it occurs in either friend_one or friend_two. I do not want to exclude this from my query.
The parameter to exclude would be $profile_user where it occurs in either friend_one or friend_two. I tried to do this if(in_array($friend_total_row->friend_one == $profile_user)), but I am getting errors with it, plus it only has friend_one in it.
Anyone have an idea how I can do this?
<?php
//Friends --- total
$friend_status = 2;
$friend_sql = "
SELECT *
FROM friends
WHERE (friend_one = :profile_user or friend_two = :profile_user)
AND status = :total_status
";
$friend_stmt = $con->prepare($friend_sql);
$friend_stmt->execute(array(':profile_user' => $profile_user, ':total_status' => $friend_status));
$friend_total_rows = $friend_stmt->fetchAll(PDO::FETCH_ASSOC);
$count_total_friend = $friend_stmt->rowCount();
?>
<div id="friend-list-container">
<div id="friend-list-count">Friends <span class="light-gray"><?php echo $count_total_friend; ?></span></div>
<div id="friend-list-image-container">
<?php
foreach ($friend_total_rows as $friend_total_row) {
if(in_array($friend_total_row->friend_one == $profile_user)) {
continue;
}
else {
$friend_1 = $friend_total_row['friend_one'];
$friend_2 = $friend_total_row['friend_two'];
//$friend_status = $friend_total_row['status'];
//$friend_status_date = $friend_total_row['date'];
}
echo $friend_1 . $friend_2;
}
?>
I am only wanting to exclude the $profile_user from outputting, which is where the X is. Then I want the squared output to show.
Updated answer :
foreach ($friend_total_rows as $friend_total_row) {
$friend_1 = $friend_total_row['friend_one'];
$friend_2 = $friend_total_row['friend_two'];
if($friend_1 !== $profile_user) {
echo $friend_1;
}
if($friend_2 !== $profile_user) {
echo $friend_2;
}
}

A Mysql Query from joomla is taking very long time

Sorry for this Question. I am not a Good Programmer
Everything Executed well with few menu items. but with 14K menu items. i stuck with this query. This is happening when i try to access
administrator/index.php?option=com_modules&view=module&layout=edit&id=97
Is there any way to alter the query ??
Query
SELECT a.id AS value,
a.title AS text,
a.alias,
a.level,
a.menutype,
a.type,
a.template_style_id,
a.checked_out
FROM gjb0e_menu AS a
LEFT JOIN `gjb0e_menu` AS b
ON a.lft > b.lft
AND a.rgt < b.rgt
WHERE a.published != -2
GROUP BY a.id,
a.title,
a.alias,
a.level,
a.menutype,
a.type,
a.template_style_id,
a.checked_out,
a.lft
ORDER BY a.lft ASC
Php code
require_once JPATH_ADMINISTRATOR . '/components/com_menus/helpers/menus.php';
$menuTypes = MenusHelper::getMenuLinks();
<ul class="treeselect">
<?php foreach ($menuTypes as &$type) : ?>
<?php if (count($type->links)) : ?>
<?php $prevlevel = 0; ?>
<li>
<div class="treeselect-item pull-left">
<label class="pull-left nav-header"><?php echo $type->title; ?></label></div>
<?php foreach ($type->links as $i => $link) : ?>
<?php
if ($prevlevel < $link->level)
{
echo '<ul class="treeselect-sub">';
} elseif ($prevlevel > $link->level)
{
echo str_repeat('</li></ul>', $prevlevel - $link->level);
} else {
echo '</li>';
}
$selected = 0;
if ($this->item->assignment == 0)
{
$selected = 1;
} elseif ($this->item->assignment < 0)
{
$selected = in_array(-$link->value, $this->item->assigned);
} elseif ($this->item->assignment > 0)
{
$selected = in_array($link->value, $this->item->assigned);
}
?>
<li>
<div class="treeselect-item pull-left">
<input type="checkbox" class="pull-left" name="jform[assigned][]" id="<?php echo $id . $link->value; ?>" value="<?php echo (int) $link->value; ?>"<?php echo $selected ? ' checked="checked"' : ''; ?> />
<label for="<?php echo $id . $link->value; ?>" class="pull-left"><?php echo $link->text; ?> <span class="small"><?php echo JText::sprintf('JGLOBAL_LIST_ALIAS', $this->escape($link->alias));?></span></label>
</div>
<?php
if (!isset($type->links[$i + 1]))
{
echo str_repeat('</li></ul>', $link->level);
}
$prevlevel = $link->level;
?>
<?php endforeach; ?>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
Here is the function which creates the Query.
public static function getMenuLinks($menuType = null, $parentId = 0, $mode = 0, $published = array(), $languages = array())
{
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('a.id AS value, a.title AS text, a.alias, a.level, a.menutype, a.type, a.template_style_id, a.checked_out')
->from('#__menu AS a')
->join('LEFT', $db->quoteName('#__menu') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt');
// Filter by the type
if ($menuType)
{
$query->where('(a.menutype = ' . $db->quote($menuType) . ' OR a.parent_id = 0)');
}
if ($parentId)
{
if ($mode == 2)
{
// Prevent the parent and children from showing.
$query->join('LEFT', '#__menu AS p ON p.id = ' . (int) $parentId)
->where('(a.lft <= p.lft OR a.rgt >= p.rgt)');
}
}
if (!empty($languages))
{
if (is_array($languages))
{
$languages = '(' . implode(',', array_map(array($db, 'quote'), $languages)) . ')';
}
$query->where('a.language IN ' . $languages);
}
if (!empty($published))
{
if (is_array($published))
{
$published = '(' . implode(',', $published) . ')';
}
$query->where('a.published IN ' . $published);
}
$query->where('a.published != -2')
->group('a.id, a.title, a.alias, a.level, a.menutype, a.type, a.template_style_id, a.checked_out, a.lft')
->order('a.lft ASC');
// Get the options.
$db->setQuery($query);
try
{
$links = $db->loadObjectList();
}
catch (RuntimeException $e)
{
JError::raiseWarning(500, $e->getMessage());
return false;
}
if (empty($menuType))
{
// If the menutype is empty, group the items by menutype.
$query->clear()
->select('*')
->from('#__menu_types')
->where('menutype <> ' . $db->quote(''))
->order('title, menutype');
$db->setQuery($query);
try
{
$menuTypes = $db->loadObjectList();
}
catch (RuntimeException $e)
{
JError::raiseWarning(500, $e->getMessage());
return false;
}
// Create a reverse lookup and aggregate the links.
$rlu = array();
foreach ($menuTypes as &$type)
{
$rlu[$type->menutype] = & $type;
$type->links = array();
}
// Loop through the list of menu links.
foreach ($links as &$link)
{
if (isset($rlu[$link->menutype]))
{
$rlu[$link->menutype]->links[] = & $link;
// Cleanup garbage.
unset($link->menutype);
}
}
return $menuTypes;
}
else
{
return $links;
}
You can simply remove the join. I'm pretty sure the join has absolutely no effect in your query, and it will be a lot quicker. You can try to run the query directly in your database with and without the join, to verify that the result is the same.
I'm not sure what this join was intended to do, but i guess it is some remnant of some functionality the programmer was trying to achieve, but that was realized differently or dropped, leaving a useless join.
The structure of this kind of hierarchical table is like this to prevent these sort of join. You have a lft and a rgt value, and any item that is between the lft and the rgt is a sub-item. In addition you have a level-value, telling you how deep in the tree a value is. So to select all children of an item, you can do:
select * where lft>item.lft and rgt>item.rgt
To select only direct descendants of your item, do
select * where lft>item.lft and rgt>item.rgt and level=item.level+1
The structure in the database is a little hard to maintain, requiring special functions to update the data, but it is quick to search and extract data.
So, your getMenuLinks() - function should start like
public static function getMenuLinks($menuType = null, $parentId = 0,
$mode = 0, $published = array(), $languages = array())
{
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('a.id AS value, a.title AS text, a.alias, a.level,
a.menutype, a.type, a.template_style_id, a.checked_out')
->from('#__menu AS a');
// Filter by the type
if ($menuType)
...

Categories