Route in Yii2 doesn't work - php

I cant to make request to my controller in Yii2
I have controller /controllers/IndexController.php
class IndexController extends Controller
{
public function actionIndex()
{
return $this->render('index');
}
public function actionCreateAccount()
{
return Json::encode(array('status'=>'ok'));
}
}
In my config/web.php
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false
],
When I try to make request http://account.ll/Index/CreateAccount
I receive an error
Unable to resolve the request "Index/CreateAccount".
When I try to make request http://account.ll/Index I got the same error
Whats wrong?

It should be:
http://account.li/index/index or just http://account.li/index (because index is the default action). If the default controller is IndexController, you can access it like that - http://account.li/.
http://account.li/index/create-account
Controller and action names in actual url should be in lowercase. Action names containing more than one word are transformed with hyphens in between words.

Try to change
public function actionCreateAccount()
to
public function actionCreateaccount()

Just need to change in url from http://account.ll/Index/CreateAccount to http://account.ll/Index/create-account

Related

Yii2: How to redirect on invalid routes?

Instead of showing an error page I'd like to redirect the user to the start page in general, if the route is invalid (there is no controller/action like requested). To make it sound the redirection should only happen on 'normal' page requests. Though AJAX calls can be invalid as well, I don't want to send a redirect to the browser here.
How can I do this efficiently?
You can override ErrorAction class and will implement necessary logic. For example:
class MyErrorAction extends \yii\web\ErrorAction
{
public $redirectRoute;
public function run()
{
if (!Yii::$app->getRequest()->getIsAjax()) {
Yii::$app->getResponse()->redirect($this->redirectRoute)->send();
return;
}
return parent::run();
}
}
After it, you should add this action in a controller and configure it
class SiteController
{
public function actions()
{
return [
'error' => [
'class' => MyErrorAction::class
'redirectRoute' => 'site/my-page'
],
];
}
}
and configure the route of error action in the error handler
'errorHandler' => [
'errorAction' => 'site/error',
]

Redirect to a controller action, action not defined

I'm using Laravel 5.5.
My objective is to redirect to another method on the same controller to display a view with data.
class SeancesController extends Controller {
...
public function getRecommandations(Request $request) {
...
$data = [
'recommandationAutresActiviteMemeDateHeure' => $recommandationAutresActiviteMemeDateHeure,
'recommandationsMemeActiviteMemeHeure' => $recommandationsMemeActiviteMemeHeure,
'recommandationsMemeActiviteMemeDate' => $recommandationsMemeActiviteMemeDate
];
return redirect()->action('SeancesController#showRecommandations', $data);
}
public function showRecommandations(Request $request) {
return view('listeRecommandations', $request->data);
}
}
It is the right way to do this? Because I get this error :
InvalidArgumentException: Action App\Http\Controllers\SeancesController#showRecommandations not defined. in file /home/nicolas/public_html/M1_CSI/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php on line 338
I need to use action because I use an ajax call to access at getRecommandations().
I used this doc : http://laraveldaily.com/all-about-redirects-in-laravel-5/.
I didn't add a route that points to showRecommendations on my routing file. It's a problem?
Thank's for help!
I didn't add a route that points to showRecommendations on my routing file. It's a problem?
yes , it is a problem. because the redirector checks the routes that are assigned to the action and redirects the user to the route.

Yii not detecting camel case actions

Yii is giving me 404 Error if I declare an action like this:
SiteController.php
public function actionRegisterUser()
This is how I call it in the main.php
['label' => 'Register User', 'url' => ['/site/RegisterUser']],
I tried several different combinations. The only combination that will work is this naming convention in both places:
public function actionRegisteruser
'url' => ['/site/registeruser']
I used to work on another Yii project (Yii 1.0) and I could name my actions in camel case and call them without any problem. Do I need to turn on some sort of setting to do this?
I also tried playing with the rules of the Controller but that didn't solve anything.
In some cases you need camelcase link. For example, for SEO purposes (keep inbound links). You could create rewrite rule on web server side or add inline rule to URL manager on app side. Example:
'urlManager' => [
'rules' => [
'<controller:RegisterUser>/<action:\w+>'=>'register-user/<action>',
],
],
Also it's possible to write custom URL rule. Example:
namespace app\components;
use yii\web\UrlRuleInterface;
use yii\base\Object;
class CarUrlRule extends Object implements UrlRuleInterface
{
public function createUrl($manager, $route, $params)
{
if ($route === 'car/index') {
if (isset($params['manufacturer'], $params['model'])) {
return $params['manufacturer'] . '/' . $params['model'];
} elseif (isset($params['manufacturer'])) {
return $params['manufacturer'];
}
}
return false; // this rule does not apply
}
public function parseRequest($manager, $request)
{
$pathInfo = $request->getPathInfo();
if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) {
// check $matches[1] and $matches[3] to see
// if they match a manufacturer and a model in the database
// If so, set $params['manufacturer'] and/or $params['model']
// and return ['car/index', $params]
}
return false; // this rule does not apply
}
}
And use the new rule class in the [[yii\web\UrlManager::rules]] configuration:
[
// ...other rules...
[
'class' => 'app\components\CarUrlRule',
// ...configure other properties...
],
]
You need to specify your action like this ['/site/register-user']. As documentation says about Inline Actions:
index becomes actionIndex, and hello-world becomes actionHelloWorld

Unable to generate a URL

I am currently trying to create a link on the index page that'll allow users to create an item. My routes.php looks like
Route::controller('items', 'ItemController');
and my ItemController looks like
class ItemController extends BaseController
{
// create variable
protected $item;
// create constructor
public function __construct(Item $item)
{
$this->item = $item;
}
public function getIndex()
{
// return all the items
$items = $this->item->all();
return View::make('items.index', compact('items'));
}
public function getCreate()
{
return View::make('items.create');
}
public function postStore()
{
$input = Input::all();
// checks the input with the validator rules from the Item model
$v = Validator::make($input, Item::$rules);
if ($v->passes())
{
$this->items->create($input);
return Redirect::route('items.index');
}
return Redirect::route('items.create');
}
}
I have tried changing the getIndex() to just index() but then I get a controller method not found. So, that is why I am using getIndex().
I think I have set up my create controllers correctly but when I go to the items/create url I get a
Unable to generate a URL for the named route "items.store" as such route does not exist.
error. I have tried using just store() and getStore() instead of postStore() but I keep getting the same error.
Anybody know what the problem might be? I don't understand why the URL isn't being generated.
You are using Route::controller() which does generate route names as far as I know.
i.e. you are referring to "items.store" - that is a route name.
You should either;
Define all routes specifically (probably best - see this blog here)
Use Route::resource('items', 'ItemController'); see docs here
If you use Route::resource - then you'll need to change your controller names
The error tells you, that the route name is not defined:
Unable to generate a URL for the named route "items.store" as such route does not exist.
Have a look in the Laravel 4 Docs in the Named Routes section. There are several examples that'll make you clear how to use these kind of routes.
Also have a look at the RESTful Controllers section.
Here's an example for your question:
Route::get('items', array(
'as' => 'items.store',
'uses' => 'ItemController#getIndex',
));
As The Shift Exchange said, Route::controller() doesn't generate names, but you can do it using a third parameter:
Route::controller( 'items',
'ItemController',
[
'getIndex' => 'items.index',
'getCreate' => 'items.create',
'postStore' => 'items.store',
...
]
);

Cakephp Passed arguments

Hello, my code is not working in CakePHP framework and it is showing an error message.
URL:
http://domainname.com/About/param1/param2
Code:
class AboutController extends AppController {
public $name = 'About';
public $helpers = array('Html');
public function index($arg1, $arg2)
{
print_r($this->request->params['pass']);
$this->set('title_for_layout','Sarasavi Bookshop - About Sarasavi Bookshop');
$this->set('nameforfiles','about');
}
}
Error message:
Missing Method in AboutController
Error: The action param1 is not defined in controller AboutController
Error: Create AboutController::param1() in file: app\Controller\AboutController.php.
<?php
class AboutController extends AppController {
public function param1() {
}
}
Notice: If you want to customize this error message, create app\View\Errors\missing_action.ctp
After creating the function param1 I can get param2, But I need to get param1 and param2 both, in index function without create another action.
Please help me,
Thanks
Your original code would work if you went to http://domainname.com/About/index/param1/param2
If you don't want the index in the url, as I assume you don't, then you need to define a route.
Add this to your routes:
Router::connect(
'/About/*',
array('controller' => 'About', 'action' => 'index')
);
to automatically route requests that don't specify an action but do have params to go to your index action. You will need to add a route for any new About actions to stop requests for them from going to index by default though.
You probably access this URL without specifying action name (index) like this:
/about/param1/param2
This will not work as Cake expects to see action name after controller name. In this case, param1 is treated as action name.
You can access your action with URL
/about/index/param1/param2
To overcome this situation, make a new rule to your Router:
Router::connect(
'/about/:param1/:param2',
array('controller' => 'about', 'action' => 'index'),
array('param1', 'param2')
);

Categories