I have problem for action view, update, and delete in index.php page, it always show bad request (#400) Missing required parameters: id_kategori and the address always go to localhost/training/frontend/web/index.php?r=kategori%2F(view/update/delete)&id=1, but when i change the address manually to localhost/training/frontend/web/index.php?r=kategori%2Fview&id_kategori=1 it's no problem, also i can create action but then it will redirect page to localhost/training/frontend/web/index.php?r=kategori%2Fview&id=1. Here's the code, its generate from Gii CRUD:
public function actionView($id_kategori)
{
return $this->render('view', [
'model' => $this->findModel($id_kategori),
]);
}
public function actionUpdate($id_kategori)
{
$model = $this->findModel($id_kategori);
if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
return $this->redirect(['view', 'id_kategori' => $model->id_kategori]);
}
return $this->render('update', [
'model' => $model,
]);
}
public function actionDelete($id_kategori)
{
$this->findModel($id_kategori)->delete();
return $this->redirect(['index']);
}
Should i rename id_kategori column to id and other id_column just to id?
Version: Yii 2 (2.0.43)
Template: Advanced Template
define $id_kategori=null in function
public function actionView($id_kategori=null)
{
return $this->render('view', [
'model' => $id_kategori ? $this->findModel($id_kategori) : null,
]);
}
You need to do like this
public function actionView($id) {
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
Related
I have lumen + jwt restapi with custom users table (ex : pengguna) with nomor as primary key and tgl_lahir as password..there is no problem with api/login and it's generate a token but when i try with other route such as api/buku, the return always 401 unauthorized although the authorization header contains valid token after login
my models like
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable;
protected $primaryKey = 'nomor';
protected $table = 'pengguna';
public $timestamps = false;
protected $fillable = [
'nomor','nama','alamat'
];
protected $hidden = [
'tgl_lahir ',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
my BukuController
<?php
namespace App\Http\Controllers;
use App\Buku;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class BukuController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function showAllBuku()
{
return response()->json(Buku::all());
}
}
my routes
$router->group(['prefix' => 'api'], function () use ($router) {
$router->post('login', 'AuthController#login');
$router->get('buku', ['uses' => 'BukuController#showAllBuku']);
});
config/auth.php
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\User::class
]
],
];
the existing pengguna table don't allowed created ID field like lumen/laravel auth, if i commented code in Middleware\Authenticate like :
public function handle($request, Closure $next, $guard = null)
{
//if this block commented is working
if ($this->auth->guard($guard)->guest()) {
return response('Unauthorized.', 401);
}
return $next($request);
}
it's working..is there another way for my case?thanks for your help
sorry my mistake, my problem solved by add this in user model
public function getAuthIdentifierName(){
return $this->nomor;
}
public function getAuthIdentifier(){
return $this->{$this->getAuthIdentifierName()};
}
I'm in windows using php-7.4.1 Architecture-x64, phalcon - 4.0.2, psr - 0.7.0 and follow instruction from 'https://docs.phalcon.io/4.0/en/application' but the problem is its always render frontend module & its view. I'm unable to find out what i'm doing wrong?
[Index.php]
use Phalcon\Mvc\Router;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault;
$di = new FactoryDefault();
$di->set('router',function () {
$router = new Router(false);
$router->setDefaultModule('frontend');
$router->add('/login',
[
'module' => 'backend',
'controller' => 'index',
'action' => 'index',
]
);
$router->add('/admin/products/:action',
[
'module' => 'backend',
'controller' => 'index',
'action' => 1,
]
);
return $router;
}
);
$application = new Application($di);
$application->registerModules(
[
'frontend' => [
'className' => \Multiple\Frontend\Module::class,
'path' => '../apps/frontend/Module.php',
],
'backend' => [
'className' => \Multiple\Backend\Module::class,
'path' => '../apps/backend/Module.php',
],
]
);
try {
$response = $application->handle($_SERVER["REQUEST_URI"]);
$response->send();
} catch (\Exception $e) {
echo $e->getMessage();
}
[Backend module]
<?php
namespace Multiple\Backend;
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Di\DiInterface;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\ModuleDefinitionInterface;
class Module implements ModuleDefinitionInterface
{
public function registerAutoloaders(DiInterface $di = null)
{
$loader = new Loader();
$loader->registerNamespaces(
[
'Multiple\Backend\Controllers' => '../apps/backend/controllers/',
'Multiple\Backend\Models' => '../apps/backend/models/',
]
);
$loader->register();
}
public function registerServices(DiInterface $di)
{
$di->set('dispatcher',function () {
$dispatcher = new Dispatcher();
$dispatcher->setDefaultNamespace('Multiple\Backend\Controllers');
return $dispatcher;
}
);
$di->set('view',function () {
$view = new View();
$view->setViewsDir('../apps/backend/views/');
return $view;
}
);
}
}
[Index Controller]
<?php
namespace Multiple\Backend\Controllers;
use Phalcon\Mvc\Controller;
class IndexController extends Controller
{
public function indexAction()
{
return '<h1>Back Controller!</h1>';
}
}
Did you set your namespaces in the frontend module as well? Like you did with registerAutoloaders in the backend.
Make sure you have registered your new module in
../app/bootstrap_web.php around line 47 which looks as shown below
$application->registerModules([
'frontend' => ['className' => 'MyApp\Modules\Frontend\Module'],
// <--- add your new module here --->
]);
and that your module class is also registered in the loader at ../app/config/loader.php around line 18 which looks as shown below
$loader->registerClasses([
'MyApp\Modules\Frontend\Module' => APP_PATH . '/modules/frontend/Module.php',
// <--- Add your new module class here --->
]);
Always keep an eye on your namespaces. I hope it helps.
I want the status order to display at AdminStats. I created the file override/controllers/admin/AdminStatsController.php:
<?php // Check order status in Stats Dashboard BO class AdminStatsController extends AdminStatsControllerCore {
public function __construct() {
parent::__construct();
$this->fields_list['order_statuses'] = array('title' => $this->l('Order Status');
}
}
But when I go to AdminStats, a blank page shows up (see image below).
Any suggestions?
EDIT: this is not the solution in respect to the question asked.
I'd to do the exact same thing. I did it something like this, but it was AdminOrdersController but it's pretty much the same. Here it is,
// override/controllers/admin/AdminStatsController.php
<?php
public function __construct() {
parent::__construct();
$this->fields_list = array_merge($this->fields_list, [
'order_statuses' => [
'title' => $this->l('Order Status'),
'align' => 'text-center',
'callback' => 'orderStatusFunction', // yes, a callback to get a piece of UI back, a button maybe
'orderby' => false, // or true, anything you'd like
'search' => false,
'remove_onclick' => true,
]
]);
}
}
Now the callback
<?php
public function orderStatusFunction($row_number, $row_data) // row_data like date, order, customer, etc
{
/* do stuff with data and assign to your template */
$view = _PS_MODULE_DIR_ . 'path/to/view/file/view.tpl';
$html = $this->context->smarty->createTemplate($view, $this->context->smarty)->fetch();
return $html;
}
Let me know if you've any confusion, or if it didn't work out.
i try to save multilanguaged content
My About model
...
public function rules() {
return [
[['status', 'date_update', 'date_create'], 'integer'],
[['date_update', 'date_create'], 'required'],
];
}
...
public function getContent($lang_id = null) {
$lang_id = ($lang_id === null) ? Lang::getCurrent()->id : $lang_id;
return $this->hasOne(AboutLang::className(), ['post_id' => 'id'])->where('lang_id = :lang_id', [':lang_id' => $lang_id]);
}
My AboutLang model
public function rules()
{
return [
[['post_id', 'lang_id', 'title', 'content'], 'required'],
[['post_id', 'lang_id'], 'integer'],
[['title', 'content'], 'string'],
];
}
My About controller
public function actionCreate()
{
$model = new About();
$aboutLang = new AboutLang();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,'aboutLang'=>$aboutLang]);
}
}
and my view (create form)
...
<?= $form->field($model, 'status')->textInput() ?>
<?= $form->field($aboutLang, 'title')->textInput() ?>
<?= $form->field($aboutLang, 'content')->textInput() ?>
enter code here
And when i put $aboutLang in create form i get an error "Call to a member function formName() on a non-object"
It looks like the views you are using were generated by Gii. In that case, Gii generates a partial view for the form (_form.php) and two views both for create and update actions (create.php and update.php). These two views perform a rendering of the partial view.
The problem you might have is that you are not passing the variable $aboutLang from create.php to _form.php, that must be done in create.php, when you call renderPartial():
$this->renderPartial("_form", array(
"model" => $model,
"aboutLang" => $aboutLang, //Add this line
));
Hope it helps.
Check your $aboutLang type.
It looks like it is null.
if ($aboutLang) {
echo $form->field($aboutLang, 'title')->textInput();
echo $form->field($aboutLang, 'content')->textInput();
}
I am using cakephp 3.0 and in the login page although I try to enter the right credentials i get invalid username or password message.
In my user table , I have the fields username and password by which i want to authenticate user.
I have tried to follow the cake book documentation for 3.0 except the step where for including password hashing.Also used the table structure similiar to the one in cakephp documentation
Is it because it is accessing the wrong table?I have mentioned the fields in App Controller
Also if i have to implement single sign on ,is there a plugin which could help me out?Please provide links to such tutorials as this is important for my graduate studies project
My model file:
class UsersTable extends Table
{
public function initialize(array $config)
{
$this->table('users');
$this->displayField('User_id');
$this->primaryKey('User_id');
$this->addBehavior('Timestamp');
}
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->notEmpty('id', 'create')
->notEmpty('username','Username is required')
->notEmpty('password','Password is required')
->notEmpty('role');
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['username']));
return $rules;
}
}
My UserController file
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Core\App;
use Cake\Event\Event;
class UsersController extends AppController
{
public function view($id = null)
{
$user = $this->Users->get($id, [
'contain' => []
]);
$this->set('user', $user);
$this->set('_serialize', ['user']);
}
public function register()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success('The user basic details has been saved.');
} else {
$this->Flash->error('The user could not be saved. Please, try again.');
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
public function edit($id = null)
{
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success('The user has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The user could not be saved. Please, try again.');
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$user = $this->Users->get($id);
if ($this->Users->delete($user)) {
$this->Flash->success('The user has been deleted.');
} else {
$this->Flash->error('The user could not be deleted. Please, try again.');
}
return $this->redirect(['action' => 'index']);
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
// Allow users to register and logout.
// You should not add the "login" action to allow list. Doing so would
// cause problems with normal functioning of AuthComponent.
$this->Auth->allow(['register', 'logout']);
}
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
$this->set('user',$user);
if ($user) {
$this->Auth->setUser($user);
$this->Flash->error(__('Login successful'));
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
public function index()
{
$this->set('users', $this->paginate($this->Users));
$this->set('_serialize', ['users']);
}
}
My AppController file
class AppController extends Controller
{
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
]
]
],
'loginRedirect' => [
'controller' => 'Orders',
'action' => 'view'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
$this->Auth->allow(['display']);
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display','login']);
}
}
My login page:
<div class="users_form">
<?=$ this->Flash->render('auth') ?>
<?=$ this->Form->create() ?>
<fieldset>
<legend>
<?=_ _( 'Please enter your username and password') ?>
</legend>
<?=$ this->Form->input('username') ?>
<?=$ this->Form->input('password') ?>
</fieldset>
<?=$ this->Form->button(__('Login')); ?>
<?=$ this->Form->button(__('Register')); ?>
<?=$ this->Form->end() ?>
</div>
I figured out what was wrong.
First place I had not included the password hasher method.
On trying to include that ,I added it to the wrong module.It must be added for the Entity class file whereas I was adding it to The UserTable.php.
This was not helping my case at all.I followed the manual to the T .
After adding the password Hasher module I added a new user.
Also it is true that it works only if the password length is varchar(255)
Therefore the user along with hashed password was created.
I was then able to login