Different Value/Default for Property in Model Yii2 - activerecord

I've created an ActiveRecord Model where a user enters their email and gets added to a database in Yii2. When they're added to the database, I want to update one of my properties based on which view they entered the information from. I know Yii2 lets you set a default value in your model, like
public function rules()
{
return [
[['view'], 'default', 'value' => a]
]
}
But I'm not sure how to set a different default value based on each view. In my view where I have the form->field($model, 'email') and submit for user input, I tried setAttribute and setAttributes and creating my own set method, but they all fail to set the property (I'm guessing they'd work if I say queried my db and performed them on an already existing instance of my Model).
I'm sure I'm overlooking something really simple

You shouldn't define default value based on current view, because models (in general) can be used not from views, but form console applications or other places in your code not related to specific view.
As #Patrick said you can add hidden field in each view like:
<?= $form->field($model, 'view')->hiddenInput(['value'=> $this->id /* view id or whatever */])->label(false);

Related

How to use same model with less fields for another view in mvc5

My Question is not belonging to how to use two models on same razor view ! basically I have a user table in which i have fields like(userid,name,email,password,gender,country,department,IsActive) and my form is working fine i am able to insert update and delete i have not use EF , what i did i create the table in sql server and create the model in my model folder , in my view i have put the required field validator for all these columns and they are mandatory to input while inserting or updating.
Now I want to have another view with another controller where i do not want to show all 8 fields instead want to show just these four columns( username,email,gender,IsActive)
when i am using the same model for the other controller and view then it loads the record correctly on index view ,but when i update the required it fires validation error as all my fields are mark as required so it ask to input the rest of four fields value as well.
I have tried to remove these un-necessary fields from model in controller code before saving using Bind([Exclude]"""") but it did not work.
I have tried modelstate.remove("") this approach works fine for all fields but my password field is still throwing validation error . someone says you need to use viewmodel and in viewmodel you have to put both of your model like the full model and small model, I want to ask how my small model would be mapped to my user table (as table["tableName"] this cannot be applied to two models and pointing to same table without primary foriegn key relation .
Share example please i am confused
modelState.Remove("Password")
This remove all model values which are un-necessary but not removing the password field which gives error while updating the
You have required fields missing data or some fields are not null when being saved. What you are trying to do is completely ok. You are basically using a Virtual Model. This is what I do. In the "get", you fix your model and send it to the view. You work with it and then when you submit, you receive the model in the "post", but it is missing several REQUIRED fields. So what you need to do is, retrieve the same record from the database, update the 3 or 4 fields from the view model and then save that model that you retrieved with the new data. This is one way. (VM = view model)
1. send VM to view
2. add data in the view
3. submit
4. receive VM in POST Controller
5. get same record from DB
6. update the particular fields using the VM data
7. save the updated record to database. This is the record you retrieved in 5.
Another way is to have all the missing fields in the model but not showing them in the view. However you need to mention them in the view, otherwise they will not post. so you need to use
#Html.Hidefor( x=> x.NameOfField)
This will ensure that the field is sent back for posting. Any field with a [Required]... is required. You cannot miss it!
How will your small model be mapped to the Database. It will not. You will transfer the data from the small model to the model that is mapped in the database... with ALL the fields. Either you get the missing values from the database or from the view by using Hidefor.
example
dbmodel.Field1 = vm.field1;
dbmodel.Field2 = vm.field2;
dbmodel.Field3 = vm.field3;
I hope this helps

Laravel change stored value of polymorphic relationship

I am trying to make the stored value of a polymorphic relationship more readable by other applications. Currently the polymorphic model type is stored as the FQCN of the model. Using the example in the Laravel Docs, imageable_type could be "App\Product", or "App\Staff". However, this value can be a little more difficult to manage if any non-laravel applications which aren't based on this convention and are also accessing the same database. Also, if the model FQCN ever gets refactored, you have to modify your other applications to account for the change.
Is there a way to change the type to something more consistent and readable, and then have a mapping class that maps the keys to the model? (e.g. have "product" map to "App\Product")
Yes. This is a change that was recently implemented.
Add this to your service provider (in the boot method):
Illuminate\Database\Eloquent\Relations\Relation::morphMap([
'product' => App\Product::class
]);
If you simply pass an array of model names, it'll default to using the table names:
Illuminate\Database\Eloquent\Relations\Relation::morphMap([
App\Product::class,
App\Staff::class,
]);
if you are adding morphMap method to service provider, you might want to use
'product' => \App\Product::class
( "\" before App),otherwise your namespace can be wrong.

Laravel Eager Loading and Form Model Binding

I have a User model and via Eager Loading i am loading also the Table Profile.
To Display it i just write $user->profile->nameOfTheProfilePropertyIWant just as normal.
Simple.
But how exactly do i use Form Model Binding now?
Normal i would use Form::text('nameOfTheUserPropertyIWant') for a User Property like an email. But i want to set in on a Property of the Profile like the location. (profile->location)
But how can i set it to an profile property?
You may do this (in a one-to-one relationship) using something like this:
Form::text('profile[location]')
In this case $user->profile->location will be populated in the given text box if an instance of User model is bound to the from using Form::model($user) with the related model profile.

Cakephp one model different form validation

I have a model name "User", their I added a validation for login. But I need to validate registration page also. Fields for both forms are different.
Can someone please tell me how to manage different form validation with 1 model.
You can validate as many fields as you want inside your User model, it does not matter in which View or in which form you input them.
So just add the fields from your registration page to the User's $validate inside your User model.
If all forms share similar fieldnames but require different validation rules you can use:
http://bakery.cakephp.org/articles/dardosordi/2008/07/29/multivalidatablebehavior-using-many-validation-rulesets-per-model
If the duplicate fields validate the same on all forms you can just add them all to the Model, it will only validate the ones present on the form.
Remember to NOT use 'required' => true, setting this key to true will make the field always required and it has to be present in the data array even if it's not on your form

.NET MVC 3 Validation

I use Entity framework for creating model.
I have table hierarchy where User is my base table and I have tables Lecturer and Student which have some specific data in them. Entity framework made model that it isn't suitable so I made my middle layer called modelview where I have student table which wraps all data from both user and student tables. I have made CRUD functionality for students but I only want that admin can create student with some initial password, than admin should not have option to change student password at Edit action.
The problem is that password is required field at student Create action so I set [Required] attribute to it, but at Edit I must not have password field and my ModelState.IsValid is then always false since password field in this case isn't present and therefore is null.
I thought on adding hidden password field, but that would be very bad since someone could look at page source and see password value.
Can I somehow once this field required and another time not required?
If you have any other idea that might help please share with me.
When a user is being edited, you can put in a placeholder hidden field, with the value * (or something like that). This will satisfy the Required attribute - you just have to make sure you don't update the password when the user is edited :)
Maybe you could randomly generate a password and not have it be required at all.
Or you could remove the requred attribute and manually check if it's present at the serverside.
if (string.IsNullOrEmpty(user.Password))
ModelState.AddModelError("Password","A password is required");
To validate clientside, if you're using jquery validation: JQuery Docs
If you have separate views for Student addition and editing, an alternative solution would be:
Create a StudentViewModel class which contains all the properties required for both Student addition and editing, and
Create a StudentAdditionViewModel class (optionally derived from StudentViewModel) which includes a Password property.
You can then use StudentAdditionViewModel as the Add view's model, and StudentViewModel as the edit view's model :)

Resources