, , , , , , ,

For most content, Sitecore has a dedicated Web Control that renders it: sc:Image, sc:Text, sc:Link, etc. But in many cases, something like sc:Currency would also be very convenient, for the rendering of prices. Sitecore has not yet provided a solution.

The solution at http://deceptacle.com/2011/07/07/sitecore-money-field/ is not sufficient, because it does not have Page Editor support: the output is not editable in the Page Editor. So we have to modify it a bit.

So what we are going to make is a new Web Control, that is able to render field values as currency (prices), and that also supports the Page Editor.
First thing we need is a class that inherits from Sitecore.Web.UI.WebControls.FieldControl. This control has a property “Format”, which determines the format of the rendered field value. We set it default to “C”, in order to render the string as currency. Then we override the methode “DoRender()”, in which we create a RenderFieldResult object. Finally we make some modifications to this object, with the private method “ProcessCurrencyFieldResult()”.
In this private method we check if the page is not in PageEditor mode, and then we write the field value to the page in the desired Format. If the page is in PageEditor mode, then write the original value to the page, without Rounding and Currency sign.
Here is the code:

public class Currency : FieldControl
	public string Format { get; set; }

	public Currency()
		Format = "C";

	protected override void DoRender(HtmlTextWriter output)
		if (string.IsNullOrEmpty(this.Field))
			throw new InvalidOperationException("Field property cannot be null or empty");

		FieldRenderer renderer = new FieldRenderer();
		renderer.Item = this.GetItem();
		renderer.FieldName = this.Field;
		RenderFieldResult result = renderer.RenderField();

		result = ProcessCurrencyFieldResult(result);


	private RenderFieldResult ProcessCurrencyFieldResult(RenderFieldResult renderFieldResult)
		string fieldValue = GetFieldValue(Field);

		double val;
		if (double.TryParse(fieldValue, out val))
			// make sure the page is not in page editor mode)
			if (!Sitecore.Context.PageMode.IsPageEditorEditing)
				renderFieldResult.FirstPart = renderFieldResult.FirstPart.Replace(fieldValue, val.ToString(Format));

		return renderFieldResult;

NB. If you are Dutch (like me) and if you use the Sitecore Field Type ‘Number’ to save price values (like I do), then you’ll notice that Sitecore saves the value of decimal numbers using a period. But the Dutch culture uses a comma for decimal numbers, so you have have to replace all the periods with commmas: .Replace(‘.’, ‘,’);