Cakephp goes to wrong path - cakephp-3.0

I am working on Cakephp. In default.ctp i give a link like
<li><?= $this->Html->link('List',['controller' => 'Products', 'action' => 'index']) ?></li>
I also have a ProductsController.php .
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;
class ProductsController extends AppController {
public function initialize(){
parent::initialize();
$this->loadcomponent('Flash');
}
public function index(){
$products = $this->Products->find('all');
$this->set(compact('products'));
}
But when i click on that link it give the error like
Error: WebrootController could not be found.
Error: Create the class WebrootController below in file: src/Controller/WebrootController.php
When click on toggle arguments it shows
object(Cake\Network\Request) {
params => [
'plugin' => null,
'controller' => 'Webroot',
'action' => 'products',
'_ext' => null,
'pass' => [],
'_matchedRoute' => '/:controller/:action/*',
'isAjax' => false
]
data => []
query => []
cookies => [
'__atuvc' => '1|21'
]
url => 'webroot/products/'
base => '/cakephp'
webroot => '/cakephp/'
here => '/cakephp/webroot/products/'
trustProxy => false
Please help me to solve this error.

Check if you have two .htaccess files present in your application root folder and in the webroot folder.
And make sure that an .htaccess override is allowed and that AllowOverride is set to All for the correct DocumentRoot
http://book.cakephp.org/3.0/en/installation.html#url-rewriting

Related

How to set home page in Yii2

public function actionIndex() {
$this->layout = 'landing';
$loginForm = new LoginForm();
if (\Yii::$app->request->getIsPost()) {
$loginForm->load(\Yii::$app->request->post());
if ($loginForm->validate()) {
$user = $loginForm->getUser();
\Yii::$app->user->login($user);
return $this->goHome();
}
}
}
method goHome() sends to the home page. I have added '' => 'site/index' to the URL Manager earlier to send people to the SiteController and Index action, but Yii2 does not do anything. How to set up a correct home page rule?
You should write homeUrl parameter on config/main.php. For example:
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'homeUrl' => ['some/home-url-example'],
'modules' => [
...
],
...
]

Cakephp dynamic homepage without slug

I am trying to build a dynamic page system with cakephp 3.
Using slugs I can show pages and content. But on the homepage, it is just using the default view template.
I have the routes as followed:
$routes->connect('/', ['controller' => 'pages', 'action' => 'display', 'home']);
$routes->connect('/:slug', ['controller' => 'pages', 'action' => 'view'], ['pass' => ['slug'], 'slug' => '[^\?/]+']);
Which works for the none homepage pages.
But I want to use the homepage as / (e.g. localhost:8000/)
And not /home (e.g. localhost:8000/home).
Currently the view function in the pages controller looks like this:
public function view($slug = null)
{
$pages = TableRegistry::getTableLocator()->get('webpages');
$page = $pages->findBySlug($slug)->firstOrFail();
$this->set(compact('page'));
}
Any idea?
Seems I already found the solution.
I changed the routing to just the following line:
$routes->connect('/*', ['controller' => 'pages', 'action' => 'view']);
Then I changed the view as followed:
public function view($slug = null)
{
$pages = TableRegistry::getTableLocator()->get('webpages');
if($slug == null){
$query = $pages->find('all', [
'conditions' => ['ishome' => 1]
]);
} else {
$query = $pages->find('all', [
'conditions' => ['slug' => $slug]
]);
}
$page = $query->first();
$this->set(compact('page'));
}
I use the answer from the following comment, but had to modify it a bit, since that code was used for an older version of cakephp (I am using cakekphp 3.8).
https://stackoverflow.com/a/3975923/6181243

What's the best way to make a ZF3 application with no default router?

I made a Zend Framework 3 MVC application. I don't want a default router. My one controller RESTFUL and only returning JSON. I want to remove the default IndexController. I want / to just give a 404 error. I'd prefer not to call any route 'home' but will do that if necessary.
If I make my route config look like this:
'router' => [
'routes' => [
'myRoute' => [
'type' => Segment::class,
'options' => [
'route' => '/myThing[/:action]',
'defaults' => [
'controller' => Controller\MyThingController::class,
'action' => 'index',
],
],
],
],
],
I get the following exception when I connect to a route that worked when I kept the default index controller in my browser:
Fatal error: Uncaught Zend\Router\Exception\RuntimeException: Route with name "home" not found in /var/www/vendor/zendframework/zend-router/src/Http/TreeRouteStack.php on line 354
If I change 'myRoute' => [ to 'home' => [ It renders the default layout instead of the Json rendered by JsonViewModel.
I just put an IndexController with a default route that renders the defautl 404 page for now. I'm going to make it return JSON at some point when I figure out how.
class IndexController extends AbstractRestfulController
{
public function indexAction()
{
$this->response->setStatusCode(Response::STATUS_CODE_404);
}
}
I'm not sure if this is what your after but to return a json response from your controller use.
In your module config:
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy',
),
},
and in your controller:
use Zend\View\Model\JsonModel;
// ...
public function indexAction()
{
$this->response->setStatusCode(Response::STATUS_CODE_404);
$view = new JsonModel();
$view->jsonVariable = 'someValue';
return $view;
}
This will return a json response.
Hope this helps.

yii2 createUrl is duplicating the route

i'm building multi lingual site with English and Arabic
url for English
url for Arabic
I want to switch language from any page exactly to the same page of the other language
so i made code like below.
$route = Yii::$app->controller->route;
$params = $_GET;
array_unshift($params, '/'.$route);
<?php if(Yii::$app->language == 'ar'){ ?>
<?= Html::a('English', [Yii::$app->urlManager->createUrl($params), 'language'=>'en']); ?>
<?php }else{?>
<?= Html::a('Arabic', [Yii::$app->urlManager->createUrl($params), 'language'=>'ar']); } ?>
and my url generating like below
/multi/backend/web/en/multi/backend/web/ar/site/index?val=hii&net=good
English
don't know what is wrong?
I'm using this for language management.
please check my main.php under 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')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'language' => 'en',
'sourceLanguage' => 'en_UK',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'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',
],
'i18n' => [
'translations' => [
'app' => [
'class' => 'yii\i18n\DbMessageSource',
'sourceLanguage' => 'en_UK',
],
],
],
'urlManager' => [
'class' => 'codemix\localeurls\UrlManager',
'languages' => ['en', 'ar'],
'enableDefaultLanguageUrlCode' => false,
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
'params' => $params,
];
If you are doing it as in your example, you have to think about it on every link you create. This can be automated easily.
URL-Rule
You can solve this with an url-rule in your config file like so:
'<language:[\w]{2,2}>/<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
This will assert the proper routing to your controller and provide you the desired language in the language-variable.
Custom UrlManager
You can extend the UrlManager-class and make sure the current language is always appended to the params:
class MyUrlManager extends \yii\web\UrlManager
{
// ...
/**
* #inheritdoc
*/
public function createUrl($params)
{
if (!isset($params['language'])) {
$params['language'] = Yii::$app->language;
}
return parent::createUrl($params);
}
// ...
}
This will automate the process of adding the language to the links you create.
Custom Application
Now you should also override the Application-class and always set the language to the one provided or choose a default (in this case en):
class MyApplication extends \yii\web\Application
{
// ...
/**
* #inheritdoc
*/
public function init()
{
parent::init();
$lang = Yii::$app->request->get('language', 'en');
Yii::$app->language = $lang;
}
// ...
}
Now your language will always be set to the default value or the one provided viathe query param as specified above.
Final thoughts
This should give you the basic idea on how to solve your problem. Adjust as necessary...especially the last part with the Application-class and how you retrieve the value of the language-var. I hope it helped!
Possible problems with your code and the extension provided
If you read the docs of the extension the urls are generated differently. It tells you to create the urls as follows:
Url::to(['demo/action', 'language'=>'ar'])
You are createing a simple link-tag and overwrite the $params. Try this instead:
echo Html::a('Arabic', Url::to(['site/index', 'language'=>'ar']));
For redirection to the current page just replace the first part with the current route.
after lots of trying ..i found a solution.. now its worked for me.
$route = Yii::$app->controller->route;
if(Yii::$app->language == 'ar'){
$_GET['language'] = 'en';
}else{
$_GET['language'] = 'ar';
}
$params = $_GET;
array_unshift($params, '/'.$route);
<?php if(Yii::$app->language == 'ar'){ ?>
<?= Html::a('English', Yii::$app->urlManager->createUrl($params)); ?>
<?php }else{?>
<?= Html::a('Arabic', Yii::$app->urlManager->createUrl($params)); } ?>
its working for the url like
http://localhost/multi/backend/web/site/index?page=2&per-page=6
and
http://localhost/multi/backend/web/site/index

Authentication Component

I am using CakePHP for the first time. So, please, be patient with me:
I have a table called admin_users, when i try to add the Auth component in my AppController.php.
While executing, I always receive an error telling me that: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db_test.users' doesn't exist.
My table is called admin_users, so the error could be because the table should be always called "users" to work properly?
Here is my implementation in AppController.php:
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash');
$this->loadComponent('Auth',[
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'AdminUsers',
'action' => 'login'
]
]);
$this->Auth->allow(['display']);
}
and in AdminUsersController, the login function:
public function login()
{
if ($this->request->is('post')){
$adminUser = $this->Auth->identify();
if ($adminUser){
$this->Auth->setAdminUser($adminUser);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('Your username or password is incorrect.');
}
}
Thank you.
Try this
In AppController.php:
function beforeFilter() {
$this->Auth->userModel = 'admin_users';
}