How do I store the relation between models in db? - Laravel - eloquent

I have an employees table and a roles table. On the from to create an employee I also wish to assign a role. However my code stores the data with NULL on the foreign key in employees table. How do I make it store the relation?
Employees model.php
class employees extends Model
{
protected $fillable = [
'first_name',
'surname',
];
public function Roles()
{
return $this->belongsTo('App\Roles');
}
Roles model.php
class Roles extends Model
{
protected $fillable = [
'role_name',
];
public function Employees()
{
return $this->hasMany('App\Employees');
}
}`
Controller to create employee
public function store(EmployeesRequest $request)
{
$employee = Employees::find($request);
Employees::create($request->all());
Roles::create($request->all());
$employee->roles()->save($roles);
return redirect()->route('employees.index')->with('message','Employee has been added');
}
On the form I have first_name, surname and role_name. These are saved but with NULL on the role_id column in my employees table? Tried reading the laravel docs but struggling to use ->save method
Current error it is returning is Call to a member function roles() on null

You have to make the role_id fillable in your Employee Model:
protected $fillable = [
'role_id',
'first_name',
'surname',
];
In your Controller:
You need use App\Roles;
public function create()
{
$role = Role::lists('role_name', 'id');
return view('roles.create', compact('role'));
}
public function store(EmployeesRequest $request)
{
Employees::create($request->all());
return redirect()->route('employees.index')->with('message','Employee has been added');
}
Form:
<div class="form-group">
{!! Form::label('role_id', 'Role:') !!}
{!! Form::select('role_id', $role, null, ['class' => 'form-control']) !!}
</div>
HTML-Form:
Try something like this, I hope it works its not tested
<label>Role</label>
<select name="role_id">
#foreach($roles as $role)
<option value="{{ $role->id }}">{{ $role->role_name }}</option>
#endforeach
</select
In your Controller:
public function create()
{
$roles = Role::all();
return view('roles.create', compact('roles'));
}

Related

Insert into DB from ASP.Net form

I have an issue when I want to insert an object into the database.
My model is Colis class which has a foreign key to ZoneReserve (ZoneReserveId), which has a foreign key on Reserve (ReserveId).
In my form I choose an existing ZoneReserve and Reserve, but when I post my form, new lines are created in DB, in table ZoneReserve and Reserve. Entity framework do not retrieve the existing line or I don't know...
I don't know if I'm clear enough, sorry for my english ;)
Do you have any advice ? I'm stuck et I tried everything :(
Thank you guys
Colis Model Class :
public class Colis
{
public int ColisId { get; set; }
[Display(Name = "Code barre du colis")]
public string CodeBarreColis { get; set; }
public bool IndAVendreColis { get; set; }
public virtual TypeColis TypeColis { get; set; }
[Display(Name = "Type de colis")]
public int TypeColisId { get; set; }
public ZoneReserve ZoneReserve { get; set; }
[Display(Name = "Emplacement du colis")]
public int ZoneReserveId { get; set;
}
ZoneReserve Model Class :
public class ZoneReserve
{
public int Id { get; set; }
public string NomZoneReserve { get; set; }
public Reserve Reserve { get; set; }
public int ReserveId { get; set; }
}
Reserve Model Class :
public class Reserve
{
[Display(Name = "Réserve")]
public int Id { get; set; }
public string NomReserve { get; set; }
}
My Action in ColisController :
[HttpPost]
public ActionResult CreerColis(Colis colis)
{
_context.Colis.Add(colis);
_context.SaveChanges();
return RedirectToAction("ListeColis");
}
My Form in the view :
#using (Html.BeginForm("CreerColis", "Colis"))
{
<div class="form-group">
#Html.LabelFor(m => m.Colis.CodeBarreColis)
#Html.TextBoxFor(m => m.Colis.CodeBarreColis, new { #class = "form-control" })
</div>
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.Colis.IndAVendreColis) A vendre ?
</label>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Colis.TypeColisId)
#Html.DropDownListFor(m => m.Colis.TypeColisId, new SelectList(Model.TypeColis, "Id", "NomTypeColis"), "Selectionner un type", new { #class = "form -control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Colis.ZoneReserve.Reserve.Id)
#Html.DropDownListFor(m => m.Colis.ZoneReserve.Reserve.Id, new SelectList(Model.Reserve, "Id", "NomReserve"), "Selectionner une zone", new { #class = "form -control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Colis.ZoneReserveId)
#Html.DropDownListFor(m => m.Colis.ZoneReserve.Id, new SelectList(Model.ZoneReserve, "Id", "NomZoneReserve"), "Selectionner une zone", new { #class = "form -control" })
</div>
<button type="submit" class="bt, btn-primary">Enregistrer</button>
}
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
$("#Colis_ZoneReserve_Reserve_Id").change(function () {
$.get("/ZoneReserve/ListeZoneReserveParReserve", { ReserveId: $("#Colis_ZoneReserve_Reserve_Id").val() }, function (data) {
$("#Colis_ZoneReserve_Id").empty();
$.each(data, function (index, row) {
$("#Colis_ZoneReserve_Id").append("<option value='" + row.Id + "'>" + row.NomZoneReserve+ "</option>")
});
});
})
});
</script>
It looks like your razor page is posting info about navigation properties of the Colis object to the controller and creating the full objects instead of creating a new Colis object with just the int foreign key specified.
As is, when posted, '''colis.ZoneReserve''' is not null nor is '''colis.ZoneReserve.Reserve''' reference which tells entity framework to create those related object as well when you .Add(colis) to the context.
[HttpPost]
public ActionResult CreerColis(Colis colis)
{
_context.Colis.Add(colis);
_context.SaveChanges();
return RedirectToAction("ListeColis");
}
You are POSTing unintended parameters to your controller, specifically '''Colis.ZoneReserve.Id''' and '''Colis.ZoneReserve.Reserve.Id''' as you BOUND TO in your razor page (see comments in code):
<div class="form-group">
#Html.LabelFor(m => m.Colis.ZoneReserve.Reserve.Id)
<!-- DropDownListFor m.Colis.ZoneReserve.ReserveId will send that (navigation path) value to the server. //-->
#Html.DropDownListFor(m => m.Colis.ZoneReserve.Reserve.Id, new SelectList(Model.Reserve, "Id", "NomReserve"), "Selectionner une zone", new { #class = "form -control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Colis.ZoneReserveId)
<!-- DropDownListFor m.Colis.ZoneResearch.Id will send that navigation property to the server //-->
#Html.DropDownListFor(m => m.Colis.ZoneReserve.Id, new SelectList(Model.ZoneReserve, "Id", "NomZoneReserve"), "Selectionner une zone", new { #class = "form -control" })
</div>
To fix your razor page (and not send unintended values to the server)
change the first drop down list for Reserve to NOT be for anything it'll bind to on the server (you don't even need to POST it's value if you can strip it before submit), one way is to change it's name to something meaningless such as "UnnecessaryData" that won't map in the controller when posted (pseudo-code, not tested)
<div class="form-group">
#Html.LabelFor(m => m.Colis.ZoneReserve.Reserve.Id)
#Html.DropDownList(new SelectList(Model.Reserve, "Id", "NomReserve"),
"Selectionner une zone",
new { #class = "form-control", name = "UnnecessaryData" })
</div>
Change the second drop-down-list to map to the correct property on the Colis object, notice all I did was change m => m.Colis.ZoneReserve.Id to the FK property of Colis m => m.Colis.ZoneReserveId:
<div class="form-group">
#Html.LabelFor(m => m.Colis.ZoneReserveId)
#Html.DropDownListFor(m => m.Colis.ZoneReserveId, new SelectList(Model.ZoneReserve, "Id", "NomZoneReserve"), "Selectionner une zone", new { #class = "form -control" })
</div>
When you POST the form, your Colis object in the controller should have a NULL ZoneReserve property and a non-zero ZoneReserveId property - this will prevent the other data records from being created by entity framework.
Note: You can also simply strip the data from the Colis in the POST controller - but that doesn't correct your implementation on the client razor page that's sending unintended structure to the server in the POST method.
Also note: Because you don't validate that the navigation properties of Colis are NULL in the controller, a malicious user COULD create a lot of crap data on the server by POSTing full object tree data that'll be added with the controller method as implemented.

Eloquent Relationship Laravel 5.4

I have three tables as follows users, jobs and job_statuses with the following simple schema.
**Users Table**
id, user_id, email, password
**Jobs Table**
id, user_id, title, description, status_id
**Job_statuses Table**
id, status
I have successfully retrieved a list of Jobs posted by an authorized user using a one-to-many relationship but I can't get hold on the status using the status_id
User Model
public function job(){
return $this->hasMany(Job::class, 'user_id')->take(5);
}
Job Model
public function user() {
return $this->belongsTo(User::class, 'user_id');
}
public function jabstatus() {
return $this->hasOne(JabStatus::class, 'status_id', 'id');
}
Job_Statuses Model
public function statuses() {
return $this->belongsTo(Job::class, 'id', 'status_id');
}
When try doing something like:
#foreach($user->job as $job)
{{$job->statuses->status}}
#endforeach
I get an error from this: {{$job->statuses->status}}
A well explained answer will do, thanks.
Finally was able to get what I wanted.
What I had was a multiple eloquent relationship.
Job Model
public function jobstatus() {
return $this->hasOne(JobStatus::class, 'id');
}
JobStatus Model
public function status() {
return $this->belongsTo(Job::class);
}
Then:
$user = User::with(['profile', 'review', 'job.jobstatus'])->find(Auth::User()->user_id);
return view('user.dashboard', ['user' => $user]);
Then on my View:
#foreach(#$user->job as $job)
{{$jab->jobstatus->status}}
#endforeach

MVC 5 identity how to add to custom user child tables?

I am using a Visual Studio MVC 5 identity user template and am trying to expand the user information by creating a child table with information about Company.
There is a lot to read about how to create this parent/child tables with great examples so that's not the problem. My question is how do I add/remove/change the child tables in a smart and easy way by using the foreign key relationship?
I'm sorry I don't have any code to show right now, but I have used a MVC 5 template and added a virtual ICollection<Company> companies to the applicationUser model and it works great. I just can't figure out how to add the custom data to the child table....
Edit-------------
ApplicationUser model:(Here i use a userData table instead of the Company table i mention in the text)
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
//Create new custom tables
//User information
public virtual ICollection<Table_UserData> UserDatas { get; set; }
public virtual Table_UserData UserData { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
//userIdentity.AddClaim(new Claim("myCustomClaim", "value of claim"));
return userIdentity;
}
}
My table:(Here i use a userData table instead of the Company table i mention in the text)
public class Table_UserData
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Controller(Here i use a userData table instead of the Company table i mention in the text):
public async Task<PartialViewResult> Register(RegisterUserViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email};
var result = await UserManager.CreateAsync(user, model.Password);
var userName = await UserManager.FindByNameAsync(model.UserName);
ApplicationUser userModel = UserManager.FindById(userName.Id);
userModel.UserDatas.Add(new Table_UserData { FirstName = model.FirstName, LastName = model.LastName });
await UserManager.UpdateAsync(userModel);
if (result.Succeeded)
{
ModelState.Clear();
return PartialView(model);
}
AddErrors(result);
}
//Something failed, redisplay form
return PartialView(model);
}
Use a ViewModel.
The following is untested, and just off the top of my head, but something similar should work.
ViewModel:
public class ViewModel
{
public Parent Parent { get; set; }
public Child Child { get; set; }
}
Controller:
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(
[Bind(Prefix = "Parent", Include = "ID,Field1,Field2")]Parent parent,
[Bind(Prefix = "Child", Include = "ID,ParentID,Field1,Field2")]Child child,
)
{
if(ModelState.IsValid)
{
db.Parents.Add(parent);
db.Childen.Add(child);
db.SaveChanges();
}
}
View:
#using ViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div>
#* Parent Properties *#
#Html.LabelFor(model => model.Parent.Field1)
#Html.EditorFor(model => model.Parent.Field1)
#Html.LabelFor(model => model.Parent.Field2)
#Html.EditorFor(model => model.Parent.Field2)
#* Child Properties *#
#Html.HiddenFor(model => model.Child.ParentID)
#Html.LabelFor(model => model.Child.Field1)
#Html.EditorFor(model => model.Child.Field1)
#Html.LabelFor(model => model.Child.Field2)
#Html.EditorFor(model => model.Child.Field2)
</div>
<div>
<input type="submit" value="Create" />
</div>
}
Ok, this answer comes late but it might help others who are learning MVC+EF to solve this issue. My code is tested and it is only a documented effort to demonstrate the solution given by Luke works fine.
For this example I am using MS Sql Server 2012, Visual Studio 2013 Professional edition, MVC 5.
To start, these are my example tables:
CREATE TABLE person(
personId int IDENTITY(1,1) NOT NULL,
personName varchar(15) NOT NULL,
personLastName varchar(15) NOT NULL,
personPhone varchar(10) NULL,
CONSTRAINT PK_person
PRIMARY KEY CLUSTERED (personId ASC)
);
CREATE TABLE pet(
petId int IDENTITY(1,1) NOT NULL,
personId int NOT NULL,
petName varchar(20) NOT NULL,
petType varchar(20) NOT NULL,
CONSTRAINT PK_pet PRIMARY KEY CLUSTERED ([petId] ASC, [personId] ASC),
CONSTRAINT FK_pet_person
FOREIGN KEY(personId)
REFERENCES person (personId)
);
It is a one-to-many relationship using automatically generated key columns (identity). The pet table has a foreign key referencing the person table primary key.
In order to add data to the child table (pet table in this example) I will use a ViewModel class, which will act as model in the View.
Here are the models:
namespace WebApp.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
// The [Table()] attribute is used to map this class to a database table.
// The table name must be written exactly as it is in the database.
[Table("person")]
public partial class person
{
// This attribute was added manually. The scaffolded class did not include it.
// It MUST be indicated that the key column is identity.
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int personId { get; set; }
[Required(ErrorMessage = "First name is required.")]
[StringLength(15)]
[Display(Name="First name")]
public string personName { get; set; }
[Required(ErrorMessage = "Last name is required.")]
[StringLength(15)]
[Display(Name="Last name")]
public string personLastName { get; set; }
[StringLength(10)]
[Display(Name="Phone number")]
public string personPhone { get; set; }
public virtual ICollection<pet> pets { get; set; }
}
}
namespace WebApp.Models
{
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Table("pet")]
public partial class pet
{
[Key, Column(Order = 0)]
// Same thing here: DatabaseGeneratedOption was originally "none"
// It was manually changed to "Identity"
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int petId { get; set; }
// This is the foreign key column
[Key, Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int personId { get; set; }
[Required(ErrorMessage = "Pet name is required.")]
[StringLength(20)]
[Display(Name="Pet name")]
public string petName { get; set; }
[Required(ErrorMessage = "Pet type is required.")]
[StringLength(20)]
[Display(Name="Pet type")]
public string petType { get; set; }
public virtual person person { get; set; }
}
}
This is the ViewModel:
using WebApp.Models;
namespace WebApp.ViewModels
{
public class personPetVM
{
public person persons { get; set; }
public pet pets { get; set; }
}
}
It is simply a class containing two properties, where each property type is a class we defined in the models.
For these classes to communicate with the database we have this context:
namespace WebApp.Models
{
using System.Data.Entity;
public partial class petContext : DbContext
{
// DBConn is defined in the Web.Config file
public petContext()
: base("name=DBConn") {
}
public virtual DbSet<person> people { get; set; }
public virtual DbSet<pet> pets { get; set; }
}
}
This is the controller:
using System.Web.Mvc;
using WebApp.Models;
using WebApp.ViewModels;
namespace WebApp.Controllers
{
public class personController : Controller
{
// Create an instance of the context class to get connected to the Database
petContext db = new petContext();
public ActionResult Index() {
// Create an instance of the ViewModel class
// and pass it to the View as its model.
personPetVM person = new personPetVM();
return View(person);
}
[HttpPost]
[ValidateAntiForgeryToken]
// Because the ViewModel contains the definition of two different classes
// it is imperative to differentiate the properties belonging to each class
// by using the [Bind(Prefix="")] attribute in the action method parameters.
// As you can see, the parameters are instances of the model classes and are
// automatically populated with the values posted on the form.
public ActionResult saveData([Bind(Prefix = "persons")] person Person,
[Bind(Prefix = "pets")] pet Pet) {
try {
// ModelState is a dictionary that contains the state of the model
// and its validation rules.
if (ModelState.IsValid) {
db.people.Add(Person);
db.pets.Add(Pet);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch {
return View();
}
}
}
}
Because our ViewModel class does not have a key column defined, it is not possible for Visual Studio to generate the View automatically for you, so you will have to write it manually:
#model WebApp.ViewModels.personPetVM
#{
ViewBag.Title = "Index";
}
<h2>Pets registry</h2>
#using (Html.BeginForm("saveData", "person", FormMethod.Post)) {
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Person</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.persons.personName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.persons.personName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.persons.personName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.persons.personLastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.persons.personLastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.persons.personLastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.persons.personPhone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.persons.personPhone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.persons.personPhone, "", new { #class = "text-danger" })
</div>
</div>
<h4>Pet</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.pets.petName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.pets.petName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.pets.petName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.pets.petType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.pets.petType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.pets.petType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Please be aware that a prefix is added to all the form generated inputs (id and name). In this particular example, all the inputs have their id composed by the name of the Model name + underscore + input name. For example: "persons_personName".
The input name is generated as Model name + dot + input name. For example: "persons.personName"
The prefix is the way Razor Views assigns values to the database tables participating in the form.
Take this into account if you want to refer to any input id/name using javascript/jQuery, especially if you add a database table field to the form (select, input, etc) by yourself. Make sure to add the respective prefix, as indicated, if you plan to post its value to the controller. If not, the form will not update the database because some input value did not pass the validation rules specified in the model.
So that's it!
I hope this example may help someone wondering how to:
Map model classes to database tables.
Define key columns in the model classes.
Create ViewModels.
Bind values to an action method.
Insert data into single tables.
Insert data into 1-to-many relationships.
Use some common Entity Framework [attributes]
Validate forms in a View.

Html.DropDownListFor() not showing selected value

I must be doing something wrong, searched google and this form, but I can not find it.
I have the following class 'product', generated with EF, representing a database table 'product':
public partial class product
{
public product()
{
this.category = new HashSet<category>();
}
public string name { get; set; }
public string description { get; set; }
public decimal price { get; set; }
public virtual ICollection<category> category { get; set; }
}
I have another class 'category', also generated with EF, representing a database table 'category':
public partial class category
{
public category()
{
this.product = new HashSet<product>();
}
public string name { get; set; }
public virtual ICollection<product> product { get; set; }
}
The two tables in the database have a many to many relation realized by a linked table called product2category which contains a combined PK of category_name and product_name. category_name is a foreign key to [categroy.name]. product_name is a foreign key to [product.name] (category.name is the PK in the category table. product.name is the PK in the product table) I use database first and there is no EF generated class named product2category.
I have an action method:
public ActionResult Edit(string id = null)
{
product product = db.product.Find(id);
if (product == null)
{
return HttpNotFound();
}
IEnumerable<SelectListItem> categoryList = db.category
.ToList()
.Select(o => new SelectListItem() {
Value = o.name,
Text = o.name,
Selected = product.category.FirstOrDefault().name == o.name
}
);
ViewBag.categoryList = categoryList;
return View(product);
}
I inserted a breakpoint and investigated the value of categoryList property. It has 3 results (when expanding the Results View):
false, "Football", "Football"
false, "Baseball", "Baseball"
true, "Tennis", "Tennis"
I have the following view (omitted some HTML for brevity)
<div class="editor-label">
#Html.LabelFor(model => model.category)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.category, (IEnumerable<SelectListItem>)ViewBag.categoryList)
#Html.ValidationMessageFor(model => model.category)
</div>
The view generates the html dropdown list but does not select the "Tennis" value. Or to say, it does not set the selected="selected" attribute at the Tennis option tag(To be sure, I also inserted a breakpoint in the view, to investigate the ViewBag.categoryList property but it gives the same result as in the controller):
<div class="editor-label">
<label for="category">category</label>
</div>
<div class="editor-field">
<select id="category" name="category">
<option value="Baseball">Baseball</option>
<option value="Football">Football</option>
<option value="Tennis">Tennis</option>
</select>
<span class="field-validation-valid" data-valmsg-for="category" data-valmsg-replace="true"></span>
</div>
I cannot find why it doesn't default select the Tennis option.
Second question:
I also cannot edit or create products because the value of the name and id attributes of the html select element. The value is set to "category" but has to be something like category.name is my believe.
I believe you are using SelectListItem wrong
Selected is a boolean value telling that item it is selected.
DropDownListFor should get the selected value in the html, which you are already doing
// Model.Category is giving it the current selected value
#Html.DropDownListFor(model => model.category, (IEnumerable<SelectListItem>)ViewBag.categoryList)
public ActionResult Edit(string id = null)
{
product product = db.product.Find(id);
if (product == null)
{
return HttpNotFound();
}
IEnumerable<SelectListItem> categoryList = db.category
.ToList()
.Select(o => new SelectListItem() {
Value = o.name,
Text = o.name //, REMOVE THE SELECTED LINE
//Selected = product.category.FirstOrDefault().name == o.name
}
);
ViewBag.categoryList = categoryList;
return View(product);
}

Building a form with dynamic widgets

I have 3 classes : Category, Parameter and Product.
Category has a one-to-many relationship with Parameters.
Product has a one-to-many relationship with Category.
Parameters are attributes for a product (color, weight, size,
brand, etc.).
When I select a category and create a new product I want to create a form with these parameters.
How can I do this? Is it possible with symfony form framework?
I hope for your help.
I trying do this something like:
class ProductRepository extends EntityRepository
{
public function getParameters()
{
$em = $this->getEntityManager();
$parameters = $em->getRepository('ShopProductBundle:CatParameter')->findAll();
$data = array();
foreach ($parameters as $k => $value) {
$name = $value->getId();
$data[$name] = array("label" => $value->getName());
}
return $data;
}
}
Form Class
class ProductType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('name', 'text', array('label' => 'Name'));
$data = $options['data'];
foreach($data as $k => $item){
$builder->add((string)$k, 'text', array('label' => $item['label']));
}
}
public function getName()
{
return 'shop_productbundle_categorytype';
}
public function getDefaultOptions(array $options){
return array('data_class' => 'Shop\ProductBundle\Entity\Product');
}
}
And create form in action:
$parameters = $em->getRepository('ShopProductBundle:Product')->getParameters();
$form = $this->createForm(new ProductType(), $parameters);
End have exception:
Expected argument of type "Shop\ProductBundle\Entity\Product", "array"
given
I guess you're getting this exception because in your controller $parameters is not a product.
You should build a new product, and add the parameters to it.
Also please have a look to this article. It deals with a problem similar to yours.
As soon as you have setup data class in your form the only object you can get is it's type.
'data_class' => 'Shop\ProductBundle\Entity\Product'
The way I'm adding multiple parameters to a product entity is a collection of form items:
How to add collection of items
Or maybe you just want to pass parameters like this:
$parameters = $em->getRepository('ShopProductBundle:Product')->getParameters();
$form = $this->createForm(new ProductType(), null, $parameters);
Or if you would like to have an entity:
$form = $this->createForm(new ProductType(), new Product(), $parameters);