django localflavor USStateSelect() inital value - html

I'm trying to use the django localflavor widget USStateSelect() in a form, but I want the widget to have Nebraska selected by default. The Widget only accepts an attrs arg, so I'm trying to understand what attributes I have to set to get the desired result. Here's what I've got in my forms.py:
state = forms.CharField(widget=USStateSelect(attrs={'value':'NE'}))
This is the docs for the HTML select element: http://www.w3.org/html/wg/drafts/html/CR/forms.html#the-select-element
This is the docs for localflavor: https://django-localflavor.readthedocs.org/en/latest/_modules/localflavor/us/forms/
<option value="NE" selected>Nebraska</option>
This is what I need to have in my html, but I can't figure out what the attrs dict needs to contain to achieve this result. I've tried adding 'selected':'selected' and 'class':'selected' to the dict, but that's not doing it.
I've seen a number of people asking how to add an empty option, but no one seems to want to make it default to a specific state. Any ideas are welcome.
Thanks,
Anthony

You can set the initial value like so:
state = forms.CharField(widget=USStateSelect(), initial='NE')
or you can set it when you instantiate the form:
form = ExampleForm(initial={'state': 'NE'})

Related

Need to get the 2sxc Field Type from an Entity

After getting everything working on this previous question Is there a way to Clone one or many Entities (records) in Code, I wanted to clean it up and make it more useful/reusable. So far, I am deciding how to copy/add the field using the content-type field names, so attribute.Key inside the foreach on Attributes. What I need instead is to know the Entity field's Type; meaning String, Number, Hyperlink, Entity, etc.
So I want something like if(AsEntity(original).FieldType == "HyperLink") { do this stuff }. I have explored the API docs but have not spotted how to get to the info. Is it possible?
I did figure out that the attribute.Value has a Type that I could use to answer most of them, but Hyperlink and String are both showing, System.String.
Here are, in order, String, Hyperlink, Entity, and Number:
atts: ToSic.Eav.Data.Attribute`1[System.String]
atts: ToSic.Eav.Data.Attribute`1[System.String]
atts: ToSic.Eav.Data.Attribute`1[ToSic.Eav.Data.EntityRelationship]
atts: ToSic.Eav.Data.Attribute`1[System.Nullable`1[System.Decimal]]
So is there a way from the Entity or its Attributes or some other pathway of object/methods/properties to just get the answer as the field Type name? Or is there a wrapper of some kind I can get to that will let me handle (convert to/from) Hyperlinks? I am open to other ideas. Since the fields.Add() is different by "FieldType" this would be really helpful.
It's kind of simple, but needs a bit more code because of the dynamic nature of Razor. Here's a sample code that should get you want you need:
#using System.Collections.Generic;
#using System.Linq;
#using ToSic.Eav.Data;
var type = AsEntity(Content).Type;
var attributes = type.Attributes as IEnumerable<IContentTypeAttribute>;
var typeOfAwards attributes.First(t => t.Name == "Awards").Type; // this will return "Entity"
I created a quick sample for you here: https://2sxc.org/dnn-tutorials/en/razor/data910/page

Angular - Setting value in input text box in another component

I am trying to set the value in an HTML input text box which is a part of ComponentA from the typescript code which is a part of ComponentB.
Taking a clue from this SO i tried doing:
(<HTMLInputElement>document.getElementById("name")).value = response.name;
But this is not working. Is there anything else i need to take care of?
EDIT: The element with Id "name" is in ComponentA and the above code that is trying to manipulate that element is in ComponentB
If you are trying to set the value of component1's textfield from the compoenent2 then you must have to use of ngModel i.e two way data binding. by providing component2 in the providers list you are able to access all the functions and variables of that component, then you can easily set your value. like this
suppose this is your component 2's value property
name:string = 'Pardeep Jain';
than you can access this in component like this-
<input type="text" [(ngModel)]='name'>
....
constructor(private delete1: Delete){
this.name = this.delete1.name;
}
Working Example
Also
(<HTMLInputElement>document.getElementById("name")).value = response.name;
is used to set the value of current template's field with id named as **name**
This is one of the cases when user interaction on one component ComponentA triggers an update on another component ComponentB.
This article describes multiple approaches, with example code, on how to pass information between components.
My personal favorite is the third approach mentioned in that article in which one of the component (say ComponentA) "listen" for update it is concerned about from any component (say ComponentB) via a service in between them, resulting in a loosely coupled components.
For more approaches here is another link.

Need Validation on html dropdownlist with data from Viewbag

I know I'm not supposed to use the Viewbag and that I should build a menu using Html.DropDowlListFor() so that i can add attribute bound to the members of the model, BUT, that would involve a pretty extensive code rewrite....
I have a custom controller with a menu:
*.ASCX
<%: Html.DropDownList("CityIDs", new SelectList(ViewBag.cities, "Id", "Name"), "--Select--", new { style = "width:200px" })%>
<%= Html.ValidationMessage("CityIDs") %>
The List populates just fine and I can default to the top item to "--Select--"
The prbolem is that I want the validation error to occur on anything that is not from the viewbag.... how can I achieve this?
Validation for dropdown lists only ensures that something was posted. If you want to ensure that the value that was posted is actually one of a set of "allowed" values, then you'll have to manually do that in your post action:
var cityIds = db.Cities.Select(m => m.Id);
if (!cityIds.Contains(model.CityIDs))
{
ModelState.AddModelError("CityIDs", "You must select one of the available choices.");
}
if (ModelState.IsValid)
{
...
Two things:
Notice that I'm pulling the city ids straight from the database (the actual code you'd need here, of course, depends on your specific implementation). The important thing, though, is that ViewBag only survives a single request, so you can't look for them in ViewBag after posting.
Despite the pluralized name of CityIDs, using the DropDownList helper ensures that only a single selected value will exist. If this is actually supposed to be a multiselect, then you need to use ListBox instead, and update this conditional here to account for check for multiple values.
Populates the top item with Text = "--Select--" and Value = ""
which will post a blank value for CityIDs and cause an error in ModelState.

Putting HTML in a hidden form field in Django

I'm having a problem with a template: I'm trying to display a form for changing a value, in which the user enters the current value in a textarea and the old value is kept inside a hidden field for auditing purposes. This value is generally some HTML, and when I render the page this HTML in the hidden field seems to get partially rendered: the value attribute of my hidden field gets closed by the first quotation marks inside the entered HTML, and the rest of the HTML spews out onto my page. I've tried using the escape decorator but that hasn't changed anything.
Firstly, a better solution might be to keep the audit value in a separate model field defined with editable=False. You can still perform checks against the value in a form's clean method:
def clean(self):
cleaned_data = super(SomeForm, self).clean()
if instance.the_audit_field == cleaned_data['the_editable_field']:
...raise a validation error?
You can also modify the value of the audit field from within the model's save method.
Secondly, assuming you must do it the way you are now, let me address the non-escaped value in your template. I assume you're using something like the following:
<textarea value="{{ form.the_audit_field.value }}"></textarea>
You should instead use the following:
<textarea>{{ form.the_audit_field.value }}</textarea>
Note, the value goes inside the textarea, instead of in the value attribute of it.
An even better way to do it is to simply allow Django to render the field for you like the following:
{{ form.the_audit_field }}

Html.DropDownList select value not being set by Model

I have a drop down list like so:
<%= Html.DropDownList("SoldTo", Model.SellDealerList, "Select a Dealer")%>
I'm populating the list in my Controller with the following code:
SellDealerList = new SelectList(repository.GetDealerList(), "id", "name", vehicle.SoldTo);
When I debug through the code the selected value on the SellDealerList has a value that is being set but the HTML source shows no selected value in the list.
I'm baffled as to what I'm doing wrong, but being new to MVC I'm sure it is probably something very simple. The biggest difference from all the other questions and answers I've seen is that I'm not using the ViewData.
Thanks!
Check my answer to this question, maybe it helps.
Perhaps you have a property "SoldTo" in your model, ViewData or ModelState. The DropDown tries to override the selected value if some of these objects has a property or key with the same name as your field. Is kind of crazy if you don't know how it works internally because you see the selected property set to true on the right item of the SelectList and yet no option of the select is selected.