How Add Search Filter In Home Page Of NopCommerce


In NopCommerce there is no by default feature to search a product under a specific category .So you either use a  pluggin or your own custom code to achive this functionality.This post will help you to add a filter search in nopcommerce 3.7

Step 1 : Add following code in

Presentation\Nop.Web\Views\Home\Index.cshtml


@Html.Action("SearchBox_Filter","Catalog")

Step 2:

Add the following action method in
Presentation\Nop.Web\Controllers\CatalogController.cs
(after SearchBox() action )


[ChildActionOnly] public ActionResult SearchBox_filter() { var model = new SearchBoxModel { AutoCompleteEnabled = _catalogSettings.ProductSearchAutoCompleteEnabled, ShowProductImagesInSearchAutoComplete = _catalogSettings.ShowProductImagesInSearchAutoComplete, SearchTermMinimumLength = _catalogSettings.ProductSearchTermMinimumLength, Categories = _categoryService.GetAllCategories(),

 

};

 

return PartialView(model);

 

}

 
Step 3:

Create a new view named SearchBox_filter.cshtml by coping Presentation\Nop.Web\Views\Catalog\SearchBox.cshtml with following code.(little modification from SearchBox.cshtml)



@model SearchBoxModel
@using Nop.Web.Models.Catalog;

@using (Html.BeginRouteForm("ProductSearch_filter", FormMethod.Get, new { id = "small-search-box-form" }))
{

<input type="text" class="search-box-text" id="small-searchterms" autocomplete="off" name="q" placeholder="@T("Search.SearchBox.Tooltip")" />
<select name="cid" id="caterory-select" style="width:150px;">
<option selected value="0">All</option>
@foreach (var item in Model.Categories)
{
if (item.ParentCategoryId == 0)
{
<option value="@item.Id">@item.Name</option>

}
}
</select>

@[email protected]("searchbox_before_search_button")*@

<input type="submit" class="button-1 search-box-button" style="border: none;padding: 0 15px;text-transform: uppercase;min-width: 86px;height: 36px;text-align: center;background-color: #4ab2f1;color: #fff;float:right;width:170px;" value="@T("Search.Button")" />

if (Model.SearchTermMinimumLength > 0)
{
<script type="text/javascript">

$("#small-search-box-form").submit(function(event) {
if ($("#small-searchterms").val() == "") {
alert([email protected](HttpUtility.JavaScriptStringEncode(T("Search.EnterSearchTerms").Text))');
$("#small-searchterms").focus();
event.preventDefault();
}
});

</script>

}
sif (Model.AutoCompleteEnabled)
{
<text>
<script type="text/javascript">

function toUpper(mystring) {
var sp = mystring.split('');
var wl=0;
var f ,r;
var word = new Array();
for (i = 0 ; i < sp.length ; i ++ ) { f = sp[i].substring(0,1).toUpperCase(); r = sp[i].substring(1); word[i] = f+r; } newstring = word.join(' '); document.getElementById('keyword').value = newstring; return true; }

$(document).ready(function () {

$('#city').autocomplete({

delay: 500,

minLength: 3,

//CitySearchAutoComplete

@*source: '@(Url.RouteUrl("ProductSearchAutoComplete"))',*@

@*source: '@(Url.RouteUrl("CitySearchAutoComplete"))',*@

@*source: [email protected]("SearchTermAutoComplete", "Catelog")',*@

//appendTo: '.search-box',

select: function (event, ui) {

$("#city").val(ui.item.label);

return false;
}

});
@*.data("#city")._renderItem = function (ul, item) {
var t = item.label;
//html encode
t = htmlEncode(t);
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>@(Model.ShowProductImagesInSearchAutoComplete ? Html.Raw("<img src='\" + item.productpictureurl + \"'>") : null)<span>" + t + "</span></a>")
.appendTo(ul);
};*@

});

</script>

</text>
}
@Html.Widget("searchbox")
}
<script>

function initialize() {

var options = {
types: ['(cities)'],
componentRestrictions: {country: "us"}
};

var input = document.getElementById('city');
var autocomplete = new google.maps.places.Autocomplete(input, options);
}

</script></code>

Step 4:  Add the Search_filter() action with following code in

presentation\nop.web\controllers\catalogcontroller.cs

<code>

[NopHttpsRequirement(SslRequirement.No)] [ValidateInput(false)] public ActionResult Search_filter(SearchModel model, CatalogPagingFilteringModel command) {

//’Continue shopping’ URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false), _storeContext.CurrentStore.Id);

 

if (model == null) model = new SearchModel();

 

var searchTerms = model.q; if (searchTerms == null) searchTerms = “”; searchTerms = searchTerms.Trim();

 

//sorting PrepareSortingOptions(model.PagingFilteringContext, command); //view mode PrepareViewModes(model.PagingFilteringContext, command); //page size PreparePageSizeOptions(model.PagingFilteringContext, command, _catalogSettings.SearchPageAllowCustomersToSelectPageSize, _catalogSettings.SearchPagePageSizeOptions, _catalogSettings.SearchPageProductsPerPage);

 

string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY, _workContext.WorkingLanguage.Id, string.Join(“,”, _workContext.CurrentCustomer.GetCustomerRoleIds()), _storeContext.CurrentStore.Id); var categories = _cacheManager.Get(cacheKey, () => { var categoriesModel = new List<SearchModel.CategoryModel>(); //all categories var allCategories = _categoryService.GetAllCategories(storeId: _storeContext.CurrentStore.Id); foreach (var c in allCategories) { //generate full category name (breadcrumb) string categoryBreadcrumb = “”; var breadcrumb = c.GetCategoryBreadCrumb(allCategories, _aclService, _storeMappingService); for (int i = 0; i <= breadcrumb.Count – 1; i++) { categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name); if (i != breadcrumb.Count – 1) categoryBreadcrumb += ” >> “; } categoriesModel.Add(new SearchModel.CategoryModel { Id = c.Id, Breadcrumb = categoryBreadcrumb }); } return categoriesModel; }); if (categories.Any()) { //first empty entry model.AvailableCategories.Add(new SelectListItem { Value = “0”, Text = _localizationService.GetResource(“Common.All”) }); //all other categories foreach (var c in categories) { model.AvailableCategories.Add(new SelectListItem { Value = c.Id.ToString(), Text = c.Breadcrumb, Selected = model.cid == c.Id }); } }

 

var manufacturers = _manufacturerService.GetAllManufacturers(storeId: _storeContext.CurrentStore.Id); if (manufacturers.Any()) { model.AvailableManufacturers.Add(new SelectListItem { Value = “0”, Text = _localizationService.GetResource(“Common.All”) }); foreach (var m in manufacturers) model.AvailableManufacturers.Add(new SelectListItem { Value = m.Id.ToString(), Text = m.GetLocalized(x => x.Name), Selected = model.mid == m.Id }); }

 

model.asv = _vendorSettings.AllowSearchByVendor; if (model.asv) { var vendors = _vendorService.GetAllVendors(); if (vendors.Any()) { model.AvailableVendors.Add(new SelectListItem { Value = “0”, Text = _localizationService.GetResource(“Common.All”) });

 

foreach (var vendor in vendors)

 

model.AvailableVendors.Add(new SelectListItem { Value = vendor.Id.ToString(), Text = vendor.GetLocalized(x => x.Name), Selected = model.vid == vendor.Id }); } }

 

IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1);

 

// only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)

 

if (Request.Params[“q”] != null) {

 

if (searchTerms.Length<_catalogSettings.ProductSearchTermMinimumLength) { // model.Warning = string.Format(_localizationService.GetResource(“Search.SearchTermMinimumLengthIsNCharacters”), _catalogSettings.ProductSearchTermMinimumLength);

 

var categoryIds = new List<int>(); int manufacturerId = 0; decimal? minPriceConverted = null; decimal? maxPriceConverted = null; bool searchInDescriptions = false; int vendorId = 0; if (model.adv) { //advanced search var categoryId = model.cid;

 

if (categoryId > 0) { categoryIds.Add(categoryId); if (model.isc) { //include subcategories categoryIds.AddRange(GetChildCategoryIds(categoryId)); } }

 

manufacturerId = model.mid;

 

//min price if (!string.IsNullOrEmpty(model.pf)) { decimal minPrice; if (decimal.TryParse(model.pf, out minPrice)) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency); } //max price if (!string.IsNullOrEmpty(model.pt)) { decimal maxPrice; if (decimal.TryParse(model.pt, out maxPrice)) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency); }

 

if (model.asv) vendorId = model.vid;

 

searchInDescriptions = model.sid; } else { //simple search var categoryId = model.cid;

 

if (categoryId > 0) {

 

categoryIds.Add(categoryId); if (model.isc) { //include subcategories categoryIds.AddRange(GetChildCategoryIds(categoryId)); } } else { var cats = _categoryService.GetAllCategories();

 

foreach (Category cat in cats) { categoryIds.Add(cat.Id); }

 

}

 

}

 

//var searchInProductTags = false; var searchInProductTags = searchInDescriptions;

 

//products products = _productService.SearchProducts( categoryIds: categoryIds, manufacturerId: manufacturerId, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, priceMin: minPriceConverted, priceMax: maxPriceConverted, //keywords: searchTerms, searchDescriptions: searchInDescriptions, searchProductTags: searchInProductTags, languageId: _workContext.WorkingLanguage.Id, orderBy: (ProductSortingEnum)command.OrderBy, pageIndex: command.PageNumber – 1, pageSize: command.PageSize, vendorId: vendorId);

 

model.Products = PrepareProductOverviewModels(products).ToList(); model.NoResults = !model.Products.Any();

 

//search term statistics if (!String.IsNullOrEmpty(searchTerms)) { var searchTerm = _searchTermService.GetSearchTermByKeyword(searchTerms, _storeContext.CurrentStore.Id); if (searchTerm != null) { searchTerm.Count++; _searchTermService.UpdateSearchTerm(searchTerm); } else { searchTerm = new SearchTerm { Keyword = searchTerms, StoreId = _storeContext.CurrentStore.Id, Count = 1 }; _searchTermService.InsertSearchTerm(searchTerm); } }

 

//event _eventPublisher.Publish(new ProductSearchEvent { SearchTerm = searchTerms, SearchInDescriptions = searchInDescriptions, CategoryIds = categoryIds, ManufacturerId = manufacturerId, WorkingLanguageId = _workContext.WorkingLanguage.Id, VendorId = vendorId });

 

} else {

 

var categoryIds = new List<int>(); int manufacturerId = 0; decimal? minPriceConverted = null; decimal? maxPriceConverted = null; bool searchInDescriptions = false; int vendorId = 0; if (model.adv) { //advanced search var categoryId = model.cid; if (categoryId > 0) { categoryIds.Add(categoryId); if (model.isc) { //include subcategories categoryIds.AddRange(GetChildCategoryIds(categoryId)); } }

 

manufacturerId = model.mid;

 

//min price if (!string.IsNullOrEmpty(model.pf)) { decimal minPrice; if (decimal.TryParse(model.pf, out minPrice)) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency); } //max price if (!string.IsNullOrEmpty(model.pt)) { decimal maxPrice; if (decimal.TryParse(model.pt, out maxPrice)) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency); }

 

if (model.asv) vendorId = model.vid;

 

searchInDescriptions = model.sid; } else {

 

//simple search var categoryId = model.cid;

 

if (categoryId > 0) { categoryIds.Add(categoryId); if (model.isc) { //include subcategories categoryIds.AddRange(GetChildCategoryIds(categoryId)); } } }

 

//var searchInProductTags = false; var searchInProductTags = searchInDescriptions; categoryIds.Add(model.cid); //products products = _productService.SearchProducts( categoryIds: categoryIds, manufacturerId: manufacturerId, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, priceMin: minPriceConverted, priceMax: maxPriceConverted, keywords: searchTerms, searchDescriptions: searchInDescriptions, searchProductTags: searchInProductTags, languageId: _workContext.WorkingLanguage.Id, orderBy: (ProductSortingEnum)command.OrderBy, pageIndex: command.PageNumber – 1, pageSize: command.PageSize, vendorId: vendorId);

 

model.Products = PrepareProductOverviewModels(products).ToList(); model.NoResults = !model.Products.Any();

 

//search term statistics if (!String.IsNullOrEmpty(searchTerms)) { var searchTerm = _searchTermService.GetSearchTermByKeyword(searchTerms, _storeContext.CurrentStore.Id); if (searchTerm != null) { searchTerm.Count++; _searchTermService.UpdateSearchTerm(searchTerm); } else { searchTerm = new SearchTerm { Keyword = searchTerms, StoreId = _storeContext.CurrentStore.Id, Count = 1 }; _searchTermService.InsertSearchTerm(searchTerm); } }

 

//event _eventPublisher.Publish(new ProductSearchEvent { SearchTerm = searchTerms, SearchInDescriptions = searchInDescriptions, CategoryIds = categoryIds, ManufacturerId = manufacturerId, WorkingLanguageId = _workContext.WorkingLanguage.Id, VendorId = vendorId }); } } model.PagingFilteringContext.LoadPagedList(products); return View(model); }</code>

 

 

Step 5:Add the following code in presentation\nop.web\infrastructure\routeprovider.cs

 

<code> //product search filter routes.MapLocalizedRoute(“ProductSearch_filter”, “search/”, new { controller = “Catalog”, action = “Search” }, new[] { “Nop.Web.Controllers” });</code>

 

Comments

comments

1 Comment

  • nopdotnet
    March 29, 2017 at 12:24 pm

    ass

LEAVE A COMMENT