I am developing a registration form in YII. In my form there is a radio option to choose register as Mode1 or register as Mode2. If user chooses mode1, data's should be entered to table1 or it should entered to table2.
In YII each model deals with one table. Here my form deals with two tables.
So how to handle such a form to validate and enter data's to table in YII?
The easiest way is to create one model for the form (assuming they have the same fields?)
This class would extend CFormModel (in the example below I refer to this model as GlobalFormModel)
This model would have the same attributes as the other two models, as well as one new attribute called mode
When the form is submitted, in the controller you can handle it based on which mode and validate it against the correct model, eg:
$model = new GlobalFormModel
if(isset($_POST['GlobalFormModel'])){
$model->attributes = $_POST['GlobalFormModel'];
if ($model->mode == 1){
$newmodel = new FormOne;
$newmodel->attributes = $model->attributes;
} else {
$newmodel = new FormTwo;
$newmodel->attributes = $model->attributes;
}
... // validate and save $newmodel
}
$this->render("yourview",array("model"=>$model));
Where FormOne is the model associated with the first table, and FormTwo is associated with the second table. First you create a new instance of the GlobalFormModel (which is passed to the view). You check if the form has been submitted (you could validate it here or after loading one of the two models, that is your choice). You check the mode, and then load the correct model.
Related
I have a Resource Controller (with all the actions: index, create, store, show, edit, update and destroy) and I was wondering what is the best approach to edit a single field column?
Let's say we have a Users table with name, email, password and active (active is a tiny int 0 or 1).
In the users management page, there is a button to activate/deactivate users (makes a request to the server to update the "active" field for the selected user).
Should I create a new method updateStatus in the Controller or is there a way to handle this using the update method?
I don't want, by mistake, allow empty values in the name, email or password when updating the "active" column, so I need to keep the validation rules (in short, all fields are required), but this means when updating the "active" field, I need to pass all the user data in the request.
At this point I'm very confused and all help will be appreciated.
Thanks in advance!
When you send an instance from edit action to the form , all the data will be sent and you can edit one or more columns if you need .
For instance :
public function update(Request $request , $id) {
$data = YourModel::find($id);
$data->someColumn = $request->someColumn;
$data->save();
}
other fields that you didn't send any value for them will be saved as they were before . for this you can set the form like below :
{!! Form::model($yourInstance,['route'=>['someRoute.update','id'=>$yourInstance->id],'method'=>'PATCH',]) !!}
It sounds like you are new to Laravel, and some key concepts can be hard to grasp.
In my opinion the best way to do it would be via a Model class. This is slightly confused by the fact that Laravel has a built in Users model, so I'm going to use a different model as the example of how to update a db field.
php artisan make:model MyData
Will create a new empty model file for the MyData table in app/
The file will look like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class MyData extends Model
{
//
}
Even though there's nothing in there, it now allows you do alter the database table using Eloquent.
In your controller add this to make sure the model is included:
use App\MyData as MyData;
The controller should have a method something like this if updating with user input from a form:
public function updateStatus(MyData $myData, Request $request){
$myData->where('id', $request->id)->update(['active' => $request->active]);
}
You could do the exact same thing like this:
public function updateStatus(Request $request){
$data = MyData::find($request->id);
$data->active = $request->active;
$data->save();
}
Both approaches make sense in different circumstances.
See https://laravel.com/docs/5.5/eloquent#updates
i have an issue with access to the id of the ActiveRecord model in Yii2 framework. when i save the model i just created, i cannot acquire the id field of new object.
$house = new House;
$house->save();
$hid = $house->id;
$hid value is empty string ''.
the problem is that i am creating new model, so that i can pass the new id to thread process that is handling file moving while i create db rows. thread starts and after json slicing and array populating, the first insert fail on sql condition (where) statement.
i have researched many answers and they point to several flaws:
assignment of pk - i don't assign the new model id field (db handles the pk autoincrement), i receive the $_post body content through json (json has many fields that are not for bulk assignment into main model, so i deal with slicing the json data before $attibutes insert).
pk in model rules - i don't have id field in model rules array.
fault in the ActiveRecord class - i don't want to hack the base classes of the framework.
later in code i planned to link the models through relations, but i suppose that failed because of this error, so i also use $hid value to populate the foreign key fields in related models.
help. please.
Could be a validation problem try in this way
$house = new House;
if ($house->validate()) {
$house->save();
$hid = $house->id;
} else {
$errors = $house->errors;
var_dump($errors)
}
If you see the result of var_dump the your validation fails (eg: some required fields .. ) and you need change the proper validation rules in your House Model ..
Otherwise you cant try with
$house->save(false); //this way the validation is not executed
(use save(false) only for debugging porpose)
thank you scaisEdge and Alex. i have forgot to check the not null columns of the db. yii2 gii module generated the model according to the db schema and i missed the rules fields of the model. i didn't need validation since i was just generating empty row (just pk).
this is the code that passes:
$house = new House;
$house->name = 'name'; [field set as required in model rules array]
$house->description = 'description'; [field set as required in model rules array]
$house->save();
$hid = $house->id;
convention and configuration, pretty neat.
I'm trying to update a record with the post data from a form. Every time I'm manually assigning the values from the form to the model and saving the record.
$model = CondoFacilities::find($id);
$model->facility_title = Input::get('facility_title');
$model->facility_description = Input::get('facility_description');
$model->facility_image = $imageName;
$status = $model->save();
Is there any way to assign the form data to the model and save/update the record in Laravel ? Similar to the one in YII2:
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$model->save();
}
I'm new to Laravel hope this awesome feature is available in Laravel as well.
Thank you for your help.
In order to create a model and store it in the database, you can use create method directly on the model like so:
YourModel::create($request->all());
where $request->all() is the post request of the form with the values that you wish to create and save it in the database.
Similarly, for updating the model, you need to first find the model:
$model = YourModel::find($id);
where $id is the unsigned integer of the model that you wish to update.
$model->update($request->all());
Of course you can also inline the update method like so:
YourModel::find($id)->update($request->all());
Read more about Eloquent and Requests.
I've created an Employer model in my Laravel 4 application and, in Employer.php I have created the following function to validate user input before saving it to the database:
public static function validate($input)
{
$validator = Validator::make($input, static::$rules);
if ($validator->fails() {
return $validator;
}
return true;
}
This works fine when I'm creating a new record in the database, because I am passing in values for all the rules where I have specified a particular field is required.
However, there are certain fields in the database I don't want the user to edit after they have been created (for example, business_name). On the controller's edit method I create a form and omit those fields from the form. But validation fails because business_name is required by the $rules.
As a temporary work around, I tried just creating a hidden field in the edit form and populating it with the business_name. However, this is also required to be unique and fails when I PATCH my form to the update method!
Any advice? Is there any way I can specify which validation rules should be applied depending on the method calling it? Or should I create a new method in Employer.php specifically to validate on the update method?
You could use the required_without validation rule. Since an newly instantiated model doesn't have an id field yet, you can require some fields only when id is not present. This should work:
public static $rules = array(
'business_name' => 'required_without:id'
);
http://laravel.com/docs/validation#rule-required-without
I have a Profile model with a hasOne relationship to a Detail model. I have a registration form that saves data into both model's tables, but I want the username field from the profile model to be copied over to the
usernamefield in the details model so that each has the same username.
function new_account()
{
if(!empty($this->data))
{
$this->Profile->modified = date("Y-m-d H:i:s");
if($this->Profile->save($this->data))
{
$this->data['Detail']['profile_id'] = $this->Profile->id;
$this->data['Detail']['username'] = $this->Profile->username;
$this->Profile->Detail->save($this->data);
$this->Session->setFlash('Your registration was successful.');
$this->redirect(array('action'=>'index'));
}
}
}
This code in my Profile controller gives me the error:
Undefined property: Profile::$username
Any ideas?
You should be able to simply replace $this->Profile->username with $this->data['Profile']['username'].
You could also store the result of $this->Profile->save($this->data) in a local variable from which you could then extract the username, especially if the username might be altered, for example, in the beforeSave() callback.
The error message you got is normal though. CakePHP does not automatically create properties that correspond to column names.