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

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

Related

How to POST action REST API in Yii2 Advanced Template

i Have a question for you guys :) I'm trying to add an API on my yii2 advanced template as i want my wordpress website send datas to my yii2 app.
My system : 1) Yii2 advanced template 2) wordpress website 3) my wordpress plugin with vuejs and axios to create a new entry in my yii2 app via API
So what i allready did :
common/config/main.php (as i use AccessController, i added orders/* to allow it)
'as access' => [
'class' => 'mdm\admin\components\AccessControl',
'allowActions' => [
'orders/*',
],
frontend/config/main.php
'components' => [
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
and (in urlManager array)
['class'=>'yii\rest\UrlRule','controller'=>'Orders'],
[‘class'=>'yii\rest\UrlRule','controller'=>'Contacts']
Then my controller :
<?php
namespace frontend\controllers;
use yii\rest\ActiveController; use yii\filters\auth\HttpBasicAuth;
class OrdersController extends ActiveController {
public $modelClass = 'common\models\Vctorders';
public function behaviors()
{
$behaviors = parent::behaviors();
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
}
public function actions()
{
$actions = parent::actions();
unset($actions['create']);
unset($actions['update']);
unset($actions['delete']);
unset($actions['view']);
//unset($actions['index']);
return $actions;
}
protected function verbs(){
return [
'create' => ['POST'],
'new' => ['POST'],
'update' => ['PUT', 'PATCH','POST'],
'delete' => ['DELETE'],
'view' => ['GET'],
//'index'=>['GET'],
];
}
public function actionCreate()
{
$model = new Vctorders();
$model->date_creation = date('Y-m-d H:i:s',strtotime('now'));
$model->etat = 0;
if($model->save()){
return 'OK';
} else{
return 'error';
}
}
}
So, i a use Postman with : http://localhost:8888/SD/sdms/orders/ i get a record, no problem
But when i do a POST with :
http://localhost:8888/SD/sdms/orders/create?livre=L'Arbre Musicien&langue=Allemand&nom=Perroud&prenom=LIttledave&nombre=2&npa=1221&pays=suisse&accept_pc=1&mail=post#post.ch&etat=1&message=lbablalbal&tel=01201201212
the answer is
{"name":"Exception","message":"Class 'frontend\\controllers\\Vctorders' not found","code":0,"type":"Error","file":"/Applications/MAMP/htdocs/SD/sdms/frontend/controllers/OrdersController.php","line":58,"stack-trace":["#0 [internal function]: frontend\\controllers\\OrdersController->actionCreate()","#1 /Applications/MAMP/htdocs/SD/sdms/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)","#2 /Applications/MAMP/htdocs/SD/sdms/vendor/yiisoft/yii2/base/Controller.php(157): yii\\base\\InlineAction->runWithParams(Array)","#3 /Applications/MAMP/htdocs/SD/sdms/vendor/yiisoft/yii2/base/Module.php(528): yii\\base\\Controller->runAction('create', Array)","#4 /Applications/MAMP/htdocs/SD/sdms/vendor/yiisoft/yii2/web/Application.php(103): yii\\base\\Module->runAction('orders/create', Array)","#5 /Applications/MAMP/htdocs/SD/sdms/vendor/yiisoft/yii2/base/Application.php(386): yii\\web\\Application->handleRequest(Object(yii\\web\\Request))","#6 /Applications/MAMP/htdocs/SD/sdms/frontend/web/index.php(17): yii\\base\\Application->run()","#7 {main}"]}
The problem is you are sending your request in POSTMAN as a GET REQUEST, and your ACTION in the CONTROLLER expects a POST REQUEST.
In your POSTMAN client at the left side, there is a selector where you can choose what kind of request you are doing.
The second error you get is because once you remove the requisite of POST, the GET request enters the action and goes here:
} elseif (!\Yii::$app->request->isPost) {
$model->load(Yii::$app->request->get());
}
And tries to load the model with the data in the GET parameters, but fails as there is no way the default $model->load() knows how to map the data in your GET petition.
In any case (GET or POST) the $model->load() will not work, as if you check the load() function you will find that it searches for the Object modal name inside the array to load the parameters, so you must do like:
http://localhost:8888/SD/sdms/orders/create?Orders%5Blivre%5=L'Arbre
But for each parameter, the strange characters you see in the result of stringify ['Orders' => ['livre' => 'Larbre']].

Route in Yii2 doesn't work

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

how to change url management flow in yii

i have implementing the project in yii. i done my project but i want to change instead of id to name. ie url management. i did uncomment in config.php then i added the following code. those follows:
my table name is recipe:
public function loadModel($id)
{
$model=Recipe::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
public function loadModel2($name)
{
$model=Recipe::model()->find('t.name=:name', array(':name' => $name));
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
except this i added top of the sitecontroller use Recipe. but it shows error is
The use statement with non-compound name 'Recipe' has no effect
please suggest me suitable answer
I personally use in my projects something like /product-name/p/1 and this is SEO friendly. To get your links to look like that you have to first change your url rules
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'urlSuffix' => '/',
'rules' => array(
'<title:.*?>/p/<id:\d+>'=>'product/view',
),
),
Then use this to create your URLs.
Yii::app()->createUrl('product/view',array('id'=>$model->id, 'title'=>$model->name))
Now it works both ways, the create url will always create urls like /product-name/p/1 and further more you can show the product the normal way
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$model = $this->loadModel($id);
$this->render('view',array(
'model'=>$model,
));
}

creating custom action for controller yii

I'm new to yii.
I've created a controller called CatalogController. I want to create a custom action called actionClear(). I've followed steps from documentation and searching on-line but when I navigate to catalog/clear, it redirects back to homepage of site. I don't know what other steps I should be taking.
I've done the following so far:
in CatalogController:
public function actionClear() {
$dataProvider=new CActiveDataProvider('Catalog');
$this->render('clear',array('dataProvider'=>$dataProvider));
}
overridden rules() method in controller:
public function actions()
{
return array(
'clear'=>'application.controllers.post.ClearAction',
);
}
a new custom action under protected/controllers/post
class ClearAction extends CAction
{
public function run()
{
echo 'fart';die;
}
}
Any help would be greatly appreciated.
Did you try the url index.php?r=catalog/clear or jus index.php/catalog/clear ?
By default in yii only the first one will work. For the second one you need to activate it in the url manager:
In your config file edit the url manager as follow:
array(
......
'components'=>array(
......
'urlManager'=>array(
'urlFormat'=>'path',
),
),
);
Source: The Yii guide

Laravel debugging 404 routes

Ok, the full routes.php file that I use... I just pasted it here: http://pastebin.com/kaCP3NwK
routes.php
//The route group for all other requests needs to validate admin, model, and add assets
Route::group(array('before' => 'validate_admin|validate_model'), function()
{
//Model Index
Route::get('admin/(:any)', array(
'as' => 'admin_index',
'uses' => 'admin#index'
));
administrator config:
...
'models' => array(
'news' => array(
'title' => 'News',
'single' => 'news',
'model' => 'AdminModels\\News',
),
...
links generator:
#foreach (Config::get('administrator.models') as $key => $model)
#if (Admin\Libraries\ModelHelper::checkPermission($key))
<?php $key = is_numeric($key) ? $model : $key; ?>
<li>
{{ HTML::link(URL::to_route('admin_index', array($key)), $model['title']) }}
</li>
#endif
#endforeach
controllers/admin.php
public function action_index($modelName)
{
//first we get the data model
$model = ModelHelper::getModelInstance($modelName);
$view = View::make("admin.index",
array(
"modelName" => $modelName,
)
);
//set the layout content and title
$this->layout->modelName = $modelName;
$this->layout->content = $view;
}
So, when accessing http://example.com/admin/news the news is sent to action_index... but for some reason it doesn't get there and it returns 404
Notice that I defined the following 'model' => 'AdminModels\\News',
when actually my namespace register was Admin\Models, so setting it to 'model' => 'Admin\Models\\News', for my issue for the 404
Routes are evaluated in the order that they're registered, so the (:any) route should be last. You're being sent (I think) to admin#index -- if that function isn't defined yet, that's why you're getting a 404.
Not related to the question, but if anyone (like me) comes here to find clues why a Laravel application displays a 404, here are some reasons:
Models not found in database that are specified in the URL
You have setup incorrect route model bindings in RouteServiceProvider (as I did when I stumbled over this answer). Example: Route::model('user', Tenant::class); when it should be User::class
Some middleware returns 404 (e.g. via "abort(404)")
The corresponding controller returns 404
The controller method (or namespace) is not found (This is the answer for this question.)

Categories