I'm trying to create a custom field type in Contour (3.0.14) using razor to do the rendering. I created a new class called CustomTextfield
with an extra Width
attribute, then a new view in ~/umbraco/Plugins/umbracoContour/Views
called Fieldtype.customtextfield.cshtml
. What I need to know is: how do I access the Width
property from the custom view?
Here's my code:
CustomTextfield.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Forms.Core;
using System.Web.UI.WebControls;
namespace Custom.FieldType {
public class CustomTextfield : Umbraco.Forms.Core.FieldType {
public CustomTextfield() {
//Provider
this.Id = new Guid("b994bc8b-2c65-461d-bfba-43c4b3bd2915");
this.Name = "Custom Textfield";
this.Description = "Renders a html input fieldKey"; //FieldType
this.Icon = "textfield.png";
}
public System.Web.UI.WebControls.TextBox tb;
public List<Object> _value;
[Umbraco.Forms.Core.Attributes.Setting("Width", description = "Enter the width of the Textfield")]
public string Width { get; set; }
public override WebControl Editor {
get {
tb.TextMode = System.Web.UI.WebControls.TextBoxMode.SingleLine;
tb.CssClass = "text";
if (!string.IsNullOrEmpty(this.Width)) {
int width;
if (Int32.TryParse(this.Width, out width)) {
tb.Width = width;
}
}
if (_value.Count > 0)
tb.Text = _value[0].ToString();
return tb;
}
set { base.Editor = value; }
}
public override List<Object> Values {
get {
if (tb.Text != "") {
_value.Clear();
_value.Add(tb.Text);
}
return _value;
}
set { _value = value; }
}
public override string RenderPreview() {
return
"<input type=\"text\" id=\"text-content\" class=\"text\" maxlength=\"500\" style=\"" + this.Width + "px\" />";
}
public override string RenderPreviewWithPrevalues(List<object> prevalues) {
return RenderPreview();
}
public override bool SupportsRegex {
get { return true; }
}
}
}
Fieldtype.customtextfield.cshtml:
@model Umbraco.Forms.Mvc.Models.FieldViewModel
<input type="text" name="@Model.Name" id="@Model.Id" class="text" value="@Model.Value" maxlength="500"
style="@{if(!string.IsNullOrEmpty(Model.Width)){<text>width:@(Model.Width)px; </text>}}"
@{if(Model.Mandatory || Model.Validate){<text>data-val="true"</text>}}
@{if (Model.Mandatory) {<text> data-val-required="@Model.RequiredErrorMessage"</text>}}
@{if (Model.Validate) {<text> data-val-regex="@Model.InvalidErrorMessage" data-regex="@Model.Regex"</text>}}
/>
The code for the view doesn't work because I'm trying to reference the non-existent Width
property. I couldn't find any examples of custom field types with custom properties using razor. If anyone could point me in the right direction, I'd be grateful.
I found the solution for this. It turns out
FieldViewModel
has anAdditionalSettings
attribute which is of typeList<FieldSettingViewModel>
which consists of a stringKey
andValue
To get my above example to work, I can use the following: