Trying to run function _googleanalytics in controller ProcessingController, but getting an error:
unknown command
command:
./yii processing/_googleanalytics '2017-02-27' '2017-02-27'
controller path:
/console/controllers/
action
public function _googleanalytics($start, $finish) {...
controller
namespace console\controllers;
class ProcessingController extends Controller
{...
/console/config/main.php
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'controllerMap' => [
'fixture' => [
'class' => 'yii\console\controllers\FixtureController',
'namespace' => 'common\fixtures',
],
],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning','info'],
'exportInterval' => 1,
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['info'],
'exportInterval' => 1,
'logVars' => [],
'categories' => ['calls'],
'logFile' => '#app/runtime/logs/calls.log',
'maxFileSize' => 1024 * 2,
'maxLogFiles' => 20,
],
],
],
],
'modules'=>[
'user-management' => [
'class' => 'webvimark\modules\UserManagement\UserManagementModule',
'controllerNamespace'=>'vendor\webvimark\modules\UserManagement\controllers', // To prevent yii help from crashing
],
'googleanalytics' => [
'class' => 'console\modules\googleanalytics\Module',
]
],
'params' => $params,
];
what I am doing wrong?
You need to make an action to access it via console/terminal the same way as we access the actions via our browser.
For example if i create a Test Controller like below inside console/controllers directory
<?php
namespace console\controllers;
class TestController extends \yii\console\Controller{
public function actionIndex($param1,$param2){
echo "\nIndex";
echo "\n$param1 $param2\n";
}
public function actionMango(){
echo "\nMango";
}
}
and then type ./yii and hit Enter it will show all default commands available along with the following at the end.
This is Yii version 2.0.14.1.
The following commands are available:
....
...
- test
test/index (default)
test/mango
which means it registers all the actions inside the controller as commands and if you write in the terminal the following command,
./yii test/index omer aslam
it will show you the output
Index
omer aslam
where omer and aslam are the 2 params passed to the function.
So you just need to prepend keyword action to your function name i would suggest using action names according to the convention, change the function from
public function _googleanalytics($start, $finish) {
to
public function actionGoogleanalytics($start, $finish) {
and then access it via
./yii process/googleanalytics 2017-02-27 2017-02-27
you can wrap with quotes but it isnt necessary to add one a space identitifies between separate params.
Hope it helps
Related
i was trying to make
this url
http://localhost/advanced/frontend/web/index.php?r=test
into
htttp://localhost/advanced/frontend/web/tests in yii2
also to receive post request
this in my codding in common/config/main.php
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'urlManager' => [
],
'urlManagerFrontEnd' => [
'enablePrettyUrl' => true,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['test'],
'only' => ['index', 'create'],
],
],
'showScriptName' => false,
],
],
];
this in my frontend testController
namespace frontend\controllers;
use Yii;
use yii\rest\ActiveController;
use common\models\Test;
use yii\data\ActiveDataProvider;
class TestController extends ActiveController {
public $modelClass = 'common\models\Test';
public function actions(){
$actions = parent::actions();
unset($actions['create']);
return $actions;
}
public function actionCreate(){
$model = new Test();
$model->load(Yii::$app->request->post(),'');
$model->save();
return $model;
}
}
i have a problem in the post request when i tried
Postman result jpg
so i have 2 problem the first is the prettyUrl and the post request
if u have a solution please make it easy because i just learn php yii2 html css etc for 1 month
I am currently using the following lines of code on every controller in the API module in order to return JSON response/data.
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
return $behaviors;
}
It works well. But how can i achieve the same using main configuration file?
I tried the following on my frontend/config/main.php
'api' => [
'class' => 'app\modules\api\Module',
'components' => [
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'common\models\User',
'enableSession' => false,
'loginUrl' => null,
],
'response' => [
'class' => \yii\filters\ContentNegotiator::className(),
'formats' => [
'application/json' => \yii\web\Response::FORMAT_JSON,
],
]
],// Module component
],
above configuration still returns XML response only. What is the correct configuration to set all the controllers in the API module to return JSON data.Thanks
Configure your response component as follows:
'response' => [
'format' => yii\web\Response::FORMAT_JSON,
// ...
]
formats is an array containing the available formats. format is the actual output format.
Add this is your config/main-local.php
use yii\web\Response;
$config['bootstrap'][]=
[
'class' => '\yii\filters\ContentNegotiator',
'formats' => [
'text/html' => Response::FORMAT_JSON,
]
];
I'm in ZF3, using the zend-mvc-skeleton and trying to configure a generic route that will match as many URLs as possible as I want to be able to create new controllers (including action methods of course), and have them immediately available.
The common approach described in the documentation is to write a route that matches the controller and action (same with ZF2).
Here is my module.config.php
namespace Application;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return [
'router' => [
'routes' => [
'home' => [
'type' => Literal::class,
'options' => [
'route' => '/',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'default' => [
'type' => Segment::class,
'options' => [
'route' => '/application[/:controller[/:action]]',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
'constraints' => [
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
],
],
],
],
],
'controllers' => [/* ... */],
'view_manager' => [/* ... */],
],
It works like a charm for http://localhost/ and http://localhost/application calling the indexAction() function of the IndexController class inside the /module/Application/src/IndexController.php file.
However, it's not working when I try to get the fooAction() function in the same Controller (i.e. IndexController). It's not resolving correctly http://localhost/application/foo. and I get the following error:
A 404 error occurred
Page not found.
The requested controller could not be mapped to an existing controller class.
Controller:
foo (resolves to invalid controller class or alias: foo)
No Exception available
Same error if I try http://localhost/bar/foo to get the fooAction() in the barController.
Do you have any idea of what's wrong with this? Any help will be appreciated. Many thanks.
The route http://localhost/application/foo won't resolve to fooAction() in the index controller, since /foo in the URL will match the controller not the action. With that route setup you would need to visit http://localhost/application/index/foo.
To get it working you'll also need to make sure you have aliased your controller in the config, e.g. assuming you have:
'controllers' => [
'invokables' => [
'Application\Controller\Index' => \Application\Controller\IndexController::class
]
],
Then alias the controller so it matches the route parameter:
'controllers' => [
'invokables' => [
'Application\Controller\Index' => \Application\Controller\IndexController::class
],
'aliases' => [
'index' => 'Application\Controller\Index'
]
],
You'll need to add aliases that match the route parameter for each controller that isn't registered using the string you want for the route, e.g. a controller Namespace\Controller\BarController should be aliased to bar, etc.
I came here with similar problem. I have created two controllers in
"Application" module, and two in new module "Account" with the same name.
Application/Controller/IndexController
Application/Controller/OverviewController
Account/Controller/IndexController
Account/Controller/OverviewController
here are my modules.config.php
module/Account/config/module.config.php
return [
'router' => [
'routes' => [
'Account-account' => [
'type' => Segment::class,
'options' => [
'route' => '/account[/][:controller[/][:action][/]]',
'defaults' => [
'__NAMESPACE__' => 'Account\Controller',
'controller' => Account\Controller\IndexController::class,
'action' => 'index',
'locale' => 'en_us'
],
],
'may_terminate' => true,
'child_routes' => [
'wildcard' => [
'type' => 'Wildcard'
],
],
],
],
],
'controllers' => [
'factories' => [
Controller\IndexController::class => AccountControllerFactory::class,
Controller\OverviewController::class => AccountControllerFactory::class,
],
'aliases' => [
'index' => IndexController::class,
'overview' => OverviewController::class
]
],
and my
module/Application/config/module.config.php
return [
'router' => [
'routes' => [
'home' => [
'type' => Literal::class,
'options' => [
'route' => '/',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'Application-application' => [
'type' => Segment::class,
'options' => [
'route' => '/application[/][:controller[/][:action][/]]',
'defaults' => [
'__NAMESPACE__' => 'Application\Controller',
'controller' => Application\Controller\IndexController::class,
'action' => 'index',
'locale' => 'en_US'
],
],
'may_terminate' => true,
'child_routes' => [
'wildcard' => [
'type' => 'Wildcard'
],
],
],
],
],
'controllers' => [
'factories' => [
Controller\IndexController::class => IndexControllerFactory::class,
Controller\OverviewController::class => IndexControllerFactory::class,
],
'aliases' => [
'index' => IndexController::class,
'overview' => OverviewController::class,
]
],
With this configuration if aliases sections are commented there is a error message which says that there is invalid controller or alias (index/overview).
If there are aliases
route: "application/overview/index" goes into Account module.
Is there any way to apply a function to all requests and queries in Yii2?
I want to replace specific characters for all of them.
I am using Yii2 advanced app
Thanks.
This is the config file:
$config = [
'language' => 'en',
'components' => [
'request' => [
'cookieValidationKey' => 'something',
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
'defaultRoles' => ['guest'],
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
],
];
return $config;
Without extending custom code on each request can be exexuted like so (add this to your application config):
return [
'on beforeRequest' => function () {
if (!Yii::$app->get('user', false)) {
return;
}
$user = User::getCurrent();
if ($user) {
Yii::$app->setTimeZone($user->time_zone);
}
},
'on afterRequest' => function () {
...
},
];
Depending on when you need to execute code (before or after the request) use 'on beforeRequest' or 'on afterRequest' accordingly.
yii2 have a request component. You can extend yii\web\request and define your custom implementation.
[
...
'components' =>
'request' => [
'class' => '\common\MyRequest',
'addGeoLocationForExample' => true,
]
...
We've been working on a project with Yii2 Advanced App, with a custom bootstrap template. I've generated the crud using gii. All other CRUDs work fine. But the User crud displays Yii2 User Module not the CRUD.
I've gone through amnah's complete documentations and couldn't find any solutions in any other places either. I even tried Yii2 documentations and it wasn't any help either.
This is my backend config
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '', (new Request)->getBaseUrl());
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'defaultRoute' => 'sahasa/index',
'bootstrap' => ['log'],
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],
'request' => [
'baseUrl' => $baseUrl,
],
'user' => [
'class' => 'amnah\yii2\user\components\User',
],
// 'user' => [
// 'identityClass' => 'common\models\User',
// 'enableAutoLogin' => true,
// ],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
'modules' => [
'user' => [
'class' => 'amnah\yii2\user\Module',
// set custom module properties here ...
],
'debug' => [
'class' => 'yii\debug\Module',
],
],
];
This is what I get when I goto localhost/app/backend/web/index.php?r=user
I want it to display a CRUD similar to this
I'm stuck there. Without the CRUD it'll be difficult to manage the USERS.
Any help is appreciated.
Thanks in advance.
I think you need to redefine the controller too. You need a new controller derived form the original controller for correctly addressing the new CRUD element.
I suppose your controller is in backend and is named user otherwise change properly the following example (part of config/main.php):
'user' => [
...
'controllerMap' => [
'user' => 'backend\controllers\user',
],
],
You can add this code to Controller in backend
public function init()
{
$user_id = Yii::$app->getUser()->id;
if($user_id){
$user = \amnah\yii2\user\models\User::findOne($user_id);
if ($user->can("admin")) {
// do something
}else{
throw new HttpException(403, 'You are not allowed to perform this action.');
}
}else{
throw new HttpException(403, 'You are not allowed to perform this action.');
}
parent::init();
}
Just click the link /user/admin
You'll get CRUD for users.