Sunday, January 18, 2015

How to add a new property to Product entity in nopCommerce?

There are many chances we'd like to add some new properties to the existing entity, such as Product or Category. I just learned how to add a new property to the Product entity, and here's how I did it.

I learned from this tutorial from nopCommerce documentation - Updating an existing entity. How to add a new property.

Scenario: I need to add a new CTALink property to the Product entity, and show the link in Product page.

1. Go to Database and add a new column CTALink in Product table.

2. Go to Libraries > Nop.Core > Domain > Catalog > Product.cs
Add this code:
public virtual string CTALink { get; set; }

3. Go to Libraries > Nop.Data > Mapping > Catalog > ProductMap.cs
Add this code:
this.Property(p => p.CTALink).HasMaxLength(500).IsOptional();

4. Go to Presentation > Nop.Admin > Models > Catalog > ProductModel.cs
Add this code:
public string CTALink { get; set; }

5. Go to Presentation > Nop.Admin > Validators > Catalog > ProductValidator.cs
Add this code:
RuleFor(x => x.CTALink).Length(0, 500);

6. Go to Presentation > Nop.Admin > Views > Product >  _CreateOrUpdate.Info.cshtml
Add these codes to where you want to edit the new property:

            @Html.NopLabelFor(model => model.CTALink):
            @Html.EditorFor(model => model.CTALink)
            @Html.ValidationMessageFor(model => model.CTALink)

7. Go to Presentation > Nop.Admin > Controllers > ProductController.cs
Add in these:
Method name: PrepareProductModel()
model.CTALink = product.CTALink;

Method name: Create(ProductModel model, bool continueEditing)
product.CTALink = model.CTALink;

Method name: Edit(ProductModel model, bool continueEditing)
product.CTALink = model.CTALink;

8. To display this on product page.
Go to Presentation > Nop.Web
Copy the ProductTemplate.Simple.cshtml in Product folder into your theme's Views folder.
Add the necessary code to display the new property on the Product page.
@if (!String.IsNullOrEmpty(Model.CTALink))

              Go Get It!

1 comment:

  1. The Admin information worked very well (I was adding a catalog page number) but step 8 kind of left us hanging. Could you please explain adding the new data field information to the front-end product detail page?