mcintyre321 / FormFactory

MVC5, Core or standalone - Generate rich HTML5 forms from your ViewModels, or build them programatically
http://formfactoryaspmvc.azurewebsites.net/
MIT License
304 stars 102 forks source link

Question: is there a way to hide a property at runtime? #27

Closed tanis2000 closed 8 years ago

tanis2000 commented 8 years ago

I have a use case where I want to use the same form for both "add" and "update" operations using an EF model.

It works fine as long as I use the DataType attributes to set which properties to show, but what I would like to do is to set one of the property to be shown only in "add" mode and not on "update".

Is there any way to tell FormFactory that kind of information at runtime?

Thanks!

tanis2000 commented 8 years ago

I'm answering my own question but I'm open to suggestions to improve my way, if any :)

I've modified Form.Property.cshtml to have the first few lines to look like this:

  bool IsHiddenOnEdit = false;
  var attrs = Model.GetCustomAttributes().Where(a => a.GetType().Name == "DataTypeAttribute").ToList();
  foreach(var a in attrs)
  {
    DataTypeAttribute dta = (DataTypeAttribute)a;
    if (dta.CustomDataType == "HiddenOnEdit")
    {
      IsHiddenOnEdit = true;
    }
  }
  if (Model.IsHidden || (IsHiddenOnEdit && ViewBag.EditMode == true))
  {
    <div style="display: none">@Html.BestProperty(Model)</div>

And I've annotated the propety with [DataType("HiddenOnEdit")] where needed.

mcintyre321 commented 8 years ago

Glad you managed to get it to work for you!

It would be great to create a base class, so that new attributes wouldn't have to modify the template, and could be added by users without modifying the core.

FormFactory core project:

public abstract class FormFactoryPropertyAttribute : Attribute
{
    public abstract void ApplyToProperty(PropertyVm vm);
}

Form.Property.cshtml

 foreach(var a in attrs.OfType<FormFactoryPropertyAttribute>())
  {
      a.ApplyToProperty(Model, Html);
  }

And then in your project

class IsHiddenOnEdit : FormFactoryPropertyAttribute {

    public override void ApplyToProperty(PropertyVm vm, FfHtmlHelper htmlHelper)
    { 
       if (htmlHelper.ViewData["EditMode"] as bool? ?? false)
           vm.IsHidden = true;
    }
}

I'll add this when I get a chance, but it might not be for a while. If you're up for the challenge, pull requests are gratefully accepted!