Search code examples
orchardcmsorchardcms-1.6

Sort a query using view counter


I want to make a projection that sort some pages depending on the user view count. So i have installed the voting module and then the content view counter module.I 've enabled the later and i 've managed to display the view counter in every page.But when i m trying to make a query that sorts based on the number of view counts there isn't such a parameter in query list. So how can i sort a query based on the number of view counts?Is there any way to make view counts sortable?

P.S My first thought is to add a new field to my pages with the value of the view counter.


Solution

  • In order to be able to sort a query by TotalViews we have to modify some code parts inside the content view counter module.

    1)Modify the Models

    public class UserViewRecord : ContentPartRecord
    {
        public virtual int TotalViews { get; set; }
    }
    
    public class UserViewPart : ContentPart<UserViewRecord>
    {
        [Required]
        public int TotalViews
        {
            get { return Record.TotalViews; }
            set { Record.TotalViews = value; }
        }
    }
    

    Actually we create a table when we can store the total views.So we have to follow 2 more steps

    2)Add some code to migration.cs

    public int UpdateFrom2() {
    
            SchemaBuilder.CreateTable("UserViewRecord", table => table
              .ContentPartRecord()
              .Column("TotalViews", DbType.Int32)
          );
    
            ContentDefinitionManager.AlterPartDefinition(
                typeof(UserViewPart).Name, cfg => cfg.Attachable());
    
            return 3;
        }
    

    3)Modify our handler class to specify that an IRepository of UserViewRecord should be used as the storage for this part.

     public UserViewPartHandler(IVotingService votingService,
            IOrchardServices orchardServices, IRepository<UserViewRecord> repository)
        {
            _votingService = votingService;
            _orchardServices = orchardServices;
            Filters.Add(StorageFilter.For(repository)); 
            //more code
            //more code
    
         }
    

    After all, as Bertrand Le Roy said, we can add a binding for the TotalViews property and use TotalViews as a sorting criterion.