before save in Yii2 - php

I have a form with multi-select fields named "city" form in Yii2. When I submit form
the post data show me the following:
$_POST['city'] = array('0'=>'City A','1'=>'City B','2'=>'City C')
But I want to save the array in serialize form like:
a:3:{i:0;s:6:"City A";i:1;s:6:"City B";i:2;s:6:"City C";}
But I don't know how to modify data before save function in Yii2. Followin is my code:
if(Yii::$app->request->post()){
$_POST['Adpackage']['Page'] = serialize($_POST['Adpackage']['Page']);
$_POST['Adpackage']['fixer_type'] = serialize($_POST['Adpackage']['fixer_type']);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model
]);
}
Please help me.
Thanks all for your effort. I have solved the issue. here is the code :
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
$this->Page = serialize($_POST['Adpackage']['Page']);
$this->fixer_type = serialize($_POST['Adpackage']['fixer_type']);
return true;
} else {
return false;
}
}
Just put this code in model and its working

It's because Yii::$app->request->post() is different than $_POST at this stage. Try to change your code to:
$post = Yii::$app->request->post();
$post['Adpackage']['Page'] = serialize($post['Adpackage']['Page']);
$post['Adpackage']['fixer_type'] = serialize($post['Adpackage']['fixer_type']);
$model->load($post);
Update:
Also it would be better to do it on ActiveRecord beforeSave() method.

Related

`Missing required parameter : id` after a successful update

why did I get this bad request (#400) error after submitting my update on my 'news' section :
Missing required parameters: id
This is my update function
php
public function actionUpdate($id)
{
$model = $this->findModel($id);
$oldFile = $model->getImageFile();
$currentImage=$model->image;
if ($model->load(Yii::$app->request->post())) {
// process uploaded image file instance
$image = $model->uploadImage();
// revert back if no valid file instance uploaded
if ($image === false) {
$model->image = $currentImage;
}
if ($model->save()) {
// upload only if valid uploaded file instance found
if ($image !== false && unlink($oldFile)) { // delete old and overwrite
$path = $model->getImageFile();
$image->saveAs($path);
}
return $this->redirect(['view', ['id'=>$model->id,'image'=>$model->image],
]);
}
} else {
return $this->render('update', [
'model'=>$model,
]);
}
}
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
Please note that the updating and uploading image process were actually a success (that's why I didn't show my model's method code that my actionUpdate called). If I go directly to view the recently updated page and view the content, it clearly displays the updated contents along with the image without problem. The error only occurs just right after the update is submitted. I thought I had pass the parameter after the update by this line :
return $this->redirect(['view', ['id'=>$model->id,'image'=>$model->image],
Right before that line I even echo $model->id to test and it echoed out the id.
I've looked for similar problem in StackOverflow and find someone suggested this :
php
if($model->save())
{
$lastInsertID = $model->getPrimaryKey();
return $this->redirect(['view', 'id' => $lastInsertID]);
}
But it didn't work. Any idea?
You should pass URL as flat array:
return $this->redirect(['view', 'id' => $model->id,'image' => $model->image]);

Yii2; code running in "else" block first, and then running code before "if" block?

I'm completely lost as to why this is happening, and it happens about 50% of the time.
I have a check to see if a user exists by email and last name, and if they do, run some code. If the user doesn't exist, then create the user, and then run some code.
I've done various testing with dummy data, and even if a user doesn't exist, it first creates them, but then runs the code in the "if" block.
Here's what I have.
if (User::existsByEmailAndLastName($params->email, $params->lastName)) {
var_dump('user already exists');
} else {
User::createNew($params);
var_dump("Creating a new user...");
}
And here are the respective methods:
public static function existsByEmailAndLastName($email, $lastName) {
return User::find()->where([
'email' => $email,
])->andWhere([
'last_name' => $lastName
])->one();
}
public static function createNew($params) {
$user = new User;
$user->first_name = $params->firstName;
$user->last_name = $params->lastName;
$user->email = $params->email;
$user->address = $params->address;
$user->address_2 = $params->address_2;
$user->city = $params->city;
$user->province = $params->province;
$user->country = $params->country;
$user->phone = $params->phone;
$user->postal_code = $params->postal_code;
return $user->insert();
}
I've tried flushing the cache. I've tried it with raw SQL queries using Yii::$app->db->createCommand(), but nothing seems to be working. I'm totally stumped.
Does anyone know why it would first create the user, and then do the check in the if statement?
Editing with controller code:
public function actionComplete()
{
if (Yii::$app->basket->isEmpty()) {
return $this->redirect('basket', 302);
}
$guest = Yii::$app->request->get('guest');
$params = new CompletePaymentForm;
$post = Yii::$app->request->post();
if ($this->userInfo || $guest) {
if ($params->load($post) && $params->validate()) {
if (!User::isEmailValid($params->email)) {
throw new UserException('Please provide a valid email.');
}
if (!User::existsByEmailAndLastName($params->email, $params->lastName)) {
User::createNew($params);
echo "creating new user";
} else {
echo "user already exists";
}
}
return $this->render('complete', [
'model' => $completeDonationForm
]);
}
return $this->render('complete-login-or-guest');
}
Here's the answer after multiple tries:
Passing an 'ajaxParam' parameters with the ActiveForm widget to define the name of the GET parameter that will be sent if the request is an ajax request. I named my parameter "ajax".
Here's what the beginning of the ActiveForm looks like:
$form = ActiveForm::begin([
'id' => 'complete-form',
'ajaxParam' => 'ajax'
])
And then I added this check in my controller:
if (Yii::$app->request->get('ajax') || Yii::$app->request->isAjax) {
return false;
}
It was an ajax issue, so thanks a bunch to Yupik for pointing me towards it (accepting his answer since it lead me here).
You can put validation like below in your model:
public function rules() { return [ [['email'], 'functionName'], [['lastname'], 'functionforlastName'], ];}
public function functionName($attribute, $params) {
$usercheck=User::find()->where(['email' => $email])->one();
if($usercheck)
{
$this->addError($attribute, 'Email already exists!');
}
}
and create/apply same function for lastname.
put in form fields email and lastname => ['enableAjaxValidation' => true]
In Create function in controller
use yii\web\Response;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post()))
{
//place your code here
}
Add 'enableAjaxValidation' => false to your ActiveForm params in view. It happens because yii sends request to your action to validate this model, but it's not handled before your if statement.

Validating content before save in yii2

I am using yii2 for a weigh bridge project
Upon create, the user is redirected to view but my controller doesn't validate the information in such a way that even if data is not entered in the form fields a user is always redirected to view.
How can I implement the validation property
Controller code:
public function actionCreate()
{
$model = new TruckWeight1();
if ($model->load(Yii::$app->request->post()) ) {
$model->time_recorded =date('H:i:s');;
$model->recorded_by =
$model->recorded_date = date('Y-m-d');
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
try this
public function actionCreate()
{
$model = new TruckWeight1();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->time_recorded =date('H:i:s');;
$model->recorded_by =
$model->recorded_date = date('Y-m-d');
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
for more on validation validation

Yii2 submit data with link

I'm writing simple shopping app and I have some issues with the add to cart link
I'm passing al the same parameter that were on Yii's default Crud form via get and i want to save them in database. Sad thing is when I tried to simply get 'post' to 'get' like this: its not working
if ($model->load(Yii::$app->request->get()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
I think I am missing something very simple but I'm rather new to this so any help will be appreciated.
Oh well i fixed that :D
public function actionCreate()
{
$model = new Koszyk();
$model->setAttributes($_GET);
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
else {
$m =$_GET;
return $this->render('create', [
'model' => $model,'param'=>$m
]);
}
}

Cannot edit particular user data with user id by form using yii framework

I am new in YII framework. I am doing update operation using YII framework. I have controller with name sitecontroller.php, model jobseekerprofile.php, view personal.php.
I got the error:
Fatal error: Call to a member function isAttributeRequired() on a non-object in E:\wamp\www\yii\framework\web\helpers\CHtml.php on line 1414
My table is job_seeker_profile
Fields
1.id
2.user_id
3.contact_no
4.gender
5.dob
6.mstatus
7.address
8.location_id
I want to edit the data in contact_no and address according to user_id
Model-Jobseekerprofile.php - rules
public function rules()
{
return array(
array('contact_no,address','required'),
);
}
controller-Sitecontroller.php
class SiteController extends Controller {
public function actionpersonal()
{
$user_id = trim($_GET['id']);
$model=Jobseekerprofile::model()->find(array(
'select'=>'contact_no,address',"condition"=>"user_id=$user_id",
'limit'=>1,));
$model = Jobseekerprofile::model()->findByPk($user_id);
if(isset($_POST['Jobseekerprofile']))
{
$model->attributes=$_POST['Jobseekerprofile'];
if($model->save())
{
$this->redirect(array('profile','user_id'=>$model->user_id));
}
}
$this->render('personal',array('model' =>$model));
}
}
Anybody help me?
Seems that $model = Jobseekerprofile::model()->findByPk($user_id) is not finding anything, so $model is null, and that is why $model->isAttributeRequired() throws an error. Check your incoming params because of this and check if there a profile with such id (or maybe you should search by attributes instead of by id?).
Besides you can use
public function actionPersonal($id) {
$model = Jobseekerprofile::model()->findByPk($id);
//
}
Instead of
public function actionpersonal() {
$user_id = trim($_GET['id']);
$model = Jobseekerprofile::model()->findByPk($user_id);
//
}
public function actionpersonal() {
$user_id = trim($_GET['id']);
$model = Jobseekerprofile::model()->findByPk($user_id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['Jobseekerprofile']; //post key edited
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
}
First Check what you are getting in $_POST
and if all is ok then try to save like
$model = Jobseekerprofile::model()->findByPk($user_id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['jobseekerprofile'];
$model->contact_no= $_POST['Jobseekerprofile']['contact_no']; //post key edited
$model->address = $_POST['Jobseekerprofile']['address'];
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
if not work then check what model returns
$error=$model->getErrors();
print_r($error);
above code surely gives you idea why it is not saving

Categories