Yii2: Returning an array of primary keys - mysql

Maybe I'm missing the essentials but why the following code will throw a Bad Request error (#400) complaining on "Missing parameter id" when rendering a view on a MySQL view?
In model:
public static function primaryKey()
{
return [
'vcostumbre_id',
'vbibliografia_id',
'vpagina_inicial',
];
}
In controller:
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
But this will work:
public function actionView($vcostumbre_id, $vbibliografia_id, $vpagina_inicial)
{
$id = [
'vcostumbre_id' => $vcostumbre_id,
'vbibliografia_id' => $vbibliografia_id,
'vpagina_inicial' => $vpagina_inicial,
];
return $this->render('view', [
'model' => $this->findModel($id),
]);
}

Because in the URL you have not the parameter "id".
It should be /mycontroller/view?id=42".
Check the view file where the link is. It should be :
Url::to(['/controller/view', 'id' => 42])

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' => [
...
],
...
]

Laravel not responding with validator errors

I validate a model
$validator = $c->validate($collection);
This is the validate function
public function validate($data){
return Validator::make($data, $this->rules());;
}
These are the rules
public function rules() {
return array([
'name' => [
'required', 'You need to choose a name for your collection.',
'unique:collections,table_name', 'A collection or collection table with this name already exists'
],
...
]);
}
I'm trying to send back a JSON response with the validator's errors, as such:
return response()->json($validator->errors(), 200);
I'm currently testing validation for the 'name' rule, and the validator is failing, as expected.
However, I'm expecting it to return that rule's message ("A collection or collection table with this name already exists")
Instead, I'm getting this returned:
My goal is to have laravel send back the error that I need, thank you in advance for any help.
edit: updated code:
Messages:
public function messages(){
return [
'name.required' => 'A name must be specified for the collection',
'name.unique' => 'A collection or collection table with this name already exists',
'name.min' => 'The collection name is too short',
'fields.*.fieldName.unique' => 'Field names must be unique',
'fields.*.fieldName.required' => 'One or more fields must be specified for the collection',
'fields.*.fieldName.not_in' => 'Illegal field name, please try another one',
'fields.*.fieldName.min' => 'The field name is too short',
'fields.*.dataType.required' => 'A data-type must be specified for fields',
'fields.*.dataType.in' => 'Illegal data-type'
];
}
public function rules() {
return array([
'name' => [
'required', 'You need to choose a name for your collection.',
'unique:collections,table_name', 'A collection or collection table
with this name already exists',
'min:2'
],
'fields.*.fieldName' =>
[
'unique' => 'Please ensure that the fields are uniquely named.',
'required' => 'You must specify a name for your fields.',
'not_in:'.implode(',', self::$illegalFieldNames),
'min:2'
],
'fields.*.dataType' =>
[
'required', 'You must specify a data type for your fields.',
'in:'.implode(',', self::$allowedDataTypes)
]
]);
}
public function validate($data){
return Validator::make($data, $this->rules(), $this->messages());
}
The validator make method takes the third parameter as the messages array. You can't mix the rules and messages like that.
public function rules()
{
return [
'name' => 'required|unique:collections,table_name'
];
}
public function messages()
{
return [
'name.required' => 'You need to choose a name for your collection',
'name.unique' => 'A collection or collection table with this name already exists',
];
}
public function validate($data)
{
return Validator::make($data, $this->rules(), $this->messages());
}
$this->rules($request, array(
'name' =>
'required|alpha_dash|min:5|max:255|unique:posts
));
use java script for revealing error
or you can use something like this .
public function store(Request $request)
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}

yii2 is not getting id in action after $model->save() and when I click the update item icon

I have a yii2 project, I am developing on my windows localhost and hosting remotely on linux.
Locally (windows) every thing is perfect.
While on linux, I have $model->id = null after $nodel->save(), although data is saved.
public function actionCreate() {
$model = new AppBreakingNews();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
I have tried die($model->id) after the save, it printed null.
Moreover, when I click on the update icon in the grid view, I am facing the same problem.
The AppBreakingNews is as follows:
<?php
namespace app\models\appmodels;
use app\models\BreakingNews;
use yii\behaviors\TimestampBehavior;
class AppBreakingNews extends BreakingNews {
public function behaviors() {
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => date('Y-m-d H:i:s'),
],
];
}
}
Notice that appBreakingNews extends the model BreakingNews that is generated by yii2 without any change.
Thanks in advance..
Please try to save model->save(false); because i think it validate something from model file.
public function actionCreate() {
$model = new AppBreakingNews();
if ($model->load(Yii::$app->request->post()) && $model->save(false)) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
or can you please print your model file here.

How to save current user_id to database (YII2)

I try to save current user_id to the education table in database. However,the data of user_id is not filled. This is my code.
At model
public function rules()
{
return [
[['year', 'fieldstudy', 'institute', 'grade'], 'required'],
[['user_id'], 'integer'],
[['year', 'fieldstudy', 'institute', 'grade'], 'string', 'max' => 255],
];
}
public function attributeLabels()
{
return [
'education_id' => 'Education ID',
'user_id' => 'User ID',
'year' => 'Year',
'fieldstudy' => 'Fieldstudy',
'institute' => 'Institute',
'grade' => 'Grade',
];
}
public function getUser()
{
return $this->hasOne(User::className(), ['user_id' => 'user_id']);
}
At controller
public function actionCreate()
{
$model = new Education();
$model->user_id =Yii::$app->user->id;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->education_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
How can I solve my problem and fix my code? Thanks
update Yii::$app->user->id to Yii::$app->user->identity->id.
public function actionCreate()
{
$model = new Education();
if ($model->load(Yii::$app->request->post())) {
$model->user_id =Yii::$app->user->identity->id;
if($model->save()){
return $this->redirect(['view', 'id' => $model->education_id]);
}
}
return $this->render('create', [
'model' => $model,
]);
}
You have to check two things
Check whether the user is logged in.
Use Yii2 debugger to see whether we are getting the id value of the logged in user by the code Yii::$app->user->id or Yii::$app->user->id
Use Yii2 debugger to check whether the correct user id value we are getting by using the code
Yii::info("User id=".Yii::$app->user->id);
Full code you have to try in the controller is given below
public function actionCreate() {
$model = new Education();
//checking whether we are getting the logged in user id value
Yii::info("User id=".Yii::$app->user->id);
$model->user_id = Yii::$app->user->id;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
//checking here the saved user id value in table
Yii::info("checking User id after saving model=".$model->user_id);
return $this->redirect(['view', 'id' => $model->education_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Now after running the application you can check using Yii2 debugger the values that are set in the user id in various places.

Yii2 multi captcha in one page

I have a page that contains multi captcha in separated forms form example login and register modals , etc.
if I use below codes the problem is that when refresh one captcha then another captcha will be unusable because they use same session varible:
1) Login
login modal (view):
echo Captcha::widget([
'id' => 'Login-captcha',
'name' => 'LoginModel[captcha]',
'captchaAction' => '/site/captcha'
]);
LoginModel :
public function rules()
{
return [
['captcha', 'captcha'],
];
}
2) Register
register modal (view):
echo Captcha::widget([
'id' => 'register-captcha',
'name' => 'RegisterModel[captcha]',
'captchaAction' => '/site/captcha'
]);
RegisterModel:
public function rules()
{
return [
['captcha', 'captcha'],
];
}
to solve session problem I used different captcha actions to set different session variables:
1)Login
login modal view:
echo Captcha::widget([
'id' => 'Login-captcha',
'name' => 'LoginModel[captcha]',
'captchaAction' => '/site/captcha-login'
]);
LoginModel :
public function rules()
{
return [
['captcha', 'captcha', 'captchaAction' => 'site/captcha-login',],
];
}
2) Register
register modal (view):
echo Captcha::widget([
'id' => 'register-captcha',
'name' => 'RegisterModel[captcha]',
'captchaAction' => '/site/captcha-register'
]);
RegisterModel:
public function rules()
{
return [
['captcha', 'captcha', 'captchaAction' => 'site/captcha-register',],
];
}
until now everything is ok but when I move sessions from regular php files to database by below config in commponent section of main config file:
'session' => [
'class' => 'yii\web\DbSession',
],
then captchas in the first page load not works and have to refresh them to work correctly.
what is the problem?
Try this, it is for yii1 but you can get the idea, more detail
public function rules()
{
return array(
...
array('verifyCode1', 'captcha', ...
array('verifyCode2', 'verifycaptcha2', ...
);
}
public function verifycaptcha2($attribute, $params)
{
$captcha2 = Yii::app()->getController()->createAction('captcha2nd');
if (!$captcha2->validate($this->verifyCode2, false))
{
$this->addError('verifyCode2', 'invalid captcha.');
}
}
Also see this