Can i user pattern in #Html.Editor In MVC? - regex

we can use pattern(regex) for inputs control
like that :
<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
My question is can i user Pattern in #html.Editor ?
I tried to use this way:
#Html.Editor("country_code", null, new { htmlAttributes = new { #class = "form-control" , required = "required" , pattern="[A-Za-z]{3}"} })
But pattern="[A-Za-z]{3}" does not recognize

Related

Add Calendar Widget to Django Form

I have a view on my website that uses a couple of Django forms to allow the user to specify a date range. I was able to get it so that one Django form creates a start and end field and that when the user clicks on those fields a calendar widget (from here) pops up that allows the user to select a date range. However, when the user selects the date range and hits "apply" the form fields aren't updated.
EDIT
The form I'm using looks like this:
class DateRangeForm(forms.Form):
def __init__(self, *args, **kwargs):
initial_start_date = kwargs.pop('initial_start_date')
initial_end_date = kwargs.pop('initial_end_date')
required_val = kwargs.pop('required')
super(DateRangeForm,self).__init__(*args,**kwargs)
self.fields['start_date'].initial = initial_start_date
self.fields['start_date'].required = required_val
self.fields['end_date'].initial = initial_end_date
self.fields['end_date'].required = required_val
start_date = forms.DateField()
end_date = forms.DateField()
The view they are used in looks like this:
def table_search(request):
initial_start = "2015/2"
initial_end = "2015/222"
message = {'last_url':'table_search'}
if request.method == "POST":
daterange_form = DateRangeForm(request.POST,required=True,initial_start_date=initial_start,initial_end_date=initial_end)
else:
daterange_form = DateRangeForm(required=True,initial_start_date=initial_start,initial_end_date=initial_end)
search_dict.update({'daterange_form':daterange_form})
return render(request, 'InterfaceApp/table_search.html', search_dict)
The Django template here:
<div class="container">
<form action="/InterfaceApp/home/" method="post" class="form">
{% csrf_token %}
<div class="daterangepicker-container mcast-search-filter">
<div class="daterangepicker-label">Date range:</div>
<div id="daterange" class="daterangepicker-content">
{% bootstrap_form daterange_form %}
<i class="icon-calendar icon-large"></i>
</div>
</div>
</form>
</div>
<script>
// the start_date and end_date are the ids that django form fields created
$("#daterange").daterangepicker({
locale: {
format: 'YYYY-MM-DD'
},
startDate: '{{daterange_form.start_date.value}}',
endDate: '{{daterange_form.end_date.value}}'
});
</script>
EDIT 2
And the forms currently look like this (after #ShangWang suggestion) rendered:
Is there a way to display it so the start and end date fields show up? I tried changing the div class so it wasn't hidden, and then they showed up but seemed superfluous.
I use bootstrap-daterangepicker: https://github.com/dangrossman/bootstrap-daterangepicker. It would bind the widget's change to your django form field, so you don't need to manipulate the data once it comes to the views.py.
To get more details you should download and play with it, but here's a rough idea:
Your form.py:
class DateRangeForm(forms.Form):
start_date = forms.DateField()
end_date = forms.DateField()
def __init__(self, *args, **kwargs):
# initialize the start and end with some dates
Your template:
<div class="daterangepicker-container mcast-search-filter">
<div class="daterangepicker-label">Date range:</div>
<div id="daterange" class="daterangepicker-content">
<i class="icon-calendar icon-large"></i>
<span></span> <b class="caret"></b>
</div>
</div>
<!-- This is a hidden div that holds your form fields -->
<div class="hide">From {{ daterange_form.start_date }} to {{ daterange_form.end_date }}</div>
To trigger the widget you need a javascript binding:
// the id_start_date and id_end_date are the ids that django form fields created
$("#daterange").initDateRangePicker("#id_start_date", "#id_end_date");
I created a datepicker wrapper, and defined the initDateRangePicker function. You should put following code in a file called daterangepicker.js and import that in your template as well(or simply copy it into your template):
(function($) {
$.fn.initDateRangePicker = function(start_date_el, end_date_el, future) {
return this.each(function() {
var start = moment($(start_date_el).val());
var end = moment($(end_date_el).val());
var display_date = function(start, end) {
var str = ""
str += start.format('MMMM Do, YYYY');
str += " - ";
str += end.format('MMMM Do, YYYY');
return str;
};
$(this).find("span").html(display_date(start, end));
var self = this;
if(!future) {
$(this).daterangepicker({
format: 'YYYY-MM-DD',
timePicker: false,
ranges: {
'Last 7 days': [moment().subtract('days', 6), moment()],
'Month to date': [
moment().startOf('month'),
moment(),
],
'Last Month': [
moment().subtract('month', 1).startOf('month'),
moment().subtract('month', 1).endOf('month'),
]
},
}, function(start, end) {
$(start_date_el).val(start.format('YYYY-MM-DD'));
$(end_date_el).val(end.format('YYYY-MM-DD'));
$(self).find("span").html(display_date(start, end));
});
}
else {
$(this).daterangepicker({
format: 'YYYY-MM-DD',
timePicker: false,
ranges: {
'Next 7 days': [moment().add('days', 1), moment().add('days', 7)],
'Next month': [
moment().add('month', 1).startOf('month'),
moment().add('month', 1).endOf('month'),
],
},
}, function(start, end) {
$(start_date_el).val(start.format('YYYY-MM-DD'));
$(end_date_el).val(end.format('YYYY-MM-DD'));
$(self).find("span").html(display_date(start, end));
});
}
});
};
}).call(this, jQuery);

How to get values from Extjs template

I am using a Rowexpander inside a ExtjsGrid. RowExpander's template has text area which is used to get values from the user.
Below is my code.How can I read the value
var expander = new Ext.ux.grid.RowExpander({
tpl : new Ext.Template(
'<p><b></b><div class="abc"> <input type="textarea" id = "hans_" name ="hans_" value = "{comment}"</ div></p><p></p><p>{promptMsg}</p>'
),
listeners:
{
expand: function(ex, record, body, rowIndex){
},
collapse: function(ex, record, body, rowIndex){
}
}
});
Solved ...
Below is the solution
Give a dynamic names to textarea of template
'<p><b></b><div> <textarea rows="2" cols="100" id = "{qnNum}" name ="{qnNum}" > {comment} </textarea><b></b></ div></p><p></p>'
Read the values
document.getElementById(record.data.qnNum);

Having trouble to typeaheadjs

I have used following script :
<input class="typeahead" type="text" id = "input">
$('#input').typeahead([{name: 'name',remote: 'planets.json',}]);
JSON file
{"name" : {"value" : ["4729", "Siva", "Prakash"]},"planets" : {"value" : ["Mercury", "Venus", "Pluto"]}}
While typing on the input box , its display two Json array name value[name , plants]. anyway in my code i have mention name as 'name' only. so it has to return that value from 'name' JSON array only ?
In planets.json it is name->value, or planets->value. Init the typeahead like this instead :
<input type="text" id="input" data-provide="typeahead">
$.getJSON("planets.json", function(json) {
$('#input').typeahead({
source : json.name.value
});
});
or json.planets.value, if you want planets

Get value on Request - Kendo UI Dropdownlist ASP.NET MVC

I'm searcing why the Kendo Dropdownlist box doesn't keep my value and pass it on the Request.
I have this on the chtml :
<form method="post" name="Lang">
Culture : #Culture
#(Html.Kendo().DropDownList()
.Name("cbLanguage")
.DataTextField("Name")
.DataValueField("Culture")
.BindTo(new List<Language>()
{
new Language() {Name = "Français (Canada)", Culture = "fr-CA"},
new Language() {Name = "English (Canada)", Culture = "en-CA"},
new Language() {Name = "English (United State)", Culture = "en-US"}
})
.Events(e => e
.Select("cbLanguage_select")
)
.Value(Culture)
)
<select name="lang" onchange="submitLang();">
<option></option>
<option value="en-US" #(Culture == "en-US" ? "selected=\"selected\"" : "")>English</option>
<option value="fr-CA" #(Culture == "fr-CA" ? "selected=\"selected\"" : "")>French</option>
</select>
</form>
<script>
function cbLanguage_select(e) {
$('form').submit();
};
function submitLang() {
$('form').submit();
}
</script>
After that i put this code on the _ViewStart.
if (!Request["lang"].IsEmpty())
{
Culture = UICulture = Request["lang"];
}
---- or this depend of each combo i want tested!!!!
if (!Request["cbLanguage"].IsEmpty())
{
Culture = UICulture = Request["cbLanguage"];
}
It's work really fine with the standard combo. But i never receive the value on the Request with the Kendo Dropdownlist.
I need help to find why!!!
Thank you!

Is it possible to override form helpers?

Using the doc, I can set my own helper for the layout surrending my field, but I'd like to personalize also some fields given by play.
The main reason is for Twitter Bootstrap 2, where I need to change (in checkbox.scala.html)
#input(field, args:_*) { (id, name, value, htmlArgs) =>
<input type="checkbox" id="#id" name="#name" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
<span>#args.toMap.get('_text)</span>
}
to :
<label class="checkbox">
<input type="checkbox" name="#name" id="#id" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value)) />
#args.toMap.get('_text)
</label>
How can I do that ?
Thanks for your help!
I finally did it like this :
I created a package views.helpers.form, that contains :
bootstrap.scala.html :
#(elements: helper.FieldElements)
<div class="control-group#if(elements.hasErrors) { error}">
<label class="control-label" for="#elements.id">#elements.label(elements.lang)</label>
<div class="controls">
#elements.input
#elements.infos(elements.lang).map { info =>
<span class="help-inline">#info</span>
}
#elements.errors(elements.lang).map { error =>
<span class="help-block">#error</span>
}
</div>
checkbox.scala.html :
#**
* Generate an HTML input checkbox.
*
* Example:
* {{{
* #checkbox(field = myForm("done"))
* }}}
*
* #param field The form field.
* #param args Set of extra HTML attributes ('''id''' and '''label''' are 2 special arguments).
* #param handler The field constructor.
*#
#(field: play.api.data.Field, args: (Symbol,Any)*)(implicit handler: helper.FieldConstructor, lang: play.api.i18n.Lang)
#boxValue = #{ args.toMap.get('value).getOrElse("true") }
#helper.input(field, args:_*) { (id, name, value, htmlArgs) =>
<label class="checkbox">
<input type="checkbox" id="#id" name="#name" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
#args.toMap.get('_text)
</label>
div>
</div>
And in my template, all I have to do is :
#import helper.{FieldConstructor, inputText, inputPassword} #** Import the original helpers *#
#import helpers.form.checkbox #** Import my helpers *#
#implicitField = #{ FieldConstructor(helpers.form.bootstrap.f) }
And voilĂ ! It works!
It will be simpler to just write your own tag with the code you want and use it instead of the provided helper. It will simplify potential issues related to overwritting platform tags.