Codeigniter: call a function in View From Controller - php

I am New to Codeigniter. In my Sample Application I add a new Tab called "RegForm" in my Main.php(View Folder). When i Click the RegForm Tab it load the New Window(width='800px' height='500px'). i understand the concept but i dont know how to write coding in Codeigniter.
Basicall i call a function in Controller file when i Clicked the RegForm tab. and i need to call a function in View where i load a window with properties. amm i correct.

YOu could do this (if I understood correctly):
View 'someview' contains this link:
$atts = array(
'width' => '800',
'height' => '500',
'scrollbars' => 'yes',
'status' => 'yes',
'resizable' => 'yes',
);
echo anchor_popup('mycontroller/mymethod','Click this for a popup',$atts);
(anchor_popup is a funcion in the URL helper, just autoload it, it's really useful)
in Controller 'mycontroller':
class Mycontroller extends CI_Controller {
//function index()
// other functions
function mymethod()
{
$this->load->model('mymodelforthis');
$data['properties'] = $this->mymodelforthis->get_properties();
$this->load->view('myview',$data);
}
}
THen, in 'myview', you display $properties the way you want
Hope this helps, lmk

Related

PrestaShop 1.7 Add new resources and class

I created new resources with this code:
class WebserviceRequest extends WebserviceRequestCore {
public static function getResources(){
$resources = parent::getResources();
// if you do not have class for your table
$resources['test'] = array('description' => 'Manage My API', 'specific_management' => true);
$resources['categoryecommerce'] = array('description' => 'o jacie marcin', 'class' => 'CategoryEcommerce');
$mp_resource = Hook::exec('addMobikulResources', array('resources' => $resources), null, true, false);
if (is_array($mp_resource) && count($mp_resource)) {
foreach ($mp_resource as $new_resources) {
if (is_array($new_resources) && count($new_resources)) {
$resources = array_merge($resources, $new_resources);
}
}
}
ksort($resources);
return $resources;
}
}
And new class:
class CategoryEcommerceCore extends ObjectModelCore {
public $category_id;
public $category_core_id;
public static $definition = array(
'table' => "category_ecommerce",
'primary' => 'category_id',
'fields' => array(
'category_core_id' => array('type' => self::TYPE_INT),
)
);
protected $webserviceParameters = array();
}
Webservice is override properly. My class WebserviceRequest is copying to
/override/classes/webservice/WebserviceRequest
but class isn't copying to /override/classes/ when i installing my module.
How to add new resourcess with own logic ? I want to add categories within relation to my table.
Regards
Martin
As soon as there is literally nothing regarding the API except Webkul tutorial... I tried to implement the "Webkul's" tutorial, but also failed. However seems that it's better to use hooks instead of overrides. I used my "reverse engineering skills" to determine the way to create that API, so-o-o-o, BEHOLD! :D
Let's assume you have a custom PrestaShop 1.7 module. Your file is mymodule.php and here are several steps.
This is an install method wich allows you to register the hook within database (you can uninstall and reinstall the module for this method to be executed):
public function install() {
parent::install();
$this->registerHook('addWebserviceResources');
return true;
}
Add the hook listener:
public function hookAddWebserviceResources($resources) {
$added_resources['test'] = [
'description' => 'Test',
'specific_management' => true,
];
return $added_resources;
}
That specific_management option shows you are going to use WebsiteSpecificManagement file instead of database model file.
Create WebsiteSpecificManagement file, called WebsiteSpecificManagementTest (Test - is CamelCased name of your endpoint). You can take the skeleton for this file from /classes/webservice/WebserviceSpecificManagementSearch.php. Remove everything except:
setObjectOutput
setWsObject
getWsObject
getObjectOutput
setUrlSegment
getUrlSegment
getContent (should return $this->output; and nothing more)
manage - you should rewrite it to return/process the data you want.
Add
include_once(_PS_MODULE_DIR_.'YOURMODULENAME/classes/WebserviceSpecificManagementTest.php');
to your module file (haven't figured out how to include automatically).
Go to /Backoffice/index.php?controller=AdminWebservice and setup the new "Auth" key for your application, selecting the test endpoint from the permissions list. Remember the key.
Visit /api/test?ws_key=YOUR_KEY_GENERATED_ON_STEP_4 and see the XML response.
Add &output_format=JSON to your URL to see the response in JSON.
You have to use something like $this->output = json_encode(['blah' => 'world']) within manage method at WebsiteSpecificManagementTest.

Concrete5 import JS or CSS in single page

I've been checking this page out on their docs: http://documentation.concrete5.org/developers/assets/requiring-an-asset
But none of the options are working out for me. No errors or anything. It just ignores the requireAsset method.
Controller:
<?php
namespace Application\Controller\SinglePage;
use PageController;
class MyAccount extends PageController
{
public function view()
{
$this->requireAsset('javascript', 'js/my_account');
}
}
Managed to finally find how to do it properly, after much digging. Here's how...
application/config/app.php:
<?php
return array(
'assets' => array(
'foobar/my-account' => array(
array(
'javascript',
'js/my_account.js'
),
),
),
);
Controller:
<?php
namespace Application\Controller\SinglePage;
use PageController;
class MyAccount extends PageController
{
public function view()
{
$this->requireAsset('javascript', 'foobar/my-account');
}
}
the way you did it works but it's not very handy and doesn't make use of all the options.
The problem came from the fact that you were requiring an asset in your controller that you had never really declared in the first place.
Now it is declared in your app.php but it doesn't have to be. You can do it in the controller as well which will make things easier to maintain.
<?php
namespace Application\Controller\SinglePage;
use PageController;
use AssetList;
use Asset;
class MyAccount extends PageController
{
public function view()
{
$al = AssetList::getInstance();
// Register (declare) a javascript script. here I called it foobar/my-script which is the reference used to request it
$al->register(
'javascript', 'foobar/my-script', 'js/my_account.js', array('version' => '1.0', 'position' => Asset::ASSET_POSITION_FOOTER, 'minify' => true, 'combine' => true)
);
// Register (declare) a css stylesheet. here I called it foobar/my-stylesheet which is the reference used to request it
$al->register(
'css', 'foobar/my-stylesheet', 'css/my_account.css', array('version' => '1.0', 'position' => Asset::ASSET_POSITION_HEADER, 'minify' => true, 'combine' => true)
);
// Gather all the assets declared above in an array so you can request them all at once if needed
$assets = array(
array('css', 'foobar/my-stylesheet'),
array('javascript', 'foobar/my-script')
);
// Register the asset group that includes all your assets (or a subset as you like). here I called it foobar/my-account which is the reference used to request it
$al->registerGroup('foobar/my-account', $assets);
// require the group so all the assets are loaded together
$this->requireAsset('foobar/my-account');
// Alternatively you can call only one of them
// $this->requireAsset('javascript', 'foobar/my-script');
}
}

Owncloud + Hooks

I am trying to add some Hooks to my OwnCloud app called Metadata, and i can't seem to figure it out (the hook is not being fired).
I tried following the content https://doc.owncloud.org/server/8.2/developer_manual/app/init.html and https://doc.owncloud.org/server/8.2/developer_manual/app/hooks.html (although it seems like the second one is outdated).
Basically all i am trying to do for now is the catch the pre-rename hook and write something to a file.
My code is :
myapp/appinfo/app.php
namespace OCA\Metadata\AppInfo;
use OCP\AppFramework\App;
$app = new App('metadata');
$container = $app->getContainer();
$container->query('OCP\INavigationManager')->add(function () use ($container) {
$urlGenerator = $container->query('OCP\IURLGenerator');
$l10n = $container->query('OCP\IL10N');
return [
// the string under which your app will be referenced in owncloud
'id' => 'metadata',
// sorting weight for the navigation. The higher the number, the higher
// will it be listed in the navigation
'order' => 10,
// the route that will be shown on startup
'href' => $urlGenerator->linkToRoute('metadata.page.index'),
// the icon that will be shown in the navigation
// this file needs to exist in img/
'icon' => $urlGenerator->imagePath('metadata', 'app.svg'),
// the title of your application. This will be used in the
// navigation or on the settings page of your app
'name' => $l10n->t('Metadata'),
];
});
\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Metadata\Hooks', 'postRename');
and then myapp/hooks.php
<?php
namespace OCA\Metadata;
use OC\Files\Filesystem;
use OC\Files\View;
class Hooks {
// private $userManager;
public static function postRename($params) {
file_put_contents("/var/www/data/owncloud_print2.log", "post_rename");
}
}
nothing ever gets written to the file. i have also tried other approaches all with no luck. anyone knows what i am doing wrong??
my connecthook was wrong. it should be:
\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Metadata\Hooks', 'postRename');

Zend Framework 2: Navigation

In my controller I create the Navigation object and passing it to the view
$navigation = new \Zend\Navigation\Navigation(array(
array(
'label' => 'Album',
'controller' => 'album',
'action' => 'index',
'route' => 'album',
),
));
There trying to use it
<?php echo $this->navigation($this->navigation)->menu() ?>
And get the error:
Fatal error: Zend\Navigation\Exception\DomainException: Zend\Navigation\Page\Mvc::getHref cannot execute as no Zend\Mvc\Router\RouteStackInterface instance is composed in Zend\View\Helper\Navigation\AbstractHelper.php on line 471
But navigation which I use in layout, so as it is written here: http://adam.lundrigan.ca/2012/07/quick-and-dirty-zf2-zend-navigation/ works. What is my mistake?
Thank you.
The problem is a missing Router (or to be more precise, a Zend\Mvc\Router\RouteStackInterface). A route stack is a collection of routes and can use a route name to turn that into an url. Basically it accepts a route name and creates an url for you:
$url = $routeStack->assemble('my/route');
This happens inside the MVC Pages of Zend\Navigation too. The page has a route parameter and when there is a router available, the page assembles it's own url (or in Zend\Navigation terms, an href). If you do not provide the router, it cannot assemble the route and thus throws an exception.
You must inject the router in every page of the navigation:
$navigation = new Navigation($config);
$router = $serviceLocator->get('router');
function injectRouter($navigation, $router) {
foreach ($navigation->getPages() as $page) {
if ($page instanceof MvcPage) {
$page->setRouter($router);
}
if ($page->hasPages()) {
injectRouter($page, $router);
}
}
}
As you see it is a recursive function, injecting the router into every page. Tedious! Therefore there is a factory to do this for you. There are four simple steps to make this happen.
STEP ONE
Put the navigation configuration in your module configuration first. Just as you have a default navigation, you can create a second one secondary.
'navigation' => array(
'secondary' => array(
'page-1' => array(
'label' => 'First page',
'route' => 'route-1'
),
'page-2' => array(
'label' => 'Second page',
'route' => 'route-2'
),
),
),
You have routes to your first page (route-1) and second page (route-2).
STEP TWO
A factory will convert this into a navigation object structure, you need to create a class for that first. Create a file SecondaryNavigationFactory.php in your MyModule/Navigation/Service directory.
namespace MyModule\Navigation\Service;
use Zend\Navigation\Service\DefaultNavigationFactory;
class SecondaryNavigationFactory extends DefaultNavigationFactory
{
protected function getName()
{
return 'secondary';
}
}
See I put the name secondary here, which is the same as your navigation key.
STEP THREE
You must register this factory to the service manager. Then the factory can do it's work and turn the configuration file into a Zend\Navigation object. You can do this in your module.config.php:
'service_manager' => array(
'factories' => array(
'secondary_navigation' => 'MyModule\Navigation\Service\SecondaryNavigationFactory'
),
)
See I made a service secondary_navigation here, where the factory will return a Zend\Navigation instance then. If you do now $sm->get('secondary_navigation') you will see that is a Zend\Navigation\Navigation object.
STEP FOUR
Tell the view helper to use this navigation and not the default one. The navigation view helper accepts a "navigation" parameter where you can state which navigation you want. In this case, the service manager has a service secondary_navigation and that is the one we need.
<?= $this->navigation('secondary_navigation')->menu() ?>
Now you will have the navigation secondary used in this view helper.
Disclosure: this answer is the same as I gave on this question: https://stackoverflow.com/a/12973806/434223
btw. you don't need to define controller and action if you define a route, only if your route is generic and controller/action are variable segments.
The problem is indeed that the routes can't be resolved without the router. I would expect the navigation class to solve that issue, but obviously you have to do it on your own. I just wrote a view helper to introduce the router with the MVC pages.
Here's how I use it within the view:
$navigation = $this->navigation();
$navigation->addPage(
array(
'route' => 'language',
'label' => 'language.list.nav'
)
);
$this->registerNavigationRouter($navigation);
echo $navigation->menu()->render();
The view helper:
<?php
namespace JarJar\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\View\Helper\Navigation;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Navigation\Page\Mvc;
class RegisterNavigationRouter extends AbstractHelper implements ServiceLocatorAwareInterface
{
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function __invoke(Navigation $navigation)
{
$router = $this->getRouter();
foreach ($navigation->getPages() as $page) {
if ($page instanceof Mvc) {
$page->setRouter($router);
}
}
}
protected function getRouter()
{
$router = $this->getServiceLocator()->getServiceLocator()->get('router');
return $router;
}
}
Don't forget to add the view helper in your config as invokable instance:
'view_helpers' => array(
'invokables' => array(
'registerNavigationRouter' => 'JarJar\View\Helper\RegisterNavigationRouter'
)
),
It's not a great solution, but it works.

Zend: Issues setting up editAction(), please advise

I am experiencing some difficulty setting up the functionality for an admin to edit an items values. I have created the editAction() function in the AdminItemController class. This is contained within a module called catalog. My routing is configured as the following:
resources.router.routes.admin-catalog-edit.route = "/admin/catalog/item/edit/:id"
resources.router.routes.admin-catalog-edit.defaults.module = "catalog"
resources.router.routes.admin-catalog-edit.defaults.controller = "admin.item"
resources.router.routes.admin-catalog-edit.defaults.action = "edit"
I have created a custom Zend_Form class and within this class I set the action and method for the form:
class My_Form_ItemAdd extends Zend_Form
{
public function init()
{
$this->setAction('/admin/catalog/item/edit')
->setMethod('post');
...
Within my controller action I have instantiated the form and pass it to the view to be rendered. I also test if it's a POST (if so validate and save to database), otherwise, test for GET (if so, extract ID and populate()):
class Catalog_AdminItemController extends Zend_Controller_Action
{
...
public function editAction()
{
$form = new My_Form_ItemEdit();
$this->view->form = $form;
...
The form loads just fine in the browser when I supply an ID at the end for GET request... however, when I submit the form an exception is thrown with the following request parameters:
array (
'controller' => 'admin',
'action' => 'catalog',
'item' => 'edit',
'module' => 'default',
...
I have no idea why the it would be doing this... is there something I'm not seeing??? Any advice would be much appreciated!
The problem lies in your route. The default behavior for /admin/catalog/item/edit/:id is to process it like /controller/action/:param/:param/:param which puts both item and edit as parameters instead of your intended purpose. Try adding something like this to your bootstrap:
protected function _initRoutes()
{
// Get front controller
$front = Zend_Controller_Front::getInstance();
// Get router
$router = $front->getRouter();
// Add route
$router->addRoute(
'admin_item_edit',
new Zend_Controller_Router_Route('admin/catalog/item/edit/:id',
array('controller' => 'item',
'action' => 'edit'))
);
}
This allows you to define the specific controller and action from the route.

Categories