PrestaShop: How to load a controller inside a controller? - php

How to load a control inside a controller prestashop?
Opencart support load controller inside the controller
$data['efgh'] = $this->load->controller('abcd/efgh');
So prestashop that support it? If yes then how?
i have a controller Category render custom tpl
public function renderList(){
$tpl = $this->createTemplate('dashboard.tpl');
// Category
$categories = GenCategory::getCategories();
$public_categories = GenCategory::getPublicCategories();
$unpublic_categories = GenCategory::getUnpublicCategories();
$tpl->assign(array(
// Category
'categories' => $categories,
'public_categories' => $public_categories,
'unpublic_categories' => $unpublic_categories,
));
return $tpl->fetch();
}
and controller Menu render custom tpl
public function renderList(){
$tpl = $this->createTemplate('menu.tpl');
$menu = GenMenu::getMenu();
$tpl->assign(array(
'menu' => $menu,
));
return $tpl->fetch();
}
I need show Menu inside Category.

I'll suggest you to use the initContent() method, and not the renderList, in this way:
public function initContent(){
// Category
$categories = GenCategory::getCategories();
$public_categories = GenCategory::getPublicCategories();
$unpublic_categories = GenCategory::getUnpublicCategories();
// Menu
$menu = $this->genMenu();
$this->context->smarty->assign(array(
// Category
'categories' => $categories,
'public_categories' => $public_categories,
'unpublic_categories' => $unpublic_categories,
// Menu
'menu' => $menu
))
$this->setTemplate(`rightdirectoryofyourtpl`.'dashboard.tpl');
}
public function genMenu(){
$menu = GenMenu::getMenu();
$this->context->smarty->assign(array(
'menu' => $menu,
));
return $this->context->smarty->fetch(`directoryofyourtpl`/menu.tpl)
}
Then in your tpl simply 'print' the $menu var

Related

How do i reference another page in <a href=""> in wordpress theme

I am converting a static an html code to wordpress theme, i want to open another page to open when i click on the anchor tag, how do i go about it. Thanks.
<li>About Us</li>
In WordPress, links are permalinks:
Permalinks are the permanent URLs to your individual weblog posts, as
well as categories and other lists of weblog postings.
Original link: https://wordpress.org/support/article/using-permalinks
When creating a theme, you must display the links that are available in the admin panel: Admin panel -> Appearance -> Menus
The menu consists of locations, location is the place in the template where the user menu is displayed
I created a mini plugin for you that allows you to create custom menus and display them anywhere
Plugin structure:
wp-content\plugins\unbywyd-custom-menus
wp-content\plugins\unbywyd-custom-menus\unbywyd-custom-menus.php
wp-content\plugins\unbywyd-custom-menus\templates
wp-content\plugins\unbywyd-custom-menus\templates\navbar.hbs
wp-content\plugins\unbywyd-custom-menus\partials
wp-content\plugins\unbywyd-custom-menus\partials\menu_item.hbs
wp-content\plugins\unbywyd-custom-menus\partials\handlebars
wp-content\plugins\unbywyd-custom-menus\partials\handlebars\{library: https://github.com/zordius/lightncandy}
My example will be complete and working so that you can create any custom menus in WordPress. I will use the handlebars template engine to make things easier.
And so the contents of the unbywyd-custom-menus.php file:
<?php
/*
Plugin Name: Unbywyd custom menus
Version: 0.1
Author: Unbywyd
Author URI: unbywyd.com
*/
/*
* We will use the Handlebars template engine
*/
if(!class_exists('LightnCandy\LightnCandy')) {
require_once ("handlebars/autoload.php");
}
use LightnCandy\LightnCandy;
define('UCMS_DIR', plugin_dir_path(__FILE__));
class unbywydCustomMenus {
public $menus = [];
function __construct($menus=array()) {
$this->menus = $menus;
add_action('init', array($this, 'init'));
/*
* Create use_custom_menu shortcode
* You can use [use_custom_menu location="navbar"] in wordpress posts to display navbar menu
* And also for using from php <php print do_shortcode('[use_custom_menu location="navbar" customparam="test" class="test"]'); ?>
*/
add_shortcode( 'use_custom_menu', array($this, 'use_custom_menu'));
}
function use_custom_menu($attrs) { // Create shortcode handler
if(!isset($attrs['location'])) {
$attrs['location'] = '';
}
return $this->get_nav($attrs['location'], $attrs);
}
function get_template( $template_name ) { // Get a template by its name from templates/ directory
$path_to_file = wp_normalize_path(UCMS_DIR . 'templates/' . $template_name . '.hbs');
if(!file_exists($path_to_file)) {
return '';
}
return file_get_contents($path_to_file);
}
function get_handlebars_partials() { // Get all partials from partials/ directory
$path_to_partials = wp_normalize_path(UCMS_DIR . 'partials/');
if(!file_exists($path_to_partials)) {
return array();
}
$list_files = scandir($path_to_partials);
$partials = array();
foreach($list_files as $path) {
$path_to_file = wp_normalize_path($path_to_partials . '/'. $path);
if(is_file($path_to_file)) {
$ext = pathinfo($path_to_file, PATHINFO_EXTENSION);
if($ext == 'hbs') {
$partials[pathinfo($path, PATHINFO_FILENAME)] = function($name, $context) use($path_to_file) {
return $this->prepare_template(file_get_contents($path_to_file))($context, array('partials' => $this->get_handlebars_partials()));
};
}
}
}
return $partials;
}
function get_handlebars_helpers() {
return array(
/*
* You can use debug helper to display the incoming data into the template
* {{{debug}}}
*/
'debug' => function($context, $options=array()) {
if(!current_user_can('editor') && !current_user_can('administrator')) {
return '';
}
return '<pre class="debug" dir="ltr" style="text-align:left !important;">'.json_encode($context['data']['root'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE).'</pre>';
}
);
}
// You can use this function to render any of your templates from /template directory
function template_render($template_name, $data) {
$prepared_template = $this->prepare_template($this->get_template( $template_name ));
$partials = $this->get_handlebars_partials();
return $prepared_template($data, array('partials' => $partials));
}
function prepare_template($template) {
$template = do_shortcode($template);
$prepared = LightnCandy::compile($template, array(
'flags' => LightnCandy::FLAG_HANDLEBARSJS | LightnCandy::FLAG_ADVARNAME | LightnCandy::FLAG_RUNTIMEPARTIAL | LightnCandy::FLAG_ERROR_SKIPPARTIAL,
'helpers' => $this->get_handlebars_helpers()
));
return LightnCandy::prepare($prepared);
}
function init() {
/*
* Registering custom menu locations
*/
foreach($this->menus as $menu) {
register_nav_menu($menu['id'], $menu['label']);
}
}
function build_tree(Array $data, $parent = 0) {
$tree = array();
foreach ($data as $d) {
if ($d['parent'] == $parent) {
$children = $this->build_tree($data, $d['id']);
if (!empty($children)) {
$d['children'] = $children;
}
$tree[] = $d;
}
}
return $tree;
}
// Get generated HTML of navigation
function get_nav( $location, $other_params=array() ) {
$menu_data = $this->get_nav_menu_items_by_location($location);
if(empty($menu_data)) {
return 'You can do nothing, or you can display a notification that there are no links in the menu';
} else {
return $this->template_render($location, array_merge($other_params, array('menu' => $menu_data)));
}
}
// Simple handler to build data of custom navigation
function get_nav_menu_items_by_location( $location, $args = [] ) {
$locations = get_nav_menu_locations();
if(!isset($locations[$location])) {
return array();
}
$object = wp_get_nav_menu_object( $locations[$location] );
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
$link = "https";
} else {
$link = "http";
}
$link .= "://";
$link .= $_SERVER['HTTP_HOST'];
$link .= $_SERVER['REQUEST_URI'];
if(!$object) {
return array();
}
$menu_items = wp_get_nav_menu_items( $object->name, $args );
if(!$menu_items) {
return array();
} else {
$menu = array();
foreach( $menu_items as $i) {
$data = array(
'url' => $i->url,
'id' => $i->ID,
'parent' => $i->menu_item_parent,
'title' => $i->title,
'active' => $i->url == $link || $i->url . '/' == $link,
'attr_title' => $i->attr_title,
'description' => $i->description,
'class' => implode(' ', $i->classes)
);
if(!empty($i->target)) {
$data['target'] = $i->target;
}
$menu[] = $data;
}
return $this->build_tree($menu);
}
return $menu_items;
}
}
/*
* Сreate our custom menus
* Of course, you can add this complexity and bring it up to the plugin settings and display it in the wordpress admin panel as option page.
*/
new unbywydCustomMenus(
[
['id' => 'navbar', 'label' => 'Navbar menu'],
['id' => 'footer', 'label'=> 'Menu in footer']
]);
First you call the plugin class and pass your custom menus to register them:
new unbywydCustomMenus(
[
['id' => 'navbar', 'label' => 'Navbar menu'],
['id' => 'footer', 'label'=> 'Menu in footer']
]);
Then you can customize the menus in the admin panel and add them to your locations
Admin panel -> Appearance -> Menus | Manage Locations
and now you can display your menu anywhere in the post using a shortcode:
[use_custom_menu location="navbar" customparam="test" class="test"]
You will also be able to display it programmatically using php:
<php print do_shortcode('[use_custom_menu location="navbar" customparam="test" class="test"]'); ?>
Link to GutHub with working plugin
You could just put in the static URL https://www.website.com/about but that will change if you move the about page into another folder. To keep this dynamic, you can use the wordpress function get_page_link() (if you have the page id) or get_permalink and get_page_by_path if you have the slug. The about page will need to be created in the database first so you can get these parameters.
Using page ID: (ex: page ID is 40)
<li>About Us</li>
Using slug: (ex: slug is 'about-us')
<li>About Us</li>
You can also get it using the page title, though this might change over time so I don't recommend it:
<li>About Us</li>
More information about retrieving links dynamically here: https://code.tutsplus.com/tutorials/why-you-shouldnt-code-urls-in-wordpress-themes-or-plugins--cms-23262

YIi PHP - Output array with a foreach loop

I'm trying to return a navigation menu using Yii PHP framework, but my controller is only outputting the first item in the array, here's my code. Note that this pattern isn't using the traditional MVC, the model i'm asking data for is being displayed site-wide, not directly to its's controller->view.
Model - get data;
//output pages for getPagesMenuItems() in base controller
public function getAllPages(){
$criteria = new CDbCriteria();
$criteria->condition = "visible = 1";
return Pages::model()->findAll($criteria);
}
Base controller in components
public $pagesMenuItems = array();
$this->pagesMenuItems = $this->getPagesMenuItems();
protected function getPagesMenuItems() {
//Non admin users - links to pages
if (Yii::app()->user->isGuest){
$rows = Pages::getAllPages();
foreach($rows as $row) {
return array(
//$row->id , $row->title , $row->guid , $row->visible
array('label' => $row->title, 'icon' => 'fa fa-times', 'url' => array('/admin/pages/view/id/' . $row->id)),
'---',
);
}
// return array();
}
else {}
}
And this is the view in the main.php
$this->widget('booster.widgets.TbMenu', array(
'items' => $this->pagesMenuItems,
'id' => 'pagesNav'
));
I know the issue is packaging the array in the foreach loop, as i've tested the output of the model and all data is correct
Can anyone see where i'm going wrong in my controller?
Thanks
change getPagesMenuItems function as below:
protected function getPagesMenuItems() {
//Non admin users - links to pages
$data = array();
if (Yii::app()->user->isGuest){
$rows = Pages::getAllPages();
foreach($rows as $row) {
$data[] = array('label' => $row->title, 'icon' => 'fa fa-times', 'url' => array('/admin/pages/view/id/' . $row->id));
}
}
else {}
return $data;
}

cakephp pagination with advance Filter

I am using cake php scroll pagination to paging products.
I am using group of check boxes in view part to set manual condition by user to paginate.
I used following code to set a condition after ajax request.
class SearchController extends AppController {
public $helpers = array('Html', 'Form', 'Session','Paginator','Js' => 'Jquery');
public $components = array('RequestHandler','Session','Cookie','Paginator');
public function index() {
$this->loadModel("Bangsworkinghrs");
$agetworkinghrs = $this->Bangsworkinghrs->getworkinghrs();
$this->set('agetworkinghrs', $agetworkinghrs);
$this->loadModel("Gig");
$options = array('Gig.subcategory' => 'Logo Design');
if(!empty($this->request->data['filter']['workinghrs'])) {
$options = array('Gig.subcategory' => 'Logo');
}
$this->Paginator->settings = $options;
$agetGigsItem = $this->Paginator->paginate('Gig', $options);
$this->set('agetGigsItem', $agetGigsItem);
}
}
via this code i am able to change condition of paging but server explodes only default 20 records next records is not exploding by server and there is no error message my cakephp version is 2.6.8
$('#filter').submit(); try submit form and remove ajax refresh data from your jquery part replace filter with your form name.
You are missing 'page' and 'limit' attribute of Cakephp default pagination.
In your options array you need to pass page number and no of records per page.
Something like this but in dynamic way.
$options = array('conditions' => array('Gig.subcategory' => 'Logo Design'),'page'=>2,'limit'=>20);
using action="get" in the form where $this->request->query['filter']['workinghrs'] data is come.
Coding:
public $paginate = array(
'limit' => 20
);
public function index()
{
$this->loadModel("Gig");
$options = array('Gig.subcategory' => 'Logo Design');
if(!empty($this->request->query['filter']['workinghrs'])) {
$options = array('Gig.subcategory' => 'Vector Design');
}
$this->Paginator->settings = $options;
$agetGigsItem = $this->Paginator->paginate('Gig', $options);
$this->set('agetGigsItem', $agetGigsItem);
}

Magento ProductController append categoryId to products

I am adding a mass action to add a category. I am most of the way there I only have one function left to figure out.
Clr\Categorymassaction\controllers\Adminhtml\Catalog\ProductController.php
class Clr_Categorymassaction_Adminhtml_Catalog_ProductController extends Mage_Adminhtml_Controller_Action
{
public function massCategoryAction()
{
$productIds = $this->getRequest()->getParam('product');
$cat = $this->getRequest()->getParam('Category');
if (!is_array($productIds)) {
$this->_getSession()->addError($this->__('Please select product(s).'));
$this->_redirect('*/*/index');
}
else {
$cat = $category['label']->getCategoryId();
foreach($productIds as $product) {
//Process $cat into categoryId append categoryId to $productId
$cat->setPostedProducts($product);
}
//Save product
$cat->save();
}
}
}
Clr\Categorymassaction\Model\Observer
class Clr_Categorymassaction_Model_Observer {
public function addCategoryMassAction(Varien_Event_Observer $observer)
{
$block = $observer ->getBlock();
if ($block instanceof Mage_Adminhtml_Block_Catalog_Product_Grid) {
$block->getMassactionBlock()->addItem('Clr_Categorymassaction', array(
'label' => Mage::helper('catalog')->__('Add to Category'),
'url' => $block->getUrl('*/*/massCategory', array('_current' => true)),
'additional'=> array(
'visibility' => array(
'name' =>'Category',
'class' =>'required-entry',
'label' =>Mage::helper('catalog')->__('Categories'),
'type' => 'select',
'values' => Mage::getModel('Categorymassaction/system_config_source_category')->toOptionArray(),
'renderer' => 'Categorymassaction/catalog_product_grid_render_category',
)
)
));
};
}
}
One last thing
class Clr_Categorymassaction_Model_System_Config_Source_Category
{
public function toOptionArray($addEmpty = true)
{
$options = array();
foreach ($this->load_tree() as $category) {
$options[$category['value']] = $category['label'];
}
return $options;
}
I am mostly in trouble here because I am refactoring, Flagbit_changeattributeset and Vuleticd_AdminGridCategoryFilter. I know what I need to do (at least I think I do) I just don't know how to finish this off. Thanks for your eyes and ears if you read it all.
UPDATE: The observer from Vuleticd_AdminGridCategoryFilter had this additional code
'filter_condition_callback' => array($this, 'filterCallback'),
)
)
));
};
}
public function filterCallback($collection, $column)
{
$value = $column->getFilter()->getValue();
$_category = Mage::getModel('catalog/category')->load($value);
$collection->addCategoryFilter($_category);
return $collection;
}
This was used to apply the filter to the grid. What I am trying to do is instead of using the dropdown to filter column fields; use the dropdown to trigger the ProductController to pass the selected items a new categoryid.
https://magento.stackexchange.com/questions/67234/productcontroller-for-mass-action Asked this question over at magento's stackexchange figured I would post the link here for posterity.

loading a view via function in controller

I am trying to get sizes chart as on of the tabs when product is selected in opencart. For this I have a model like below
class ModelCatalogSizes extends Model {
public function getSizes()
{
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "sizes ORDER BY id");
return $query->rows;
}
}
I have view as a template for the same which is just a html table with values as input radio options.
In my product controller class, I have a function like below
public function sizes()
{
$this->language->load('product/product');
$this->load->model('catalog/sizes');
$this->data['sizes'] = array();
$results = $this->model_catalog_sizes->getSizes();
foreach ($results as $result) {
$this->data['sizes'][] = array(
'type' => ucfirst($result['type']),
'coat' => $result['coat'],
'chest' => $result['chest'],
'cverarm' => $result['overarm'],
'waist' => $result['waist'],
'hip' => $result['hip'],
'inseam' => $result['inseam'],
'neck' => $result['neck'],
'sleeve' => $result['sleeve'],
'height' => $result['height'],
'weightLb' => $result['weightLb'],
'weightKg' => $result['weightKg'],
);
}
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/sizes.tpl')) {
$this->template = $this->config->get('config_template') . '/template/product/sizes.tpl';
} else {
$this->template = 'default/template/product/sizes.tpl';
}
$this->response->setOutput($this->render());
}
Now I am trying to directly load this view via the index function in the product controller class by saying $this->data['size'] = $this->sizes();
When I echo my $size in my product view, nothing comes up. I'd presume the whole view built in the function above should show up. Am I wrong (probability 99%)? can someone help me with directly publishing the view via function?
What you need to do is add the route for that as a child of the index() method's children
Open /catalog/controller/product/product.php and find this code at the bottom of the index() method
$this->children = array(
'common/column_left',
'common/column_right',
'common/content_top',
'common/content_bottom',
'common/footer',
'common/header'
);
and add your route, which would be 'product/product/sizes' for your sizes() method
$this->children = array(
'common/column_left',
'common/column_right',
'common/content_top',
'common/content_bottom',
'common/footer',
'common/header',
'product/product/sizes'
);
And then in your template, you just need to use <?php echo $sizes; ?> wherever you want it to go

Categories