How to get the ChoiceField value using javascript - javascript

First of all sorry for my bad english i am french !
So i have a little problem. I use the django built-in class ChoiceField in my form :
class LogForm(forms.Form):
FormData = (('1', 'Code',), ('2', 'Normal',), ('3', 'Hexa',))
choixFormData = forms.ChoiceField(label=' Forme des donnees ', choices=FormData)
liaison = (('1', 'RS232_1_Port1',), ('2', 'RS232_1_Port2',), ('3', 'RS232_1_Port3',), ('4', 'RS232_1_Port4',),
('5', 'RS422_1_Port1',), ('6', 'RS422_1_Port2',), ('7', 'RS422_1_Port3',), ('8', 'RS422_1_Port4',),
('9', 'RS422_2_Port1',), ('10', 'RS422_2_Port2',), ('11', 'RS422_2_Port3',), ('12', 'RS422_2_Port4',),
('13', 'VoieNumAna',), ('14', 'CAN1',), ('15', '1553',))
choixLiaison = forms.ChoiceField(label='Liaison', choices=liaison)
Data = forms.CharField(required=False, label=' Data ', max_length=100, widget=forms.Textarea)
And i also use the Django Channels in order to implement websockets in my app.
The thing is, i want to be able to render the form thanks to the view ( this is working fine ) and then i want to get the value of the selected choice ( once the the form is rendered ) using javascript.
I tried this :
document.querySelector('#id_Start').onclick = function(e) {
const messageInputDom = document.querySelector('#id_choixLiaison');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
}
I am very new to javascript and i dont understand the reason why this is not working.
I want to be able to get the value of the selected choice field in a string.
Do not hesitate to tell me if the question is badly asked or if you need more details.
Thank you !

Related

how to convert unicode and display in browser? reactjs

I am creating a messages page where admin and client can send and receive messages and I am getting some characters which show up, and another developer tells me it's unicode.
something like this
\u2019hey
or this
m\u0159i\u0165 sroun\u011br tro\u0161a hro\u010d ti\u010d s\u00fds\u016f v diplych o zrutr\u00fd. Zlyzli crest\u016fstbukl\u00e1 slokab zlecou, a nij \u0159uk\u00fd tiv. Nij dratl\u00e1h. Tref\u00fd zraditi tin\u011bgle. \u017el\u00edzlod mrytl\u00e9 n\u011bj vosk n\u011bmu z chlyv\u011bt oskev ston div\u011bm. Nivp\u00e1du\u0161 obozr\u016f sre\u0165n\u011bch k\u0159oufl\u00fd a pi\u0148 syb\u0159otru slou\u0161\u00ed. Bliti m\u0159opidtisly vuvle obu ji\u0161 p\u0159a\u010d m\u00e1n\u011b chapupotid \u017eredi hl\u00fdt zrouskod. Vl\u016fbu lkyd k mlozrat, brsk mled\u0159ej koudyzrozr\u00e1 \u0161k\u00fdnid k t\u011bviz. Z kluz studip bruh\u0159ou s d\u00e1tiv\u011b ti\u017elo dikre\u010d. Zu veplev \u0148\u00e1mesk \u010fo\u010d k otil. T\u0159a\u010d i tipo vl\u00e9\u0165o\u0165 k su\u010f kl\u00fdpru \u0161udi\u0148\u010fa
so, how do I convert it to a format more suitable to display on the browser?? using reactjs
these could be icons or anything . not sure.
Here's an example array of what I am getting from server.
I am putting it into an array and then looping through it to display like this
msgContent = arr.map((item,index)=>{
let len = arr.length-1;
if(len ===index){
return <span key={index+100} className={styles.textMsg}>{item}</span>
}else{
return <span key={index+100} className={styles.textMsg}>{item}<br/></span>
}
})
and it still shows up garbled.
could you tell me where am I going wrong here?
Different ways of displaying HTML entities are listed in the documentation. The examples you have in your question are unicode numbers corresponding to the entity, which works perfectly fine as strings in JSX, so if you just want to display them properly, you don't have to change it at all.
Example
function App() {
return <div> {"\u2019hey"} </div>;
}

How do I populate a list field in a model from javascript?

I have a Kendo.MVC project. The view has a model with a field of type List<>. I want to populate the List from a Javascript function. I've tried several ways, but can't get it working. Can someone explain what I'm doing wrong?
So here is my model:
public class Dashboard
{
public List<Note> ListNotes { get; set; }
}
I use the ListNotes on the view like this:
foreach (Note note in Model.ListNotes)
{
#Html.Raw(note.NoteText)
}
This works if I populate Model.ListNotes in the controller when the view starts...
public ActionResult DashBoard(string xsr, string vst)
{
var notes = rep.GetNotesByCompanyID(user.ResID, 7, 7);
List<Koorsen.Models.Note> listNotes = new List<Koorsen.Models.Note>();
Dashboard employee = new Dashboard
{
ResID = intUser,
Type = intType,
FirstName = user.FirstName,
LastName = user.LastName,
ListNotes = listNotes
};
return View(employee);
}
... but I need to populate ListNotes in a Javascript after a user action.
Here is my javascript to make an ajax call to populate ListNotes:
function getReminders(e)
{
var userID = '#ViewBag.CurrUser';
$.ajax({
url: "/api/WoApi/GetReminders/" + userID,
dataType: "json",
type: "GET",
success: function (notes)
{
// Need to assign notes to Model.ListNotes here
}
});
}
Here's the method it calls with the ajax call. I've confirmed ListNotes does have the values I want; it is not empty.
public List<Koorsen.Models.Note> GetReminders(int id)
{
var notes = rep.GetNotesByCompanyID(id, 7, 7);
List<Koorsen.Models.Note> listNotes = new List<Koorsen.Models.Note>();
foreach (Koorsen.OpenAccess.Note note in notes)
{
Koorsen.Models.Note newNote = new Koorsen.Models.Note()
{
NoteID = note.NoteID,
CompanyID = note.CompanyID,
LocationID = note.LocationID,
NoteText = note.NoteText,
NoteType = note.NoteType,
InternalNote = note.InternalNote,
NoteDate = note.NoteDate,
Active = note.Active,
AddBy = note.AddBy,
AddDate = note.AddDate,
ModBy = note.ModBy,
ModDate = note.ModDate
};
listNotes.Add(newNote);
}
return listNotes;
}
If ListNotes was a string, I would have added a hidden field and populated it in Javascript. But that didn't work for ListNotes. I didn't get an error, but the text on the screen didn't change.
#Html.HiddenFor(x => x.ListNotes)
...
...
$("#ListNotes").val(notes);
I also tried
#Model.ListNotes = notes; // This threw an unterminated template literal error
document.getElementById('ListNotes').value = notes;
I've even tried refreshing the page after assigning the value:
window.location.reload();
and refreshing the panel bar the code is in
var panelBar = $("#IntroPanelBar").data("kendoPanelBar");
panelBar.reload();
Can someone explain how to get this to work?
I don't know if this will cloud the issue, but the reason I need to populate the model in javascript with an ajax call is because Model.ListNotes is being used in a Kendo Panel Bar control and I don't want Model.ListNotes to have a value until the user expands the panel bar.
Here's the code for the panel bar:
#{
#(Html.Kendo().PanelBar().Name("IntroPanelBar")
.Items(items =>
{
items
.Add()
.Text("View Important Notes and Messages")
.Expanded(false)
.Content(
#<text>
#RenderReminders()
</text>
);
}
)
.Events(e => e
.Expand("getReminders")
)
)
}
Here's the helper than renders the contents:
#helper RenderReminders()
{
if (Model.ListNotes.Count <= 0)
{
#Html.Raw("No Current Messages");
}
else
{
foreach (Note note in Model.ListNotes)
{
#Html.Raw(note.NoteText)
<br />
}
}
}
The panel bar and the helpers work fine if I populate Model.ListNotes in the controller and pass Model to the view. I just can't get it to populate in the javascript after the user expands the panel bar.
Perhaps this will do it for you. I will provide a small working example I believe you can easily extend to meet your needs. I would recommend writing the html by hand instead of using the helper methods such as #html.raw since #html.raw is just a tool to generate html in the end anyways. You can write html manually accomplish what the helper methods do anyway and I think it will be easier for you in this situation. If you write the html correctly it should bind to the model correctly (which means it won't be empty on your post request model) So if you modify that html using javascript correctly, it will bind to your model correctly as well.
Take a look at some of these examples to get a better idea of what I am talking about:
http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
So to answer your question...
You could build a hidden container to hold your list values like this (make sure this container is inside the form):
<div id="ListValues" style="display:none">
</div>
Then put the results your ajax post into a javascript variable (not shown).
Then in javascript do something like this:
$('form').off('submit'); //i do this to prevent duplicate bindings depending on how this page may be rendered futuristically as a safety precaution.
$('form').on('submit', function (e) { //on submit, modify the form data to include the information you want inside of your ListNotes
var data = getAjaxResults(); //data represents your ajax results. You can acquire and format that how you'd like I will use the following as an example format for how you could save the results as JSON data: [{NoteID ="1",CompanyID ="2"}]
let listLength = data.length;
for (let i = 0; i < listLength; i++) {
$('#ListValues').append('<input type="text" name="ListNotes['+i+'].NoteID " value="' + data.NoteID +'" />')
$('#ListValues').append('<input type="text" name="ListNotes['+i+'].CompanyID " value="' + data.CompanyID +'" />')
//for your ajax results, do this for each field on the note object
}
})
That should do it! After you submit your form, it should automatically model bind to you ListNotes! You will be able to inpsect this in your debugger on your post controller action.

Proper display of user editing form (CRUD model) with checkbox

I'm making a simple CRUD model with input checkbox. I have no problems on server side, everything is fine. I use NodeJS +MongoDB. But I have problem in editing existing user. When I edit an existing user with a checked checkbox( I get JSON object with parameter checked=true ) how should I display it using JS? This is part of my users.js file in /routes/ folder
var express = require('express');
var router = express.Router();
var User = require('../../models/User');
var rest = require('restler');
router.get('/adduser', function(req, res){
var user = new User();
user.contacts.push({phone: '', email: ''});
rest.get('http://localhost:3000/api/adduser').on('complete', function(data) {
res.render('users/add', { title: 'Add New Users' , n: user});
});
});
And this is views/users/fields.jade part of file for better understanding:
.form-group
label.col-sm-2.control-label(for='email') E-mail:
.col-sm-10
input(type="email", placeholder="email", name="email", value = n.contacts[0].email,required)
.form-group
.col-sm-offset-2.col-sm-10
input#enabled(type="checkbox",style='text-align: center; vertical-align: middle;',placeholder="", name="enabled", value = n.enabled)
| Enable user
So my problem is that I don't understand how I should display that checkbox is really checked when loading existing user.
If user is checked attribute n.enabled=true and if not n.enabled=false. So if user is checked on load of that user I need the input filed to be checked.
I've tried it to do the following way, but it wrote me that n wasn't defined...and I don't know how to pass n as the parameter for that function:
$(document).ready(function(){
if(n.enabled=="true"){$("enabled").toggle(this.checked);}
});
In fields.jade, change value = n.enabled to checked = (n.enabled ? 'checked' : '')
Use # for id-selectors and use n.enabled directly to hide or show your element like,
$("#enabled").toggle(n.enabled);
//-^ prepend # before id selectors
toggle() will show/hide your element, To check uncheck use the prop() like
$(document).ready(function(){
$("#enabled").prop("checked",n.enabled);
});

Zend forms working with ajax/javascript onchange event

I am writing a code to use onchange in my application this is my code so far
.Phtml
<script type="text/javascript">
function submit()
{
$id = intval($_GET['id']);
$satellite = intval($_GET['satellite_id']);
if ($id == 0)
{
echo "Please select a Region";
}
else
{
$query = "select * from satellites where region_id = '".$id."'";
$query = mysql_query($query);
echo "<select name='satellite_id'><option value=''>-- select one --</option>";
while ($row = mysql_fetch_assoc($query))
{
echo "<option value='".$row['satellite_id']."'".($row['satellite_id']==$satellite?" selected":"").">".$row['satellite_name']."</option>";
}
echo "</select>";
//DisplayFormRow ("Satellite", FormDropDownBox ("satellite_id", $SatelliteARY, $Result['satellite_id']));
}
}
</script
//zend code Form
$region_name = new Zend_Form_Element_Select('region_name');
$region_name->setAttribs(array('style' => 'width: 150px;'));
$region_name ->setLabel('Region')
->onchange('this.form.submit();') //tried this code ->onchange('javascript:submit();')
->addMultiOption('--Select One--', '--Select One--');
$mdlRegions = new Model_Regions();
$regions = $mdlRegions->getRegions();
foreach ($regions as $region)
{
$region_name->addMultiOption($region->region_id, $region->region_name, $region->region_short_name);
}
//model
<?php
class Model_Regions extends Zend_Db_Table_Abstract
{
protected $_name = 'regions';
//protected $_name = 'smmedetails';
public function getregion($region_id)
{
$region_id = (int)$region_id;
$row = $this->fetchRow('region_id = ' . $region_id);
if (!$row) {
throw new Exception("Could not find row $region_id");
}
return $row->toArray();
}
public function smmedetails2region($region_name)
{
$data = array(
'region_name'=> $region_name
);
return $this->insert($data);
}
public function getRegions()
{
$select = $this->select();
return $this->fetchAll($select);
}
}
//controller
public function registerAction()
{
$this->view->headScript()->appendFile('/js/ui/jquery.ui.autocomplete.js');
$form = new Form_SmmeDetails();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$companyname = $form->getValue('companyname');
$companytradingname = $form->getValue('companytradingname');
$region_name = $form->getValue('region_name');
$satellite_name = $form->getValue('satellite_name');
$city = $form->getValue('city');
$companyaddress = $form->getValue('companyaddress');
$addresscode = $form->getValue('addresscode');
$companypostaladdress = $form->getValue('companypostaladdress');
$postalcode = $form->getValue('postalcode');
$companyphonenumber = $form->getValue('companyphonenumber');
$companyfaxnumber = $form->getValue('companyfaxnumber');
$companycellnumber = $form->getValue('companycellnumber');
$businessemailaddress = $form->getValue('businessemailaddress');
$businesswebsite = $form->getValue('businesswebsite');
$smmedetails = new Application_Model_DbTable_SmmeDetails();
$smmeid = $smmedetails ->smmedetailsSmmeDetails($companyname, $companytradingname, $region_name, $satellite_name, $city, $companyaddress, $addresscode, $companypostaladdress, $postalcode, $companyphonenumber, $companyfaxnumber,
$companycellnumber, $businessemailaddress, $businesswebsite);
// $region = new Application_Model_DbTable_Region();
//$region ->smmedetails2region($formData, $smmedetails->smmeid);
$this->_redirect('/admin/smme/register2/smmeid/'.$smmeid);
} else {
$form->populate($formData);
}
}
}
The code is suppose to view a hidden input select, called satellite when you select a feild option from regions, the satellite should view certain options based on the region selected. In short the region selected should correspond with what the user selected. eg Province is Gauteng, so cites would be, Johannseburg,Pretoria etc. Take note the region and satellite options are called from the database table according to they names and id. The code above keeps giving me and error Message: Method onchange does not exist. Was told not to use onchange method should I be using ajax and can I use javascript and sqlquery in the view or should I call it as an action? If so how? Here is a slight picture example.
Please be of help
Thanks in advance
I'd make a few suggestions to what you have there.
Firstly, for simplicity, I'd not use the onChange function, because I don't see it in the API, plus JavaScript or jQuery written in that way can become difficult to maintain and write properly. It is a lot simpler to instead include an external JavaScript file. By doing this, you can also test and debug the JavaScript separately, as well as reuse it.
Have a look at the excellent document for onChange, and getJson. I've used these and others and they're quite straight-forward. For testing, I recommend QUnit for starters. It makes testing a breeze.
Secondly, if you're using the Zend libraries for Model_Regions and $region_name, then I'd suggest using them instead of the direct mysql calls as well. This will allow you to build a good library which you can continue to expand as needed, plus it makes composing SQL quicker and safer.
For the controller, I'd suggest a RestController with a Restful Route. Here's an excellent tutorial.
I hope this helps you out with the problem. If you need anything more, let me know.
Thanks for emailing me about this.
The way I go about this is as follows:
Firstly I set up the form, and then an action in a controller.
Lets say getmajorgroupAction()
which in that action I would then disable layout, and just get the relevent results based on the id.
Then in the view file, loop through the
so the output from that call would be
<option value="1">1</option>
<option value="2">2</option>
etc
Personally I use jquery now, whereas the post you referenced when you emailed me, I was using another method.
trying to use something like this
jQuery(document).ready(function() {
jQuery("#division").change(function () {var division = jQuery("#division").val();
jQuery("#major_group").load("/module/getmajorgroup/", {division_id: division} );});
});
Hope that makes sense.
Thanks that was useful but i found a way to do it using this formula below, but everytime I click on the first select the while still in the session the second select appears all the time, eg if a person choose the wrong selection and re tried it brings up another field instead of fixing the field. I think its in a countinous loop . heres my script
<script type="text/javascript">
$(document).ready(function() {
$("#region_name").on('change', function () {
ajaxAddField();
}
);
}
);
// Retrieve new element's html from controller
function ajaxAddField()
{
$.ajax(
{
type: "POST",
url: '<?php echo $this->baseURL()?>/admin/ajax/get-cities/city/' + encodeURIComponent($('#region_name').val()),
success: function(newElement) {
// Insert new element before the Add button
//$(this).prev().remove().end().before('#city-label');
$("#city-label").before(newElement);
}
}
);
}
</script>

The entity with name <entityName> was not found in the MetadataCache

Following a Microsoft hands-on lab for Dynamics CRM 2011, I am attempting to add a custom view to a form that responds 'onchange' to a particular property. Here is my function to add the custom view:
function HandleOnChangeDVMInformationLookup()
{
var locAttr = Xrm.Page.data.entity.attributes.get("new_referringdvm");
if (locAttr.getValue() != null)
{
var dvmId = locAttr.getValue()[0].id;
var viewDisplayName = "DVM Information";
var viewIsDefault = true;
var fetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"><entity name="dvminformation"><attribute name="dvminformation_id"/><attribute name="dvminformation_name"/><attribute name="new_firstname"/><attribute name="new_lastname"/><filter type="and"><condition attribute="id" operator="eq" value="' +dvmId +'"/></filter></entity></fetch>';
var layoutXml = '<grid name="resultset" object="10001" jump="dvminformation_name" select="1" icon="1" preview="1"><row name="result" id="dvminformation_id"><cell name="dvminformation_name" width="300" /><cell name="new_firstname" width="125"/></row></grid>';
var control = Xrm.Page.ui.controls.get("new_dvm_information");
control.addCustomView("62e0ee43-ad05-407e-9b0b-bf1f821c710e", "dvminformation", viewDisplayName, fetchXml, layoutXml, viewIsDefault );
}
}
Upon changing the selected 'dvm' in the form and triggering this function I receive the following error:
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: The entity with a name = 'dvminformation' was not found in the MetadataCache.Detail:
-2147217150
The entity with a name = 'dvminformation' was not found in the MetadataCache.
2013-06-10T22:01:49.4392114Z
Is 'dvminformation' not the entity name I just defined in the XML? Am I missing a step?
Thanks.
It's unlikely that dvminformation is a real entity name. Are you sure there is an entity that exists with that name?
Open the solution and look for the entity, then check its schema name.
If its a custom entity they usually have the format of prefix_name, e.g. new_timeline, new_alert, in your case it might just be dvm_information. If dvm is your solution prefix.
Only system entity have a name without an underscore, e.g. contact, account, incident and dvminformation doesn't look like a system entity to me.
I had the same error message with the customerAddress entity.
Turns out I referenced the entity as "customerAddress" (note the camel case).
But CRM wants logical names of entities and attributes in all lower case. So "customeraddress" did work.
Check if you are connecting to correct org (web.config?)
See

Categories