Whats the approach for this simple module?

Topics: Writing modules
May 1, 2011 at 8:37 AM

Hi, im burning my head with this right now so i proceed to ask you all.

Im trying to write a simple module that displays a random string each time it is loaded in the site. Strings are randomly picked from the database. It must work as a widget and end-user should be able to add/delete strings from the admin's panel.

I have thought of creating a module and then having a field String to map another class, String. This class holds the required string. But im unsure about how would the user approach then to add/delete strings from the administration. Any suggestions for the general idea? Thanks.

May 1, 2011 at 5:43 PM

I'd make it so it selects a random content item of a specific type (and has a setting so you can configure which type you want to display).

Then you can just use the BodyPart on that item to write the string (which will mean you can also use HTML markup in it, and flexibly add other parts to the content if you ever want that further down the line) - and just use IContentManager methods to display the content.

The only trick then is actually performing the random DB choice; you could always just load in the entire lot and pick randomly from the list but this wouldn't be very efficient if you had a lot of choose from. DB randomness is possible but it's a bit tricky in MS SQL whichever route you go down. When I did it for a previous project I had to create a random function, then a view of that function, then perform a join from the source table to that view, order by the random field and take the first result. But I don't know exactly how you'd get that running in Fluent NHibernate with migrations etc. I could do with this myself at some point so if you find out any more it'd be great if you let me know!

May 1, 2011 at 11:35 PM

Hi,

Thanks in advance to you for all this, i have seen many answers from you and i appreciate your time. 

I have worked this day with the module, and i got the following:

My module is now ready to show a String, and in the editor view i'm able to select which string to render. This is cool until now. Step further would be to retrieve the full list of Strings (the String ContentItems) when im populating the the object (i guess it shoudl be in the SET method of the ContentPart right? How would i access to the database and get the records?? Im reading an example where, INSIDE A VIEW, they do:

Model.Customers
			.Where(c => c.Id != Model.CustomerId)
			.Select(c => new SelectListItem {
				Selected = c.Id == Model.SponsorId,
				Text = c.Name,
				Value = c.Id.ToString()
			}) [...]

 

If i include something similar in my SET method in the ContentPart class, and then i pick one Item at random, that would work? And would it be the right approach?

Thanks