Laravel Eager Loading and Form Model Binding - laravel

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.

Related

Different Value/Default for Property in Model Yii2

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);

Spring unmodifiable View-/Display- Object

I want to display data which i am getting from my db in a view. As far as i know, in case i set my objects in the model defined as #ModelAtttibute, the user will be able to manipulate the data. For example: if my model has the attribute "firstname", the user will be able to manipulate the value by accessing the attribute over a get parameter(...?firstname=blabla)
In this case the model attribute is used for displaying data and not for processing user input and accodingly i dont want the user to overwrite values.
Has anyone any solutions/pattern for solving this problem?

ASP.NET MVC 3.0 - Maintain model state

Am new to ASP.NET MVC 3.0. Request expert's view on the below mentioned scenario.
I have a customer details page, where only Name is editable. There are 10 other customer properties that are non editable and displayed using SPAN. When user submits the page, I need to update only the Name.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
Anyone tried caching model (or viewmodel) using session id? Is it a good practice?
You are almost thinking in right direction.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
In Update Method **Load Customer again and update name Only as required and then save
**For 2 reasons
The first and most important rule is 'don't trust user data'. and
Concurrency and to avoid saving old data. See this example
Instead of using Session, I will suggest to use Hidden Field for record LastUpdateDateTime and Customer ID which will be posted back in the model to retrieve record and verify LastUpdatedtime with database record
Tipically, you should use a view model different than the database model. Having said that,in your current case the situation is very simple, submit only the name to the controller and then set the Name property of the object you get from EF with the submitted name.
Caching the view model or the model isn't your concern. The database model caching is handled by EF, your problem is mainly a lack of clear application layering. IN fact I strongly suggest to learn a bit more about the MVC pattern, basic application architecture (2-3 layering) and when and how to use a OR\M (which EF is).
use hidden inputs for other properties in your form. In that way you can get all properties binded to your EF entity and you dont need to get entity again from db.
#Html.DisplayFor(model=>model.x)
#Html.HiddenFor(model=>model.x)
or you can serialize the entity(if you use POCO entities) and set to hidden input. When you post back you should deserialize the entity.
My choice is always first one. :)

How does my MVC controller query one database table before writing to another?

I am working on a custom Joomla MVC component.
My view has a form where the user enters an ID. I have retrieved the ID ($input_id) in the controller. Now I need to query the database to get the name WHERE ID = $input_id, then write the name to a different database table.
Can this all be done within the controller or do I have to pass my variables to the model somehow? Not sure of the correct way to achieve this within the MVC framework.
All data and data manipulation should be done in the model (e.g. model your data). The controller is there to determine the path of execution and which methods should be called (e.g. the manager aka controller determines what needs to be done).
Have a look at this tutorial which will help you understand MVC for Joomla better by taking you through the development of a simple component.

Why Two Classes, View Model and Domain Model?

I know it could be bad to use domain models as view models. If my domain model has a property named IsAdmin and I have a Create controller action to create users, someone could alter my form and get it to POST a IsAdmin=true form value, even if I did not expose such a text field in my view. If I'm using model binding then when I committed my domain model, that person would now be an admin. So the solution becomes exposing just the properties I need in the view model and using a tool like AutoMapper to map the property values of my returning view model object to that of my domain model object. But I read that the bind attribute on a class can be used to instruct the Model Binder which properties it should and shouldn't bind. So what really is the reason for making two separate classes (domain model and view model) that essential represent the same thing and then incure overhead in mapping them? Is it more a code organization issue and if so, how am I benefiting?
EDIT
One of the most important reasons I've come across for a View Model that's separate from the Domain Model is the need to implement the MVVM pattern (based on Martin Fowler's PM pattern) for managing complex UIs.
I have found that while my domain model gets me 85% of the way to having the fields I want, it has never covered 100% of the values I want on my view. Especially when it comes to permissions and whether or not a user should have access to certain portions of the view.
The design concept I attempt to follow is to have as little logic in my views as possible. This means I have fields in my view model like "CanViewThisField" or "CanEditThisField." When I first started with MVC I would have my domain model be my view model and I was always running into the scenario where I needed just one or two more fields to make my view less cluttered. I've since gone the View Model/Model Builder route and it has worked wonderfully for me. I don't battle my code any longer but am able to enhance my view model as I need to without affecting the domain model.
Another good reason to have a ViewModel is paging large sets of data. You could pass the view an array of Person ( Person[] ) but metadata such as the number of pages, the number of the current page, the size of the page would not belong on the Person class.
Therefore a PersonListViewModel would solve this issue.
A ViewModel holds only those members which are required by the View. They can usually be thought of as a simplification or a "flattening" of the underlying domain model.
Think of them like this:
ViewModel: this is the data that is appropriate to render on this
view
Domain model: this is all the information my application needs
about this entity in order to perform all it's functionality
For example, my Order class has a member called Customer which is a composition association, that is, my Order has a Customer. This Customer object has members such as Firstname, Lastname, etc... But how would I show this on a "details" view of the order or a list of Orders and the Customers who placed them?
Well, using a ViewModel I can have an OrderListItemViewModel which has a CustomerName member and I can map the combination of Firstname and Lastname from the Customer object to this. This can be done manually, or much preferably using Automapper or similar.
Using this approach, you can have multiple Order ViewModels that are specific to different views, e.g. the Order list view might render the customer name in a different way to the Order details view.
Another advantage of ViewModels is that you can cut down on extraneous data not required of the underlying domain object on a view, e.g. if I'm viewing a list of orders, do I really want to see all the customer's contact information, billing details, etc...? I guess that depends on the purpose of the list but, probably not.
Sometimes you need to display the data in a specific manner (ie, displaying a date in the format mm/dd/yyyy vs. yyyy/mm/dd) and often it is easier to make this property in the view and not in the domain model, where you would (or should) have a mapping to a column in your db.
you need to remember
that your domain model classes are only used internally; that is, they are never sent to the
client. That’s what your service model types (View Model types) are used for—they represent the data that will be going back and forth between the client and your service.

Resources