creating a form field populated by a relationship in Laravel 4 - laravel

I am trying to build a form for a Happening. The Happening references a Places table by place_id.
e.g. happening "OktoberFest" has a place_id 123 which corresponds in table Places to München
These are the relationships declared in the models:
For model Place:
public function happenings()
{
return $this->hasMany('Happening');
}
For model Happening:
public function place()
{
return $this->belongsTo('Place');
}
model Happening has a place_id field linking it to Place.
I am also using {{Form::model($happening, array('route' => array('happenings.update', $happening->id)...}} as form opening
Problem 1: how to create a {{Form::text('......')}} that will be properly prefilled with München when editing the happening Oktoberfest ?
Problem 2: I was trying to get that field to work as an ajax autosuggest (i.e. starting to pull suggestions from the Places table as soon as 3 characters have been entered). I have checked a few implementations but they don't seem to mix correctly with Problem 1
To try and solve Problem 1, I have tried the solution here
Laravel 4 Form builder Custom Fields Macro
but I was unable to make it work.
Long question, it's my very first on stack overflow, please be patient :)

If a Happening is linked to Place via the column 'place_id' you have to supply an id to save in your model/table.
There are a couple of ways that I can think of:
make a list of availble Places in a radio of select, the name will be 'place_id', the value the id of the Place en something like title for the value.
instead of displaying radio's or a select a textfield with autocomplete is a great solution if you got a lot of places. I won't go into detail how to implement it but the general idea is to autocomplete the typed in placename and on selection of that place to put the id of that place in a hidden field named 'placed_id'
After saving the form save your model with the posted place_id
(and check that id if it's valid and existing, never trust user input )

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

Joomla Component Dynamic Custom Field based on other Field Value

I am creating a new Joomla Component. I am able to create custom fields for the component backend forms - but I am not able to create Dynamic Custom Fields.
What I would like to do is have a field that is dynamical populated based on the value of a previous field. The easiest way to explain this is the simple country,state,city breakdown.
Field 1 = Country
Field 2 = State (Based on what the user selected as as Country in Field 1)
Field 3 = City (Based on what the user selected as State in Field 2)
The fields would of course need to be refreshed, reset as the user picks a different country etc.
The data to populate the fields would also all need to come from a database based on the previous fields value.
I am guessing this needs to be done via ajax or javascript or something? But wondering if there is an official way? Especially since there are database calls involved.
Please let me know if there is anything I can explain better..
David
I ended up just creating text fields but then validating the input to make sure the values added are correct.

How to show data in input field when select data at dropdown in Grocery Crud and Codeigniter

In Grocery Crud and Codeigniter , Basically i want to show data from one table(such as a_tbl) when select data or id_no(id_no will get from a_tbl) in dropdown then Name and current posting data will take in input field from table(such as a_tbl) , Then Designation, Dept and Section will take in input field from three different table (such as desg_tbl, dept_tbl, sect_tbl).
How can i solve it , Please any help me
You can use AJAX.
If you use jquery, you can do something like:
$("#field-ID_No").change(function(){
$.ajax({
'url':'your_controller/get_name_of_id/'+$("#field-ID_No").val(),
'success':function(response){
$("#field-Name").value(response);
}
});
});
Basically, when field-ID_No (the select/combobox) changed, the program will send a request to the server (for example: get_name_of_id/1). Assuming, you have "get_name_of_id" function in the controller that echo-ing a name based on given id, you will get the name as response.
(Sorry if it sounds complicated). And then, the value of field-Name should be changed with that echoed name.
For more information about AJAX and JQuery, you can read https://stackoverflow.com/a/5004276/755319
I have done this what you want, it is really simple complete tutorial is on following link
http://www.grocerycrud.com/forums/topic/1087-updated-24112012-dependent-dropdown-library/
hope you will find it helpful

MCV3: View to edit entity has to hold every column?

I got a silly general question...
If I generate a strongly typed view of an entity and chose "edit" as scaffolding, then the view does contain every column for that table. Changing and saving the values via setting it modifierd and call db.SaveChanges() does work in the controller. So far, so good.
But if I remove just one of that columns inside the view, then saving doesn't work anymore.
Is there a rule describing this? Is it only possible to make view with every column when wanting to save the model later on? I don't want to make 90 of 100 columns "hidden"...
PS: When editing a value in another table which is connected via Foreign Key (like customer.address.STREET) saving also does not work. Does everything of the entity ADDRESS has to be inside the view? I really don't get that.
Besides that: If I create my own ViewModel containing two entities: Do they also have to hold every column of both entities? This would be a whole bunch of traffic...
Answer is: You should not use the .Modified state. Instead using the UpdateModel method works fine without every field.

Model Data Type versus View Control

I have having a little trouble wrapping my head around the design pattern for MVC when the data type of the model property is very different than what I wish to display in a form. I am unsure of where the logic should go.
Realizing that I am not really sure how to ask the question I think I will explain it as a concrete example.
I have a table of Invoices with a second table containing the InvoiceDetails. Each of the InvoiceDetail items has an owner who is responsible for approving the charge. A given invoice has one or more people that will eventually sign off on all the detail rows so the invoice can be approved. The website is being built to provide the approval functionality.
In the database I am storing the employee id of the person who approved the line item. This schema provides me a model with a String property for the Approved column.
However, on the website I wish to provide a CheckBox for the employee to click to indicate they approve the line item.
I guess my question is this -- how do I handle this? The Model being passed to the View has a String property but the form value being passed back to the Controller will be of the CheckBox type. I see two possible ways...
1) Create a new Model object to represent the form fields...say something like FormInvoiceDetails...and have the business logic query the database and then convert the results to the other type. Then after being submitted, the form values need to be converted back so the original Model objects can be updated.
2) Pass the original InvoiceDetails collection to the View and have code there create render the CheckBox based on the value of the String property. I am still not sure how to handle the submission since I still need to map back the form values to the underlying database object.
Maybe there is a third way if not one of these two approaches?
To make the situation a bit more complicated (or maybe it doesn't), I am rendering the form to allow for the editing of multiple rows (i.e. collection).
Thanks for any insight anybody can provide.
You need a ViewModel, like #Justn Niessner suggests.
Your controller loads the complete model from the database, copies just the fields it needs into a ViewModel, and then hands the ViewModel off to the view for rendering.
I'd use Automapper to do the conversion from Model to ViewModel. It automates all the tedious thingA.x = thingY.x; code.
Here is an additional blog post going over in detail the use of ViewModels in the Nerd Dinner sample.
I believe what you are looking for is the ViewModel.
In cases where you are using a ViewModel, you design the ViewModel to match the exact data you need to show on your page.
You then use your Controller to populate and map your data from your Model in to your ViewModel and back again.
The Nerd Dinner ASP.NET MVC Example has some very good examples of using ViewModels.

Resources