Make regular expression field optional which is displayed as mandatory field in MVC 4 - regex

I'm working on ASP.NET MVC 4. I'm using Data Annotations in model for validation.
There is one field name Mobile and validating using regular expression like below.
[RegularExpression(#"[0-9]{10}", ErrorMessage = "Mobile Number is Not Valid")]
public string Mobile { get; set; }
As per the application requirement above field is not mandatory but need to validate Mobile number if user insert it.
My problem is that when I submit form it displays "Mobile field is required." but the mobile field is not decorate with [Required] attribute. So How it display as required?
What could be the reason?
How to solve it?

In your project, there is a folder "views" where you probably created your view with your needed controls.
there should be something like:
#Html.LabelFor(m => m.Mobile)<br />
#Html.TextBoxFor(m => m.Mobile)<br />
in order to make the regularExpression work.
If you already did this, another problem could be your model.
At the top of your view you should add your model by:
#model yourModelName

As you did not post any code in you controller, Index is assumed as action of your controller and MyModel is assumed as model.
Try the following code in your controller:
public ActionResult Index(MyModel model)
{
//This will check if `Mobile` is empty and remove the Mobile from validation if the field is empty
if (collection.Get("Mobile") == "") //Mobile is the name of the Mobile number field in view
{
ModelState.Remove("Mobile");
}
if(ModelState.IsValid){
//do something
}
else{
return View(model);
}
}
Hope it helps

You can do it very easily using following simple jQuery..
//Remove Required field validation on pin and mobile number
$(document).ready(function () {
$("#Mobile").removeAttr("data-val");
});
Pls try and let me us know if that works for you or not.
Thanks

Related

How to make Date Editable while using Glass mapper

Today i am facing one issue which has following requirement.
Date should be Editable.
Date should be in particular format.
My Code is like below which is not working.
foreach(var item in Model)
{
<div>#Editable(item, x => x.Start_Date.ToString("MMMM dd,yyyy"))</div>
}
I have tried following approach but throwing "DateParameters" namespace error.
#Editable(item, x=> x.Start_Date, new DateParameters { Format = "MMMM dd,yyyy"})
Also i have learner following thing but how can i achieve this ?
To make a field editable takes two parameters, this has been used to make the Date field editable. The first parameter instructs Glass.Mapper which field to make editable, the second parameter then specifies what the output should be when the page is not in page editing mode. This allows you to control the output of the field when in the two different modes.
Can anybody help me ?
For Experience editor mode, this works for me in razor view:
#Editable(model => model.SomeDateField, new { Format = "dd-MM-yyyy" })
Sitecore 8.2 though, with Glass 4.4.
What you want to do is to provide the default format but keep things the same for the main glass stuff. Like so:
foreach(var item in Model)
{
<div>#Editable(item, x => x.Start_Date, x=>x.Start_Date.ToString("MMMM dd,yyyy"))</div>
}
This will make the date a normal date when editing, but allow you to format it for the final page.
Usually in this case i use different code for "Normal View" and "Experience Editor", so for normal view you need only to display the date with format without making it editable, and on experience editor you need only to edit the date field the author will not care about the date format with experience editor, so your code will be like this :
foreach(var item in Model)
{
{
#if (Sitecore.Context.PageMode.IsExperienceEditorEditing)
{
<div>#Editable(item, x => x.Start_Date)</div>
}
else
{
<div>#item.Start_Date.ToString("MMMM dd,yyyy")</div>
}
}
}
I have tried that as well but it is throwing an error like below
**Value cannot be null. Parameter name: objectToSwitchTo
at Sitecore.Diagnostics.Assert.ArgumentNotNull(Object argument, String argumentName)
at Sitecore.Common.Switcher2.Enter(TValue objectToSwitchTo)
at Glass.Mapper.Sc.GlassHtml.MakeEditable[T](Expression1 field, Expression1 standardOutput, T model, Object parameters, Context context, Database database, TextWriter writer)**
Any help on this ?

Sitecore|WFFM| Custom Error Message with details| on Same Page with Form

I have a Web Form for Marketer set up done for one of my Pages.
I have Custom Submit Action written for it as shown below in the code snippet -
public class **CustomFormSubmit : ISaveAction**
{
public void Execute(ID formid, AdaptedResultList fields, params object[] data)
{
try
{
**//var returnValue= Custom Logic to save form data // returns true or false**
}
catch (Exception ex)
{
Logger.Log(ex.Message + ":" + builder, ExceptionCategory.Error);
throw;
}
}
In my above Web form - Success Mode is - SuccessMode/Redirect and I have a success Page configured for it.
My requirement in above scenario is to keep user on the same Page(with Form) if returnValue is false . (as shown in above code snippet)
Can anyone Please guide me in the above scenario as - how to keep user on the same Page with values filled in the form so that user can submit it again.
Product Details - 7.2 rev. 141226 , Web Forms for Marketers 2.4 rev.140117
To add further details -
I am not sure how can I go back to my page instead of the redirection in case if return is false in the above code snippet.
As soon the submit button is clicked the above function- Execute- gets called.
How do I go back to the Page - Do I need to override any function or customize something.
If any exception comes while saving data- then the control goes back to the same Page with all values filled by user retained -with the Save Action Failed Message which is configured in Sitecore .
So my requirement will be to go to to the form as happening in case of Exception when false comes as return value while saving data and to put customised Error Messages which might change each time, so not statically configured ,rather a dynamic one.
Thanks!
Saurabh
One option will be to redirect to the original page with the Form on.
Enable your form to populate the fields via Query String using the ReadQueryString property, via Presentation Details of the Form Renderer:
So on false of your Save Action you create a collection of query strings with the name of each Field, as it appears in the Form, followed by the User's value.
The code below will loop through all your fields and arrange them into a QueryString with its FieldName and Value;
string urlOfForm = HttpContext.Current.Request.Url.AbsolutePath;
var queryString = new StringBuilder("?");
foreach (AdaptedControlResult field in fields)
{
queryString.Append(string.Format("{0}={1}&", field.FieldName, field.Value));
}
urlOfForm = urlOfForm + queryString;
HttpContext.Current.Response.Redirect(urlOfForm);
Sitecore will then automatically populate the appropriate fields with the values, achieving your requirement.
EDIT
I have found that most Exceptions thrown will take the user back to the Form with their values populated. You can then pass in the cause of the failure to write to your CRM. See below for Example
if (submitFailed)
{
throw new Exception("The email address entered already exists in our System");
}
The complexity then comes in dynamically swapping out the Save Action Failed Message to show this Exception Message. All posts I find about custom Save Action Message state the only real approach is to redirect via your Custom Save Action to a different page showing a different message. Which is not suitable to your requirements.
I have found the pipeline Args you are going to need to patch FormSubmitFailedArgs and SubmitFailedArgs. The Former will need the following change
public FormSubmitFailedArgs(ID formID, AdaptedResultList fields, ID actionFailed, Exception ex)
: base(formID, actionFailed, ex)
{
this.Fields = fields;
this.ErrorMessage = ex.Message;
}
and the Latter will need
public SubmitFailedArgs(ID formID, ID actionFailed, string errorMessage, Exception innerException)
{
this.FormID = formID;
this.ActionFailed = actionFailed;
this.ErrorMessage = innerException.Message;
this.InnerException = innerException;
}
Location and Styling of Submit Message:
You need to find the FormRender sublayout file, this is defaulted to website\sitecore modules\Web\Web Forms for Marketers\Control\SitecoreSimpleFormAscx.ascx inside there you will find a compont called SubmitSummary this renders out the submit message so move it to where you require.
Also note it references the CssClass scfSubmitSummary this is what you will need to target to change the styling of the Message. This Answer is already REALLY long so I won't give a blow by blow how to change the styling of that class, see here for example - http://www.awareweb.com/awareblog/10-1-13-wffmguide
Pipeline Patching
I've dug in deeper, in order to use the custom Args we created for using the exception error message you will need to control the Pipeline which ultimately uses those Args, this is the processor Sitecore.Form.Core.Pipelines.FormSubmit.FormatMessage, Sitecore.Forms.Core in the <errorSubmit> Pipeline.
From my investigation it shouldn't take much effort then its a matter of patching it, you can modify if the Sitecore.Forms.config directly or use patch:instead from a config file within the App_Config/Includes folder - see here for more info.
One option would be to create a Custom Form Verification Action. You could save the data here, although it would be better to verify the data against your API here and then save the data in custom save action, simply since this seems more logical as to how WFFM was meant to function.
using Sitecore.Data;
using Sitecore.Form.Core.Controls.Data;
using Sitecore.Form.Core.Submit;
using System;
using System.Collections.Generic;
namespace Custom.WFFM
{
public class CustomVerificationStep : BaseCheckAction
{
public string FailedMessage { get; set; }
public override void Execute(ID formid, IEnumerable<ControlResult> fields)
{
// Call your API
// You have access to the fields, so you can pass them through as parameters to your if needed
bool flag = ServiceAPI.ValidateUserData(param1, param2, etc);
if (!flag)
{
throw new Exception(string.Format(this.FailedMessage ?? "There was an error while verifying the data against the service call"));
}
}
public override ActionState QueryState(ActionContext context)
{
return ActionState.DisabledSingleCall;
}
}
}
Create the corresponding Verification Action under /sitecore/system/Modules/Web Forms for Marketers/Settings/Actions/Form Verification:
You can change the error message by setting it in the Parameters field as <FailedMessage>Custom Failed Error Message</FailedMessage>.
And then add your verification step to your form:
If you need a different error message per form then you can set the error message to display from the Error Messages tab.
The user will then be returned to the same without any of the save actions being called and the form fields still filled in.

django-autocomplete-light add parameter to query url

I'm trying to pass some data along to the autocomplete_light.AutocompleteModelBase so I can exclude some models from the search. I'm trying to use the Dependencies info in the docs here
but I can seem to get it.
The id of the input is id_alternate_version-autocomplete, so I'm trying:
$("#id_alternate_version-autocomplete").yourlabsWidget().autocomplete.data = {'id': 'foo'};
But the url called looks like http://127.0.0.1:8000/autocomplete/FooAutocomplete/?q=bar
I want: http://127.0.0.1:8000/autocomplete/FooAutocomplete/?q=bar&id=foo
How can I do something like that?
DAL provides a way to do this with "forwarding" of another rendered form field's value.
See http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#filtering-results-based-on-the-value-of-other-fields-in-the-form
This is how I did it:
$(document).ready(function() {
$('form#recipe').on('change propertychange keyup input paste', function() {
var ingredient_item_type = $("form#recipe input[type='radio']:checked").val();
var widget = $("form#recipe input#id_ingredients_text").parents('.autocomplete-light-widget');
if(ingredient_item_type) {
widget.yourlabsWidget().autocomplete.data['hello'] = 'world';
}
});
});
Javascript acrobatics aside, the key observation is thus:
anything you put in the .data object of the autocomplete widget will
automatically be made part of the GET request. HTH.

How to add multiple forms Joomla 2.5 component

I am developing a joomla website which required some custom component to integrate manage portfolio, user profile etc. We downloaded one of the hello_world MVC component for joomla 2.5[http://docs.joomla.org/Developing_a_Model-View-Controller_Component/2.5/Introduction] and did necessary customization. First component worked well. But now we need a new component that is having multiple forms required to integrate.
Eg: Store types for one form, store details for another form, manage country/ state by another form.
In the default component having option for manage one form [add/edit/delete/view]. Here I tried to modify/replicate but I failed.
Can anyone suggest the architecture/ sample code to manage multiple forms [Add/edit/delete/view] in joomla 2.5 component creation.
Any help will be apreciate?
Supposing You're speaking of forms stored in the model/forms folder... You should try to override the getForm() function in your model, to call the right form. You should pass a 'layout' when calling the page and then get it in the model constructor.
May be so:
class YourComponentModelYourModel extends JModelAdmin{
public function __construct($config = array()){
switch(JRequest::getVar('layout')){
case 'firstlayout' : $this->form='firstform';
break;
case 'secondlayout' : $this->form='secondform';
break;
default : $this->form='defaultform';
}
parent::__construct($config);
}
...
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_yourcomponent.'.$this->form,$this->form,
array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)){return false;}
return $form;
}
You must put a layout for each form in the views/YourView/tmpl folder and the form declaration must call the layout also :
<form action="<?php echo JRoute::_('index.php?option=com_yourcomponent&layout=firstlayout&id='.(int) $this->item->id); ?>"
method="post" name="adminForm" id="draw-form">

Adding a search box to filter a list of results in Symfony?

I need to put a search box within a list of objects as a result of a typical indexSuccess action in Symfony. The goal is simple: filter the list according to a criteria.
I've been reading the Zend Lucene approach in Jobeet tutorial, but it seems like using a sledge-hammer to crack a nut (at least for my requirements).
I'm more interested in the auto-generated admin filter forms but I don't know how to implement it in a frontend.
I could simply pass the search box content to the action and build a custom query, but is there any better way to do this?
EDIT
I forgot to mention that I would like to have a single generic input field instead of an input field for each model attribute.
Thanks!
I'm using this solution, instead of integrating Zend Lucene I manage to use the autogenerated Symonfy's filters. This is the way i'm doing it:
//module/actions.class.php
public function executeIndex(sfWebRequest $request)
{
//set the form filter
$this->searchForm = new EmployeeFormFilter();
//bind it empty to fetch all data
$this->searchForm->bind(array());
//fetch all
$this->employees = $this->searchForm->getQuery()->execute();
...
}
I made a search action which does the search
public function executeSearch(sfWebRequest $request)
{
//create filter
$this->searchForm = new EmployeeFormFilter();
//bind parameter
$fields = $request->getParameter($this->searchForm->getName());
//bind
$this->searchForm->bind($fields);
//set paginator
$this->employees = $this->searchForm->getQuery()->execute();
...
//template
$this->setTemplate("index");
}
It's important that the search form goes to mymodule/search action.
Actually, i'm also using the sfDoctrinePager for paginate setting directly the query that the form generate to get results properly paginated.
If you want to add more fields to the search form check this :)
I finally made a custom form using the default MyModuleForm generated by Symfony
public function executeIndex {
...
// Add a form to filter results
$this->form = new MyModuleForm();
}
but displaying only a custom field:
<div id="search_box">
<input type="text" name="criteria" id="search_box_criteria" value="Search..." />
<?php echo link_to('Search', '#my_module_search?criteria=') ?>
</div>
Then I created a route named #my_module_search linked to the index action:
my_module_search:
url: my_module/search/:criteria
param: { module: my_module, action: index }
requirements: { criteria: .* } # Terms are optional, show all by default
With Javascript (jQuery in this case) I append the text entered to the criteria parameter in the href attribute of the link:
$('#search_box a').click(function(){
$(this).attr('href', $(this).attr('href') + $(this).prev().val());
});
And finally, back to the executeIndex action, I detect if text was entered and add custom filters to the DoctrineQuery object:
public function executeIndex {
...
// Deal with search criteria
if ( $text = $request->getParameter('criteria') ) {
$query = $this->pager->getQuery()
->where("MyTable.name LIKE ?", "%$text%")
->orWhere("MyTable.remarks LIKE ?", "%$text%")
...;
}
$this->pager->setQuery($query);
...
// Add a form to filter results
$this->form = new MyModuleForm();
}
Actually, the code is more complex, because I wrote some partials and some methods in parent classes to reuse code. But this is the best I can came up with.