Customer Custom Attributes

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
7 years ago
Is there an easy way to get the values of a customer's custom attribute?  In following routine I see customer object, I am trying to figure out how to get customer attribute values using this object.  Any help will be appreciated.  It looks like I can't use customer.GetAttribute method in this area.


public virtual decimal GetUnitPrice(Product product,
            Customer customer,
            ShoppingCartType shoppingCartType,
            int quantity,
            string attributesXml,
            decimal customerEnteredPrice,
            DateTime? rentalStartDate, DateTime? rentalEndDate,
            bool includeDiscounts,
            out decimal discountAmount,
            out Discount appliedDiscount)
7 years ago
To use GetAttribute extension method, add

using Nop.Services.Common;
5 years ago
If using nopCommerce 4.1, this method should help.

Make sure your controller or class uses dependency injection to get the customerModelFactory.


/// <summary>
/// Get's the value of a custom customer attribute
/// </summary>
/// <param name="nopCustomer"></param>
/// <param name="attributeName"></param>
/// <returns></returns>
private string getCustomCustomerAttribute(ICustomerModelFactory customerModelFactory, Nop.Core.Domain.Customers.Customer nopCustomer, string attributeName)
{
  string value = string.Empty;

  var model = customerModelFactory.PrepareCustomerModel(null, nopCustomer);

  var accountAttribute = model.CustomerAttributes.Where(attrib => attrib.Name.ToLower() == attributeName.ToLower()).FirstOrDefault();

  if (accountAttribute != null)
  {
    value = accountAttribute.DefaultValue;
  }

  return value;
}



Example of getting customerModelFactory


using Nop.Web.Framework.Controllers;
using Nop.Web.Areas.Admin.Factories;

namespace Nop.Plugin.MyPlugin
{
  class MyPlugin : BasePluginController
  {
    private readonly ICustomerModelFactory _customerModelFactory;
    
    /// <summary>
        /// Use dependency injection to parameters
        /// </summary>
        /// <param name="customerModelFactory"></param>
        public MyPlugin(ICustomerModelFactory customerModelFactory)
    {
      this._customerModelFactory = customerModelFactory;
    }
  
    public IActionResult Index()
    {
      // just a stub, doesn't actually work
      var customer = getCurrentCustomer();
      
      string customerHeight = getCustomCustomerAttribute(this._customerModelFactory, customer, "height");
      
      return Json(new
      {
        height = customerHeight
      });
    
    }
  
  }


}
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.