I want to make a sidebar menu like the website mega.nz in php.. like this
I have tried with this code:
function foldersList($folderName = NULL) {
$return = '';
$globFolder = ($folderName != NULL ? $folderName : './server/'.$_SESSION['username']) . "/*";
foreach (glob($globFolder, GLOB_ONLYDIR) as $subFolder) {
$baseFolder = basename($subFolder) . '';
// okay let me see
// call function to check subfolders - don't forget write `/`
$subFolders = foldersList($subFolder);
$return .= '<li><a><i class="fa fa-desktop"></i>' . $baseFolder . '<span class="fa fa-chevron-down"></span></a>';
$return .= '<ul class="nav child_menu">';
// if subfolder exist add to return variable
$return .= $subFolders != '' ? $subFolders : '';
$return .= '</ul>';
$return .= '</li>';
}
return $return;
}
but the problem is the folder doesn't recognize if inside the folder, have one more folder or have a list of files.
I want, if folder have list of files inside, go to another link
if folder, have one more folder, makes dropdown menu, to show this folder.
To skip empty folders or folders that have only files change the function to:
function foldersList($folderName = NULL) {
$return = '';
$globFolder = ($folderName != NULL ? $folderName : './server/'.$_SESSION['username']) . "/*";
$folders = glob($globFolder, GLOB_ONLYDIR);
if(!empty($folders)) {
foreach ($folders as $subFolder) {
$baseFolder = basename($subFolder) . '';
// okay let me see
// call function to check subfolders - don't forget write `/`
$subFolders = foldersList($subFolder);
$return .= '<li><a><i class="fa fa-desktop"></i>' . $baseFolder . '<span class="fa fa-chevron-down"></span></a>';
$return .= '<ul class="nav child_menu">';
// if subfolder exist add to return variable
$return .= $subFolders != '' ? $subFolders : '';
$return .= '</ul>';
$return .= '</li>';
}
}
return $return;}
Other solution: use a nice plug-in to help you with the tree https://www.jstree.com/
EDIT: added example usage of jstree
Change your function to:
function foldersList($folderName = NULL) {
$return = '';
$globFolder = ($folderName != NULL ? $folderName :
'./server/'.$_SESSION['username']) . "/*";
$folders = glob($globFolder, GLOB_ONLYDIR);
$foldersArray = [];
if(!empty($folders)) {
foreach ($folders as $subFolder) {
$baseFolder = basename($subFolder) . '';
// okay let me see
// call function to check subfolders - don't forget write `/`
$subFolders = foldersList($subFolder);
$foldersArray[] = [
'text' => $baseFolder,
'children' => $subFolders
];
}
}
return $foldersArray;}
Here is a demo with the output of modified function: https://jsfiddle.net/mrazvan/3sxh0b3c/1/
Create a file where you run the function and echo the json output in one php file:
echo json_encode( foldersList('path/to/folder/'));exit;
To fetch the output from back end, you can try using the following JS code:
$(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "path/to/phpfile.php",
success: function(data) {
$('#tree-container').jstree({
'plugins' : ['types'],
'core' : {
'data' : data,
'themes' : {
'variant' : 'medium'
}
}
});
}
});
});
Related
I am building out a nested menu for a Magento store I am working on. The store has around 700 categories in total (that are nested around 4 levels at most) that need to be spat out into this menu.
The code I have written takes on average 2.5s to process (tested using microtime).
I am wondering if this is unavoidable given the amount of categories that need to be processed.
Anyways, this is the code I have come up with (go easy I am a front end dev by trade): NOTE: is am also using this code to loop out CMS pages in the same fashion
$type = Mage::registry('current_category') ? 'category' : 'page';
if($type == 'category') {
$currentID = Mage::registry('current_category')->getId();
$parentIDs = explode('/', Mage::registry('current_category')->path);
$rootID = Mage::app()->getStore()->getRootCategoryId();
}
else {
$currentID = Mage::getSingleton('cms/page')->getId();
$parentIDs = Mage::getSingleton('cms/page')->getPathIds();
$rootID = 0;
}
function checkChildHtml($parentId, $htmlString) {
$string = '';
if($parentId != $rootID) {
$string = $htmlString;
}
return $string;
}
// Recurse the site tree and build out a menu
function buildChildMenu($type, $currentID, $parentId, $isChild, $parentIDs, $rootID) {
// Get the appropriate collection based on type
if($type == 'category') {
$children = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active', '1')
->addAttributeToFilter('include_in_menu', '1')
->addAttributeToFilter('parent_id', array('eq' => $parentId))
->addAttributeToSort('position', 'asc');
}
else {
$children = Mage::getModel('cms/page')->getCollection()
->addFieldToSelect('*')
->addFieldToFilter('is_active', '1')
->addFieldToFilter('include_in_menu', '1')
->addFieldToFilter('parent_id', array('eq' => $parentId))
->setOrder('position','asc');
}
// TODO check for $parentID != $rootID is a little hacky, need to DRY this up
$html .= ($parentId != $rootID) ? '<ul>' : null;
// Loop over categories at the current level
foreach($children as $child) {
$childId = $child->getId();
$parent = (count($child->getChildren()) > 0) ? $child->getChildren() : false;
$classes = [];
// Build out class lists
if($parent) {
$classes[] = 'parent';
}
if(in_array($childId, $parentIDs, true) || count($children) == 1) {
$classes[] = "current active";
}
if($childId == $currentID) {
$classes[] = "current-page";
}
// Build out the list item with the values appropriate to the type
if($type == 'category') {
$html .= checkChildHtml($parentId, '<li class="' . implode(' ', $classes) . '">' . ($parent ? '<button class="toggle"></button>' : null) . '' . $child->getName() . '');
}
else {
$html .= checkChildHtml($parentId, '<li class="' . implode(' ', $classes) . '">' . ($parent ? '<button class="toggle"></button>' : null) . '' . $child->title . '');
}
// Append the list html (if not root page)
if($parent) {
// Get the categories below this page
$html .= buildChildMenu($type, $currentID, $child->getId(), true, $parentIDs, $rootID);
}
// Close the list (if not root product page)
$html .= checkChildHtml($parentId, '</li>');
}
$html .= checkChildHtml($parentId, '</ul>');
return $html;
}
// Build out menu from root level down
$categoryListHtml = buildChildMenu($type, $currentID, $rootID, false, $parentIDs, $rootID);
Are there any obvious bottlenecks here? If not, what is best practise in this scenario?
For instance, should I AJAX the children when requested? Or maybe cache the menu? Or... something else?
Okay, the issue was that I had my cache turned off whilst I was developing this menu. With the cache enabled the processing time is insignificant.
I am using codeigniter. I need to get all variables from a language file to an array.Is it possible?
Is there any method available like as follows?
$a = $this->load->language('editor');
print_r($a);
I was tried $this->lang->language; But,This will return labels from another language files loaded.
$CI = & get_instance();
$arr = $CI->lang->language;
Or Use following library
Class My_language {
var $language = array();
/**
* List of loaded language files
*
* #var array
*/
var $is_loaded = array();
function __construct() {
log_message('debug', "Language Class Initialized");
}
function load($langfile = '', $idiom = '', $return = FALSE, $add_suffix = TRUE, $alt_path = '') {
$langfile = str_replace('.php', '', $langfile);
if ($add_suffix == TRUE) {
$langfile = str_replace('_lang.', '', $langfile) . '_lang';
}
$langfile .= '.php';
if (in_array($langfile, $this->is_loaded, TRUE)) {
return;
}
$config = & get_config();
if ($idiom == '') {
$deft_lang = (!isset($config['language'])) ? 'english' : $config['language'];
$idiom = ($deft_lang == '') ? 'english' : $deft_lang;
}
// Determine where the language file is and load it
if ($alt_path != '' && file_exists($alt_path . 'language/' . $idiom . '/' . $langfile)) {
include($alt_path . 'language/' . $idiom . '/' . $langfile);
} else {
$found = FALSE;
foreach (get_instance()->load->get_package_paths(TRUE) as $package_path) {
if (file_exists($package_path . 'language/' . $idiom . '/' . $langfile)) {
include($package_path . 'language/' . $idiom . '/' . $langfile);
$found = TRUE;
break;
}
}
if ($found !== TRUE) {
show_error('Unable to load the requested language file: language/' . $idiom . '/' . $langfile);
}
}
if (!isset($lang)) {
log_message('error', 'Language file contains no data: language/' . $idiom . '/' . $langfile);
return;
}
if ($return == TRUE) {
return $lang;
}
$this->is_loaded[] = $langfile;
$this->language = array();
$this->language = $lang;
return $this->language;
unset($lang);
log_message('debug', 'Language file loaded: language/' . $idiom . '/' . $langfile);
return TRUE;
}
}
Call like this
$this->load->library('my_language');
$arr = $this->my_language->load('demo');
print_r($arr);
I know this is quite an old question, but I just want to give my solution for this problem since no answers has done the trick for this problem. (tested on codeigniter 3)
$this->load->helper('language');
$foo = $this->lang->load('lang_file', 'english', true);
print_r($foo);
notice that the third parameter for load method determines whether to return the loaded array of translations. source: codeigniter 3 docs.
hope this helps
Yeah ofcourse its possible. You can do like this :
//load helper for language
$this->load->helper('language');
//test is the language file in english folder
$this->lang->load('test','english');
//fetch all the data in $var variable
$var=$this->lang->language;
//print $var
print_r($var);
$var will return the array. :)
If you want to return language file data in Array than you need to pass the third parameter in load function.
$this->lang->load('header','hindi',true) // filename,language,true
I'm trying to implement a function to be able to add directional (up / down) icons next to each of the table headers for a pagination table within CakePHP.
My current code is as follows:
$sort_key = $this->Paginator->sortKey();
$type = $this->Paginator->sortDir() === 'asc' ? 'up' : 'down';
function sortArrows($key, $title, $sort_key, $type)
{
$type_opposite = ($type === 'asc' ? 'down' : 'up');
if($key == $sort_key)
{
$icon = " <i class='fa fa-angle-" . $type . "'></i>";
}
else
{
$icon = " <i class='fa fa-angle-" . $type_opposite . "'></i>";
}
return "'$key', '$title' " . "$icon";
}
Which I am calling on the page as (on each of the table header fields):
<?php echo $this->Paginator->sort(sortArrows('street_suburb', 'Suburb', $sort_key, $type), array('escape' => false)); ?>
This produces the following error:
Notice (8): Array to string conversion [CORE/Cake/View/Helper/HtmlHelper.php, line 372]
I think I am quite close to what I need, I just cannot figure out what I am returning incorrectly from the function to get this to work.
Thanks
Inspired by your solution I have created a Helper extending PaginatorHelper to solve the problem.
Here is the code of file name MyPaginatorHelper.php:
<?php
namespace App\View\Helper;
use Cake\View\Helper\PaginatorHelper;
use Cake\Utility\Inflector;
class MyPaginatorHelper extends PaginatorHelper
{
public function sort($key, $title = null, array $options = [])
{
if (empty($title)) {
$title = $key;
if (strpos($title, '.') !== false) {
$title = str_replace('.', ' ', $title);
}
$title = __(Inflector::humanize(preg_replace('/_id$/', '', $title)));
}
$sortKey = $this->sortKey();
if (strpos($sortKey, '.') !== false) {
$sortKey = substr($sortKey, strpos($sortKey, '.')+1);
}
$sortDir = $this->sortDir() === 'asc' ? 'up' : 'down';
if($key == $sortKey)
{
$title .= " <i class='fa fa-angle-" . $sortDir . "'></i>";
$options['escape'] = false;
}
return parent::sort($key, $title, $options);
}
}
To use this helper you have to add this line in the AppView::initialize() method:
$this->loadHelper('Paginator', ['className' => 'MyPaginator']);
And then all the Paginator->sort() calls will have this feature by default.
I ended up coming up with a solution however I don't know if it is the best way around it. It does work however.
<?php
$sort_key = $this->Paginator->sortKey();
$type = $this->Paginator->sortDir() === 'asc' ? 'up' : 'down';
function sortArrows($key, $title, $sort_key, $type)
{
if($key == $sort_key)
{
$icon = " <i class='fa fa-angle-" . $type . "'></i>";
return $title . " " . $icon;
}
else
{
return $title;
}
}
?>
Called like:
<?php echo $this->Paginator->sort('street_suburb', sortArrows('street_suburb', 'Suburb', $sort_key, $type), array('escape' => false)); ?>
I am running with some weird situation with Switch Case statement in PHP, where it is somehow ignoring the case and throwing default value. However this is not limited to the Switch Case only and happening with if else as well. So might be something wrong I am doing apart from conditional check.
I am using codeingiter and below I am posting all my code and helpers. I hope this would be enough information but let me know if you need any more information.
Helpers
// get employees
function get_employees(array $array = array())
{
$CI = get_instance();
return $CI->db->get_where('employees', $array)->result();
}
// get employee status from the `employment_status`
function get_employee_status($id)
{
$result = get_employees(array('id' => $id));
foreach ($result as $employee)
{
$status = $employee->employment_status;
}
return ($status !== '') ? $status : 'none';
}
// get employee status icon (based on status)
function get_employee_status_icon($id, $tooltip = TRUE)
{
$status = get_employee_status($id);
$get_icon = ($tooltip) ? 'rel="tooltip" title="' . ucwords(str_replace('_', ' ', $status)) . '"' : NULL;
switch ($status)
{
case 'active':
$status_icon = '<span class="glyphicon glyphicon-ok" ' . $get_icon . '></span>';
break;
case 'at_risK':
$status_icon = '<span class="glyphicon glyphicon-warning-sign" ' . $get_icon . '></span>';
break;
case 'attrition':
$status_icon = '<span class="glyphicon glyphicon-ban-circle" ' . $get_icon . '></span>';
break;
default:
$status_icon = '<span class="glyphicon glyphicon-exclamation-sign" ' . $get_icon . '></span>';
break;
}
return $status_icon;
}
Controller
public function employees()
{
$this->data['title'] = '<i class="fa fa-users"></i> ' . lang('emp_all');
$base_url = base_url() . 'admin/hr/employees';
$numbs = $this->employees_model->filter_count();
$total_rows = $numbs['count'];
$limit = get_option('per_page');
$page = ($this->uri->segment(4) !== FALSE) ? (int) $this->uri->segment(4) : 0;
get_pagination($base_url, $total_rows, $limit, 4, 2, TRUE);
$this->data['results'] = $this->employees_model->fetch_rows($limit, $page);
$this->data['links'] = $this->pagination->create_links();
$this->load->view('hr/employees/index', $this->data);
}
View file
// view file
foreach ($results as $employee):
do_print(get_employee_status($employee->id) . ' - ' .get_employee_status_icon($employee->id));
echo '<tr>';
...
echo '<td class="status-' . get_employee_status($employee->id) . '">' . get_employee_status_icon($employee->id) . '</td>';
...
echo '</tr>';
endforeach;
To clear things again: the code outputs the default value (icon) for the last case. It is ignoring the last case just only for the ICON and not for the tooltip or even th class
So how can I fix this where I can get output same as the case everywhere?
EDIT: --- Added output images and var_dump image
Please see the second last var_dump and output result to match the at_risk icon. Which is wrong
HTML Output
var_dump()
First of all you should correct your this function by properly initializing $status variable;
// get employee status from the `employment_status`
function get_employee_status($id)
{
$result = get_employees(array('id' => $id));
$status = '';
foreach ($result as $employee)
{
$status = $employee->employment_status;
}
return ($status !== '') ? $status : 'none';
}
Now, you should do var_dump of $status and see what you find in status variable value.
Warning: Please contact support about failure in /public_html/install/index.php on line 1295
Fatal error: Function name must be a string in /public_html/install/index.php on line 1296
Okay so I did bad at explaining the whole thing. So Basically I'm trying to install Boonex Dolphin 7.0.6 (Social Networking CMS) on my Web site. I installed all the files correctly. I went to the install page. Went to the second page where I had to make all the files Writable. Once I made all the files Writable I went on to the next page called "Paths". And this is where it gave me the error above. The file has over 1483 Lines. Here is the Code Below.
Where it says $func = create_function("", $funcbody); Thats Line 1295
Lines 1281 - 1350
function printInstallError($sText) {
$sRet = (strlen($sText)) ? '<div class="error">' . $sText . '</div>' : '';
return $sRet;
}
function createTable($arr) {
$ret = '';
$i = '';
foreach($arr as $key => $value) {
$sStyleAdd = (($i%2) == 0) ? 'background-color:#ede9e9;' : 'background-color:#fff;';
$def_exp_text = "";
if (strlen($value['def_exp'])) {
$funcbody = $value ['def_exp'];
$func = create_function("", $funcbody);
$def_exp = $func();
if (strlen($def_exp)) {
$def_exp_text = " <font color=green>found</font>";
$value['def'] = $def_exp;
} else {
$def_exp_text = " <font color=red>not found</font>";
}
}
$st_err = ($error_arr[$key] == 1) ? ' style="background-color:#FFDDDD;" ' : '';
$ret .= <<<EOF
<tr class="cont" style="{$sStyleAdd}">
<td>
<div>{$value['name']}</div>
<div>Description:</div>
<div>Example:</div>
</td>
<td>
<div><input {$st_err} size="30" name="{$key}" value="{$value['def']}" /> {$def_exp_text}</div>
<div>{$value['desc']}</div>
<div style="font-style:italic;">{$value['ex']}</div>
</td>
</tr>
EOF;
$i ++;
}
return $ret;
}
function rewriteFile($sCode, $sReplace, $sFile) {
$ret = '';
$fs = filesize($sFile);
$fp = fopen($sFile, 'r');
if ($fp) {
$fcontent = fread($fp, $fs);
$fcontent = str_replace($sCode, $sReplace, $fcontent);
fclose($fp);
$fp = fopen($sFile, 'w');
if ($fp) {
if (fputs($fp, $fcontent)) {
$ret .= true;
} else {
$ret .= false;
}
fclose ( $fp );
} else {
$ret .= false;
}
} else {
$ret .= false;
}
return $ret;
}
If you need more code please let me know so I can help also thanks for reading this ^_^ and re helping as well. I also tried what the last person said with the adding "$a" and ";" but it did not help. Just got me more errors.
What can be stored in $value['def_exp']?
As it is your create_function call is not returning a value. Or so it seems. I did a simple mock up to show an example:
$funcbody = 'hello';
$func = create_function('$a', 'return $a;');
$def_exp = $func($funcbody);
This works as expected. Depending on what is in $funcbody you either need to add a ; after it IE:
$func = create_function('$a', $funcbody . ';');
A return before it and ; after it:
$func = create_function('$a', 'return ' . $funcbody . ';');
Or pass it as a parameter as I did in the first example. Not sure which you require, as I do not know what is stored in the $value['def_exp'] but hopefully that gets you rolling.
create_function() is probably failing. try
var_dump( $func );
if its false, then that is why and you should look at $funcbody