Can't get the parameter passed from view to controller in Yii2 - yii2

I am passing a value($model->stop) of my form to controller action(search2) via button click.But I can't get that value in the controller.
view:
<?= Html::a(Yii::t('app', 'Search'), ['search2','id' => $model->stop], ['class' => 'btn btn-success'])
Controller:
public function actionSearch2($id)
{
if ($model->load(Yii::$app->request->post())) {
$searchModel = new ScheduleRouteSearch();
$dataProvider1 = $searchModel->search1(Yii::$app->request- >queryParams, $id);
return $this->render('search', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider1,
]);
}
}
Error:
Bad Request (#400)
Missing required parameters: id
The above error occurred while the Web server was processing your request.
Please contact us if you think this is a server error. Thank you.
Help me to solve this.

All your code seems right,
I think problem is with $model->stop value
$model->stop // value might be null --null value also gives missing parameter error
please check.

Related

Don't create field in database

I hava code like below. It creates a field in database and show in another places. I would like to block create a database field if message field is not exit. Rest fields are taken from system. What is wrong in my code.
$delivery->comments_buro()->create([
'name' => auth()->user()->firstname,
'user_id' => auth()->user()->id,
'message' => $request['repair_report_buro'],
'icon' => 'fa fa-commenting-o',
'style' => $position->style,
]);
Thanks for help.
You need Laravel Validations for that. Please read this: https://laravel.com/docs/5.8/validation
For example:
//controller
public function index(Request $request)
{
$validator = Validator::make($request->all(), [
'message' => 'required|string',
]);
if ($validator->fails()) {
//do validation error handling here
}
// create new row in database.
}
I have a right code. It works with it. I close this question. The right code is:
if(isset($request['repair_report_buro']) && !empty($request['repair_report_buro'])){
$delivery->comments_buro()->create([
'name' => auth()->user()->firstname,
'user_id' => auth()->user()->id,
'message' => $request['repair_report_buro'],
'icon' => 'fa fa-commenting-o',
'style' => $position->style,
]);
}

Yii2 transfer logic from view to model

I would like to arrange my code a little bit better. I have this in view, generated by giiant:
$form->field($model, 'land_id')->dropDownList(ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name'), [
'prompt' => Yii::t('app', 'Select'),
'disabled' => (isset($relAttributes) && isset($relAttributes['land_id'])),]);
Somebody has told me here on stackoverflow that it's not really nice. So I would like to transfer this part:
ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name'
into model. The same applies to grid filter dropdowns:
'filter' => ArrayHelper::map(\app\models\base\Land::find()->asArray()->all(), 'id', 'name'),
Does it make sense? I think so, I hope so. I've tried to implement it in model Land 2 ways:
public function getAllAsArray() {
return ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name');
}
or
public function getAllAsArray() {
return ArrayHelper::map($this->find()->orderBy('name')->all(), 'id', 'name');
}
and I wanted to call it from View/Grid (Zip - Land):
'filter' => $model->land->allAsArray,
but I'm getting the following error:
Undefined variable: model
then tried this way:
'filter' => function ($model) {$model->getLand()->one()->getAllAsArray();},
'filter' => function ($model) {$model->getLand()->getAllAsArray();},
then I get no error messages, but it's also not working.
and in Form (Zip - Land) the same way:
$form->field($model, 'land_id')->dropDownList($model->land->allAsArray(), [
'prompt' => Yii::t('app', 'Select'),
'disabled' => (isset($relAttributes) && isset($relAttributes['land_id'])),]);
but I'm getting the following error:
Call to a member function getAllAsArray() on null
Can you please point me to the right direction? I think I don't understand something basically and this disturbes me. Thank you very much in advance!
Land model
public static function getAllAsArray() {
return ArrayHelper::map(Land::find()->orderBy('name')->all(), 'id', 'name');
}
index
use app\models\Land;
'filter' => Land::getAllAsArray(),
form
use app\models\Land;
$form->field($model, 'land_id')->dropDownList(Land::getAllAsArray(), [
'prompt' => Yii::t('app', 'Select'),
'disabled' => (isset($relAttributes) && isset($relAttributes['land_id']))]);

User login action is not working, showing invalid username and password in CakePHP3

I am trying to implement login functionality in CakePHP3 by following all prescribed ways. I have already tried many alternatives apart from main method found on Authentication page of official Cake website.
The error, I am receiving is "Invalid username or password". Below is a snapshot of code, I have used. Please note, I have followed proper naming conventions of CakePHP so no config issue should be there. Plus the issue is in 3.x version so don't answer for older versions please.
File: UsersController > Login Action
public function login() {
if($this->Auth->user()){
$this->Flash->error(__('You are already logged in!'));
return $this->redirect($this->Auth->redirectUrl());
}
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$this->Flash->success(__('You\'re successfully logged-in.'));
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Username or password is incorrect'));
}
}
File: AppController > Initialize Function
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Users',
'action' => 'login',
],
'authError' => 'Did you really think you are allowed to see that?',
'authenticate' => [
'Form' => [
'fields' => ['username' => 'username']
]
],
'storage' => 'Session'
]);
$this->Auth->allow(['display']);
$this->Auth->allow(['register']);
}
File: Login View
<?php
echo $this->Form->create();
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->button('Login', ['class' => 'btn']);
echo $this->Form->end();
?>
Hope, I haven't missed anything but still it is not working as intended.
Any suggestion will be appreciated.
TIA
It is not working without PasswordHasher in Auth component.
You should add it in /src/Model/Entity/User.php
Add below code at the end. Also add use Cake\Auth\DefaultPasswordHasher;
protected function _setPassword($value){
$hasher = new DefaultPasswordHasher();
return $hasher->hash($value);
}
After this add new user and try to login with it.
Is your user entity using the DefaultPasswordHasher in the file src/Model/Entity/User.php?
Just a thought...

Getting field value in controller

I want to get value of field in controller.
could you please help me?
here is my form code:
<?php
$form = ActiveForm::begin([
'id' => 'request-form',
'action' => 'site/request_page',
'method' => 'post',
'fieldConfig' => ['autoPlaceholder' => false]
]);
?>
<?= $form->field($model, 'workroom_id')->label(FALSE) ?>
and this is my controller code:
public function actionRequest_page() {
echo Yii::$app->request->post('workroom_id');
die();
}
But I got nothing in result.
write workroom_id in safe rule like this-
public function rules()
{
return [
[['workroom_id'],'safe']
];
}
Use bellow code -
echo Yii::$app->request->post('MODEL_NAME')['workroom_id'];
You should expand your action form-attribute. By using Url::to() for instance. As in echo \yii\helpers\Url::to(['site/request_page']);
And access your post data differently. Try var_dump(Yii::$app->request->post()); to see what your form data looks like. The other answer shows how to access it correctly.
The docs have an excellent starting place for working with forms.

yii2 join model as dataProvider

I've joined 2 tables like following:
$model = SalesEntry::find()
->joinWith('salesItems')
->all();
then in view used DataProvider like following:
GridView::widget([
'dataProvider' => $model,
'columns' => [
'date', // sample field from first table to see if ok
],
]);
and I’ve got following error:
Call to a member function getCount() on a non-object
What am I doing wrong here?
That is because an ActiveQuery instance is not a DataProvider, which the widget expects. You need to wrap it in an ActiveDataProvider for it to work:
GridView::widget([
'dataProvider' => new \yii\data\ActiveDataProvider(['query' => $model]),
' columns' => [
'date', // sample field from first table to see if ok
],
]);
DataProvider in GridView should be an instance of yii\data\DataProviderInterface
See docs.