Running a module controller in yii - php

I have just created a module named myfirstmodule using gii in yii and then just hit the URl in my browser like:
localhost/yii_learn/index.php?r=myfirstmodule
defaultcontroller will run and display the output. Now I created a new controller and view in the same module and just run by:
http://localhost/yii_learn/index.php?r=myfirstmodule/mycontroller/index
It's redirecting me to home page of project.
Below is the code:
mycontroller.php
class mycontroller {
//put your code here
public function actionIndex(){
$this->render('myfirst');
}
And my view file code is
<?php
$this->breadcrumbs=array(
$this->module->id,
);
?>
<h1><?php echo $this->uniqueId . '/' . $this->action->id; ?></h1>
<p>
This is the view content for action "<?php echo $this->action->id; ?>".
The action belongs to the controller "<?php echo get_class($this); ?>"
in the "<?php echo $this->module->id; ?>" module.
</p>
<p>
You may customize this page by editing <tt><?php echo __FILE__; ?></tt>
</p>
Main.php file code
<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'My Web Application',
// preloading 'log' component
'preload'=>array('log'),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
),
'modules'=>array('testmodule','CustomerOnBoarding',
'myfirstmodule'=>array(),
// 'myfirstmodule'=>array(
// 'class'=>'\myfirstmodule\DefaultController',
// ),
// uncomment the following to enable the Gii tool
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>false,
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
),
// application components
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
// uncomment the following to enable URLs in path-format
// 'urlManager'=>array(
// 'caseSensitive' => true,
// 'urlSuffix' => '/',
// 'showScriptName' => false,
//
// 'urlFormat'=>'path',
'rules'=>array('myfirstmodule'=>'myfirstmodule/mycontroller/index',
// '<controller:\w+>/<id:\d+>'=>'<controller>/view','<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
// database settings are configured in database.php
'db'=>require(dirname(__FILE__).'/database.php'),
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
// array(
// 'class'=>'CWebLogRoute',
// ),
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'webmaster#example.com',
),
);
Can anyone help me in this, that how can I run my controller and view .

The format of the url is http://localhost/yii_learn/index.php?r=controllername/functionname. If you want to access a function through url, it should be prefixed with action. For example a function actionSampleFunction() in testcontroller can be accessed by http://localhost/yii_learn/index.php?r=testcontroller/samplefunction.

Have you try via access rules for this action
like. Simply add this to your controller and try.
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index'),
'users'=>array('*'),
),
);
}
if worked let me know.

Related

Typo3 extension "plugin can not be determined" exception [duplicate]

I built an extension and I would like to add plugin options at the time of adding the plugin to the page
Extension Name : hotels
in Hotel model ,
<?php
class Hotel{
... get set methods ...
}
?>
in HotelController.php
<?php
namespace TYPO3\Hotels\Controller;
class HotelController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController{
public function listAction(){
// $this->view->assign('result', array('test' => 'hello, u r in list')); }
}
?>
in ext_localconf.php
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'TYPO3.' . $_EXTKEY,
'hotels',
array('Hotel' => 'list,single,display,update,save,preview,edit')
);
in ext_tables.php
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerPlugin(
$_EXTKEY,
'hotels',
'list of Hotels'
);
$pluginSignature = str_replace('_','',$_EXTKEY) . '_hotels';
$TCA['tt_content']['types']['list']['subtypes_addlist'][$pluginSignature] ='pi_flexform';
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPiFlexFormValue($pluginSignature, 'FILE:EXT:' . $_EXTKEY . '/Configuration/FlexForms/flexform_myhotel.xml');
Somehow, I think i'm missing something. This gives an error :
I can see the option in backend side at time of adding extension but when i want to show (view) that Page where I add that extension , generates an error .
----> The default controller for extension "Hotels" and plugin "hotels" can not be determined. Please check for TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin() in your ext_localconf.php.
Please Guide me
In TYPO3 6.x, you are advised to use namespaced classes and tell the configurePlugin method your vendor name.
As you didnt include any of your controller code, I'll try to sketch it:
At first, make sure, you use a namespaced controller class-remember to set a Vendor name.
Make sure, your actions are named with the *Action suffix
EXT: myext/Classes/Controller/HotelController
namespace MyVendor\MyExt\Controller;
class HotelController {
/**
* #return void
*/
public function listAction(){
}
}
Next, mention the namespace in configurePlugin like this:
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'MyVendor.' . $_EXTKEY,
// UpperCamelCase please, refer to [1]
'Hotels',
array('Hotel' => 'list,single,display,update,save,preview,edit')
);
This allows the class locator to resolve the classes correctly.
To verify it, make sure you re-install your extension.
PS: Please use the namespaced classes whenever possible in 6.x. The old Tx_* classes are only aliases and put additional load on your interpreter.
1 - TYPO3 API Docs for ExtensionUtility::configurePlugin()
Update:
There is a multitude of possible errors.
You wired a FlexForm. Did you set the switchableControllerActions appropriately?
One thing I saw more than once: The f:link.action (or f:uri.action respectively) doesnt like to be without an appropriate controller attribute
You clearly missed the namespace concept :) Rename your ControllerClass to HotelController and the file must live in Classes/Controller/HotelController.php, then do the adjustments to configurePlugin() to reflect the vendorName as I described
Try it.
in ext_localconf.php
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'TYPO3.' . $_EXTKEY,
'hotels',
array(
'Hotel' => 'list,single,display,update,save,preview,edit'
),
// non-cacheable actions
array(
'Hotel' => 'list',
)
);
in ext_tables.php
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerPlugin(
$_EXTKEY,
'hotels',
'list of Hotels'
);
$extensionName = \TYPO3\CMS\Core\Utility\GeneralUtility::underscoredToUpperCamelCase($_EXTKEY);
$pluginSignature = strtolower($extensionName). '_hotels';
if (TYPO3_MODE === 'BE') {
/**
* Registers a Backend Module
*/
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerModule(
'TYPO3.' . $_EXTKEY,
'web', // Make module a submodule of 'web'
'hotels', // Submodule key
'', // Position
array(
'Hotel' => 'list,single,display,update,save,preview,edit'
),
array(
'access' => 'user,group',
'icon' => 'EXT:' . $_EXTKEY . '/ext_icon.gif',
'labels' => 'LLL:EXT:' . $_EXTKEY . '/Resources/Private/Language/locallang_hotels.xlf',
)
);
}
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile($_EXTKEY, 'Configuration/TypoScript', 'Hotels List');
#Clear cache and remove typo3temp data

FileNameController cannot find the requested view "create" in Yii 1

I have upload a new form in an existing webapp which is live (Linux server). But I am not able to set the route properly and get error.
Files :
1. view/newform/(create,index,view,_view,_form).php
controllers/NewFormController.php
models/NewForm.php
main.php :
'urlManager' => array(
'showScriptName' => false,
'urlFormat' => 'path',
'rules' => array(
'/' => 'site/index',
'newform' => 'newform/create', /*This rule is for new form */
**********************************
Link I use to access the wbepage online :
websitename.com/newform/create or create.php (I get 404 not found)
websitename.com/NewForm/create or create.php (NewFormController cannot find the requested view "create" error )
I can view it properly on localhost(windows) =>
localhost/public_html/index.php?r=newform/create
Questions :
What link should I use to view it online ?
How to get correct Route to the form I created ?
Edited :
I can view the index page after adding the path (/newform/index) in actionIndex(). controller
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('NewForm');
$this->render('/newform/index',array(
'dataProvider'=>$dataProvider,
));
}
Here is the create function :
When I use this the error I get : cannot find the requested view "_form"
public function actionCreate()
{
$model=new NewForm;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['NewForm']))
{
$model->attributes=$_POST['NewForm'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('/newform/create',array(
'model'=>$model,
));
}
Found It :P
$this->render('/newform/_form',array(
'model'=>$model,
));
in crontroller

How Do I disable the "gii" code generator for non admin user?

I am using Yii 1.13 framework for my project, I need "gii" code generator but I want to restrict it for admin user only, How can I achieve this ?
Follow the below steps:-
Copy the gii module from system.gii i.e framework/gii
Paste it inside the protected/modules folder of project.
Make the following changes in the GiiModule.php in your gii module.
Change this
public function beforeControllerAction($controller, $action)
{
if(parent::beforeControllerAction($controller, $action))
{
$route=$controller->id.'/'.$action->id;
if(!$this->allowIp(Yii::app()->request->userHostAddress) && $route!=='default/error')
throw new CHttpException(403,"You are not allowed to access this page.");
$publicPages=array(
'default/login',
'default/error',
);
if(Yii::app()->user->isGuest && !in_array($route,$publicPages))
Yii::app()->user->loginRequired();
// check your admin conditions here
elseif(!isset(Yii::app()->user->isAdmin) || !Yii::app()->user->isAdmin)
throw new CHttpException(403,"You are not allowed to access this page.");
else
return true;
}
return false;
}
In your config/main.php
'modules' =>
array(
'gii'=>array(
'class'=>'application.modules.gii.GiiModule',
'password'=> Your password,
'ipFilters'=>array('127.0.0.1','::1'),
),
),
Note:- I haven't tested it. But it might give you an idea about how to proceed.
You can restrict user by IP or choose a password for Gii tool according to it's documentation
return array(
......
'modules'=>array(
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'pick up a password here',
// 'ipFilters'=>array(...a list of IPs...),
),
),
);

The default controller for extension and plugin can not be determined ERROR in TYPO3

I built an extension and I would like to add plugin options at the time of adding the plugin to the page
Extension Name : hotels
in Hotel model ,
<?php
class Hotel{
... get set methods ...
}
?>
in HotelController.php
<?php
namespace TYPO3\Hotels\Controller;
class HotelController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController{
public function listAction(){
// $this->view->assign('result', array('test' => 'hello, u r in list')); }
}
?>
in ext_localconf.php
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'TYPO3.' . $_EXTKEY,
'hotels',
array('Hotel' => 'list,single,display,update,save,preview,edit')
);
in ext_tables.php
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerPlugin(
$_EXTKEY,
'hotels',
'list of Hotels'
);
$pluginSignature = str_replace('_','',$_EXTKEY) . '_hotels';
$TCA['tt_content']['types']['list']['subtypes_addlist'][$pluginSignature] ='pi_flexform';
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPiFlexFormValue($pluginSignature, 'FILE:EXT:' . $_EXTKEY . '/Configuration/FlexForms/flexform_myhotel.xml');
Somehow, I think i'm missing something. This gives an error :
I can see the option in backend side at time of adding extension but when i want to show (view) that Page where I add that extension , generates an error .
----> The default controller for extension "Hotels" and plugin "hotels" can not be determined. Please check for TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin() in your ext_localconf.php.
Please Guide me
In TYPO3 6.x, you are advised to use namespaced classes and tell the configurePlugin method your vendor name.
As you didnt include any of your controller code, I'll try to sketch it:
At first, make sure, you use a namespaced controller class-remember to set a Vendor name.
Make sure, your actions are named with the *Action suffix
EXT: myext/Classes/Controller/HotelController
namespace MyVendor\MyExt\Controller;
class HotelController {
/**
* #return void
*/
public function listAction(){
}
}
Next, mention the namespace in configurePlugin like this:
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'MyVendor.' . $_EXTKEY,
// UpperCamelCase please, refer to [1]
'Hotels',
array('Hotel' => 'list,single,display,update,save,preview,edit')
);
This allows the class locator to resolve the classes correctly.
To verify it, make sure you re-install your extension.
PS: Please use the namespaced classes whenever possible in 6.x. The old Tx_* classes are only aliases and put additional load on your interpreter.
1 - TYPO3 API Docs for ExtensionUtility::configurePlugin()
Update:
There is a multitude of possible errors.
You wired a FlexForm. Did you set the switchableControllerActions appropriately?
One thing I saw more than once: The f:link.action (or f:uri.action respectively) doesnt like to be without an appropriate controller attribute
You clearly missed the namespace concept :) Rename your ControllerClass to HotelController and the file must live in Classes/Controller/HotelController.php, then do the adjustments to configurePlugin() to reflect the vendorName as I described
Try it.
in ext_localconf.php
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'TYPO3.' . $_EXTKEY,
'hotels',
array(
'Hotel' => 'list,single,display,update,save,preview,edit'
),
// non-cacheable actions
array(
'Hotel' => 'list',
)
);
in ext_tables.php
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerPlugin(
$_EXTKEY,
'hotels',
'list of Hotels'
);
$extensionName = \TYPO3\CMS\Core\Utility\GeneralUtility::underscoredToUpperCamelCase($_EXTKEY);
$pluginSignature = strtolower($extensionName). '_hotels';
if (TYPO3_MODE === 'BE') {
/**
* Registers a Backend Module
*/
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerModule(
'TYPO3.' . $_EXTKEY,
'web', // Make module a submodule of 'web'
'hotels', // Submodule key
'', // Position
array(
'Hotel' => 'list,single,display,update,save,preview,edit'
),
array(
'access' => 'user,group',
'icon' => 'EXT:' . $_EXTKEY . '/ext_icon.gif',
'labels' => 'LLL:EXT:' . $_EXTKEY . '/Resources/Private/Language/locallang_hotels.xlf',
)
);
}
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile($_EXTKEY, 'Configuration/TypoScript', 'Hotels List');
#Clear cache and remove typo3temp data

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.

Categories