Aria Templates - Form Submission Issues - javascript

I am trying to submit an aria template form http://ariatemplates.com/,the submission is done to a Spring MVC controller/servlet.
The form is getting submitted all right but i am not able to get the values of the aria elements like date picker,text box etc in the controller.
Request.getParameter is of no use.
Any Help will be appreciated.
Here is my sample tpl file,js file and the Spring Controller.
TPL File
{Template {
$classpath:'view.Turnover',
$hasScript : true
}}
{macro main()}
<form action="test.do" method="POST" id="turnoverform">
<div style="float:left;padding-top: 3em;padding-bottom: 3em;padding-right: 3em;">
{#aria:Div {
sclass : "basic",
width : 740,
height : 300
}}
<p style="font-family:Arial,Helvetica,sans-serif;font-size: medium;">Create Turnover Report</p>
<hr />
{#aria:DatePicker {
label: " begin date:",
labelWidth:190,
width:330,
helptext:"Type date or select",
}/}
{#aria:DatePicker {
margins:"x x x 20",
label: "end date:",
labelWidth:190,
helptext:"Type date or select",
width:330,
}/}
<br/>
<br/>
<br/>
{#aria:TextField {
label : "User id",
labelPos : "left",
helptext : "ID",
width : 250,
block : true,
labelWidth : 80,
bind : {
"value" : {
inside : data,
to : 'value' }
}
}/}
<br />
{/#aria:Div}
<br />
{#aria:IconButton {
icon: "std:confirm",
label:"Create",
width : 300,
tooltip : "Click on this to create a Report",
block: true,
onclick : {
fn : buttonClick
}
} /}
</div>
</form>
{/macro}
{/Template}
Javascript File :
Aria.tplScriptDefinition({
$classpath : "view.TurnoverScript",
$prototype : {
/**
* Callback for the click event on the first button.
* #param {aria.DomEvent} evt Click event
*/
buttonClick : function (evt) {
aria.core.IO.asyncFormSubmit({
formId : "turnoverform",
callback : {
fn : this.onSuccess,
onerror : this.onError,
scope : this
}
});
},
onSuccess : function (evt, args) {
alert("The Template has been created");
//this.$json.setValue(["view:Dialog"], "dialogOpen", true);
},
onError : function (evt, args) {
alert("The Template has not been created due to some Error");
}
}
});

in Aria Templates you don't work normally with DOM elements but with the data model.
The way to achieve what you want is to bind those values to the datamodel using the bind property
{#aria:DatePicker {
label: " begin date:",
labelWidth:190,
width:330,
helptext:"Type date or select",
bind : {
value : {
inside : data,
to : "begin_date"
}
}
}/}
Your datamodel would now contain those values, try to modify those values and see the content of this.data in your template script.
To submit the data you have two options,
Template Script through aria.core.Io.asyncRequest (or maybe the RequestMgr, depending on your application complexity).
This method takes a data string that in case of POST requests is the message body. It has to be a string so you can use aria.utils.json.JsonSerializer.serialize() to convert your datamodel into a string.
aria.utils.json.JsonSerializer.serialize(this.data, config)
In the previous snippet of code config is optional, if provided it should match this bean.
Module controller through submitJsonRequest
The good thing about using a controller is that you separate the logic of connecting to a server from the template and that you can send directly an object as data, serialization is done internally.
The drawback is that you'll probably have to configure your UrlService to convert actions to actual URL. Few more info here

Related

CKEditor TypeError: c[a] is undefined in CodeIgniter

Im trying to install CKEditor in my codeigniter based website and I have followed this tutorial: CKEditor in Codeigniter Tutorial
But Im receiving this error: TypeError: c[a] is undefined
CKEDITOR.lang.load/d() ckeditor___ckeditor:230
CKEDITOR.scriptLoader</<.load/f() ckeditor___ckeditor:231
CKEDITOR.scriptLoader</<.load/x() ckeditor___ckeditor:231
CKEDITOR.scriptLoader</<.load/A() ckeditor___ckeditor:231
CKEDITOR.scriptLoader</<.load/u/g.$.onerror()
The folder which ckeditor folder is in: assets/js/ ( which will be: assets/js/ckeditor/ )
The CKEDITOR_BASEPATH is CKEDITOR_BASEPATH = 'http://localhost:5678/assets/js/ckeditor/';
I have no idea what this error is and I can't find properly answers or fix to it.
Thanks in advance.
I had same issue. CKEditor isn't identifying properly its own folder.
So you should set a CKEDITOR_BASEPATH variable before loading CKEditor.
It's briefly said here: (but there might be other places where it's explained better.)
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.html#.basePath
Therefore implementation will be like this:
<script>
window.CKEDITOR_BASEPATH = 'http://example.com/path/to/libs/ckeditor/';
</script>
In my case i used window.CKEDITOR_BASEPATH = '/app/storereport/ckeditor/';
Then load the main ckeditor.js script.
<script type="application/javascript"/>
$(document).ready(function (){
CKEDITOR.replace( 'product_content' ); // ID of element
});
</script>
Use ckeditor in codeigniter
You need
1.Ckeditor helper : ckeditor_helper.php file put on system/helpers folder
2.Ckeditor-pacakge : http://ckeditor.com/download put on root directory
Write bellow code in controller file ex.Page.php
-------------------------------------------------------------------------
class Page extends CI_Controller {
public $data;
public function __construct() {
parent::__construct();
$this->load->helper('ckeditor'); //load helper
}
//load html view
public function add() {
$this->data['ckeditor'] = array(
'id' => 'format', //ID of the textarea that will be replaced 'path' => '../ckeditor/',
'config' => array(
'toolbar' => "Full", //Using the Full toolbar
'width' => "auto", //a custom width
'height' => "300px", //a custom height
),
);
//Loading add File
$this->load->view('page/add', $this->data);
}
}
load view file
---------------------------------------------------------------------
add.php
<?php
$form_data = array('class'=>'form-horizontal', 'role'=>'form','id' => 'pagefrm','name' => 'pagefrm','enctype'=>'multipart/form-data');
echo form_open('Page/Newpage',$form_data); ?>
<div class="form-group">
<label class="col-md-3 control-label" for="example-email">Page Format </label>
<div class="col-md-6">
<textarea class="form-control ckeditor" name="format" id="format" ></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-12">
<button type="submit" class="btn btn-primary waves-effect waves-light"> Add </button>
</div>
</div>
<?php echo form_close();?>
write js to your view file->
<script src="<?php echo base_url();?>assets/js/jquery.min.js"></script>
<script src="<?php echo base_url();?>assets/js/jquery.validate.js"></script>
<script src="<?php echo base_url();?>ckeditor/ckeditor.js"></script> //manage your path
Here you also validate not allowed blank content not allowed using validate.js
--------------------------------------------------------------------
<script type="text/javascript">
$(document).ready(function () {
// When the browser is ready...
$(function () {
// form validation
$("#pagefrm").validate({
// Specify the validation rules
rules: {
format: {
required: function (textarea) {
CKEDITOR.instances['format'].updateElement();
// update textarea
var editorcontent = textarea.value.replace(/<[^>]*>/gi, ''); // strip tags
return editorcontent.length === 0;
}
}
},
// Specify the validation error messages
messages: {
format: "Please enter page format"
},
ignore: [],
submitHandler: function (form) {
form.submit();
}
});
});
});
</script>
I have also used Ckeditor on my CI project. Don't use this long way use these simple steps -
Export your Ckeditor library in your path assets/js/ as you have already done this.
Include this on your html page -
<script type="text/javascript" src="/assets/js/ckeditor/ckeditor.js"></script> on the top of your page .
After the html include script having code as-
CKEDITOR.replace( 'content' );
/* content is the name of the textarea field on which ckeditor is to be applied*/
//ckeditor_helper.php
//put on system/helpers/
<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
function form_ckeditor($data)
{
$data['language'] = isset($data['language']) ? $data['language'] : 'es';
$size = isset($data['width']) ? 'width: "'.$data['width'].'", ' : '';
$size .= isset($data['height']) ? 'height: "'.$data['height'].'", ' : '';
$options = '{'.
$size.
'language: "'.$data['language'].'",
stylesCombo_stylesSet: "my_styles",
startupOutlineBlocks: true,
entities: false,
entities_latin: false,
entities_greek: false,
forcePasteAsPlainText: false,
filebrowserImageUploadUrl : "filexplorers/fckeditor_upload/image", // << My own file uploader
filebrowserImageBrowseUrl : "filexplorers/inlinebrowse/image", // << My own file browser
filebrowserImageWindowWidth : "80%",
filebrowserImageWindowHeight : "80%",
toolbar :[
["Source","-","FitWindow","ShowBlocks","-","Preview"],
["Undo","Redo","-","Find","Replace","-","SelectAll","RemoveFormat"],
["Cut","Copy","Paste","PasteText","PasteWord","-","Print","SpellCheck"],
["Form","Checkbox","Radio","TextField","Textarea","Select","Button","ImageButton","HiddenField"],
["About"],
"/",
["Bold","Italic","Underline"],
["OrderedList","UnorderedList","-","Blockquote","CreateDiv"],
["Image","Flash","Table"],
["Link","Unlink","Anchor"],
["Rule","SpecialChar"],
["Styles"]
]
}';
$my_styles = 'CKEDITOR.addStylesSet("my_styles",
[
// Block Styles
{ name : "H3", element : "h3"},
{ name : "Heading 4", element : "h4"},
{ name : "Heading 5", element : "h5"},
{ name : "Heading 6", element : "h6"},
{ name : "Document Block", element : "div"},
{ name : "Preformatted Text", element : "pre"},
{ name : "Address", element : "address"},
// Inline Styles
{ name: "Centered paragraph", element: "p", attributes: { "class": "center" } },
{ name: "IMG bordered", element: "img", attributes: { "class": "bordered" } },
{ name: "IMG left", element: "img", attributes: { "class": "left" } },
{ name: "IMG right", element: "img", attributes: { "class": "right" } },
{ name: "IMG left bordered", element: "img", attributes: { "class": "left bordered" } },
{ name: "IMGright bordered", element: "img", attributes: { "class": "right bordered" } },
]);';
return
// fix: move to <HEAD...
'< script type="text/javascript" src="'.base_url().'application/plugins/ckeditor/ckeditor.js"></ script>' .
// put the CKEditor
'< script type="text/javascript">' .
$my_styles .
'CKEDITOR.replace("'.$data['id'].'", ' . $options . ');</ script>';
}

Updating array in mongodb document within Mean.js

I’m just beginning with mean.js and getting my feet wet building out a custom article module with a few basic extra properties. I’m trying to add a list of tags that are added on the create form via an text input field. As you can see below, this works fine when they're freshly created. I can see the tags array in the newly created document in the terminal. When I load the edit view the tags field is populated with the elements of the tags array separated by commas. That seems ok. Now I want to simply add new tags after the current ones, separating each new tag with a comma, and have the array updated with the new list. However, after performing the update the tags array elements change to one long string containing all tags.
I had a look at the server side update function but I’m not quite sure what to do there to make it work. It appears the article is being updated as a complete object so maybe I need to extract the tags array and perform a push new tags separately?Anyone know what I’m doing wrong?I've been troubleshooting it for a day or so now and am out of ideas.Thanks in advance!
JSON print of new article:
{
"user" : ObjectId("545db575197ad8a949894a18"),
"desc" : “some description”,
"_id" : ObjectId("546115f20a3048862033d393"),
"created" : ISODate("2014-11-10T19:45:54.079Z"),
"tags" : [
"here”,
"be",
"tags"
],
"name" : "Test”,
"__v" : 0
}
JSON print after update - Note: tags are now one string
{
"__v" : 1,
"_id" : ObjectId("546115f20a3048862033d393"),
"created" : ISODate("2014-11-10T19:45:54.079Z"),
"desc" : "some description",
"name" : "Test",
"tags" : [
"here,be,tags,more"
],
"user" : ObjectId("545db575197ad8a949894a18")
}
// Create new article
$scope.create = function() {
console.log('Tags before split: ' + this.tags);
var tags = this.tags;
var tags = tags.split(" ");
console.log(“Tags array “ + tags);
// Create new article object
var article = new Article ({
name: this.name,
desc: this.desc,
tags: tags
});
// Update existing article
$scope.update = function() {
var article = $scope.article;
console.log(“This "
+ article);
article.$update(function() {
$location.path('articles/' + article._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
Tags input field in create-article view
<div class="form-group">
<label class="control-label" for="tags">Tags</label>
<div class="controls">
<input type="text" data-ng-model="tags" id="tags" class="form-control" placeholder="Tags" required>
</div>
</div>
Tags input field in update-article view
<div class="form-group">
<label class="control-label" for="tags">Tags</label>
<div class="controls">
<input type="text" data-ng-model="article.tags" id="tags" class="form-control" placeholder="Tags" required>
</div>
</div>
Update article server side controller
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Article = mongoose.model('Article'),
_ = require('lodash');
exports.update = function(req, res) {
var article = req.article;
article = _.extend(article , req.body);
article.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(article);
}
});
};
The articles model
var ArticleSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Article name',
trim: true
},
desc: String,
tags: [String],
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Article', ArticleSchema);
You need to split the tags before you update, just the way you do in your create function.

Backbone JS: Issue related to click event and POST request

I am new to Backbone and just finished a simple get request. Trying to implement a simple POST request.
Use case:
When user clicks on Transfer button input field values will be sent to a REST API as a JSON object.
<div id="transfer">
<input type="text" placeholder="From Address" id="fromAddress" />
<input type="text" placeholder="To Address" id="toAddress" />
<input type="text" placeholder="Amount" id="dollars" />
<input type="button" id="button" value="Transfer"/>
</div>
Issue 1
First problem is that what will go into the Backbone View.
My Backbone View:
var TransferView = Backbone.View.extend({
events: {
"click #button": "sendMoney"
},
sendMoney: function() {
alert();
console.log($("#fromAddress").val());
//this.model.transferMoney($("#fromAddress").val(),
$("#toAddress").val(), $("#dollars").val());
}
});
var transferView = new TransferView();
transferView.render();
When I click on button nothing happens. What is the issue here?
Issue 2
Backbone Model looks like this.
var Money = Backbone.Model.extend({
url: 'http://localhost:3000/sendMoney',
defaults: {
fromAddress: "",
toAddress: "",
amount: ""
},
transferMoney: function(request, response) {
//get field values?
this.save();
}
});
var transferMoney = new Money();
Flow didn't reach the model yet, but I am not sure how would I fetch fromAddress, toAddress and amount values from req? How would I pass the request parameters in JSON format to REST service?
Note: Can not use form here. It is more like a ajax request.
The issues with your view are :
you're missing a template
you have a syntax error in $("#toAddress").val(), $("#dollars").val());
Since the view doesn't have a template, nothing gets displayed and therefore there is no "#button" to attach events to. Also, don't forget you'll typicallly need to provide a Money model instance to the view, so that you can then set attributes on it.
To pass value from the form, just use the val() method.
And to send data to the API, you just need to save: Backbone does the rest.
Basically, what you probably want to have is something like
var TransferView = Backbone.View.extend({
events: {
"click #button": "sendMoney"
},
sendMoney: function() {
this.model.save({
fromAddress: $("#fromAddress").val(),
toAddress: $("#toAddress").val(),
amount: $("#dollars").val(),
});
}
});
And to instanciate the view:
var money = new Money();
var transferView = new TransferView({ model: money });
It would probably be a good investment of your time to read a few Backbone tutorials, such as http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/
To delegate saving to a model method, do something like:
var Money = Backbone.Model.extend({
url: 'http://localhost:3000/sendMoney',
defaults: {
fromAddress: "",
toAddress: "",
amount: ""
},
transferMoney: function(attributes) {
this.save(attributes);
}
});
var TransferView = Backbone.View.extend({
events: {
"click #button": "sendMoney"
},
sendMoney: function() {
this.model.transferMoney({
fromAddress: $("#fromAddress").val(),
toAddress: $("#toAddress").val(),
amount: $("#dollars").val(),
});
}
});

How to enable/disable save button of backbone form-view when user changes form content

I have form which gets data from backbone model. When the form is shown, they have initially value set to backbone model. Now, if any field is edited, i want to enable "save" button immediately as soon as any changes is made to field. However, if you change field value and again change it to original, it should again disable the "save" button that allows to save model.I want to achieve as one shown in this jsfiddle :http://jsfiddle.net/qaf4M/2/
I am using backbone.js and backbone.stick (http://nytimes.github.io/backbone.stickit/) to bind model to template.
I create view as follows with model as parameter
RegionManager.show(new app.myView({
model : new app.myModel(
{id: 1})
}));
MY model value is something like this:
{
"id":1, "name:"a" , "age":21
}
The view is as follows:
myView = Backbone.View.extend({
template: _.template( $("#template").html() ),
events: {
"click #save" : "update",
},
bindings: {
'#id': 'id',
'#name': 'name',
'#age': 'age'
},
initialize: function () {
if(this.model){
this.model.fetch();
},
render: function () {
this.$el.html( this.template );
this.stickit(); //used library http://nytimes.github.io/backbone.stickit/
Backbone.Validation.bind(this);
},
update: function() {
this.model.save (
{success: this.success_callback, error: this.error_callback});
},
success_callback: function (model, response) {
},
error_callback: function (model, response) {
alert('error.');
}
});
My template look like
<script type="text/template" id="template">
<form id="myForm " >
<fieldset>
<label>Name</label>
<input type="text" id="name" name="name" />
<label>Age</label>
<input type="text" id="age" name="age" />
<input type="hidden" id="id" name="id"/>
</fieldset>
<a id="save" disabled >Save Changes</a>
</form>
I am confused where should i bind event and how or what is proper way to know the user has chagne some value and accordingly disable button when there is no cahnge in form and enable when change has been made.
A simple solution would be to make your view listen to your model's changes:
initialize: function () {
if(this.model){
this.model.fetch({
success: function(model, resp) {
this.model._attributes = resp; // create a copy of the original attributes
this.listenTo(this.model, 'change', function() {
// when the model changes
// maybe write some function to compare both
if(_.isEqual(this.model._attributes, this.model.toJSON())) {
// disable
}
else {
// able
}
});
}
});
}
So, when the data comes back from the server, you create a copy, and then listen to your model's changes. If the new attributes equal the original, disable the button.

Displaying Data in Dojogrid using dojo.xhrget() method

I want to display a set of data which i am retrieving by an asynchronous call to the server using dojo.xhrget() method. I am retrieving data through a URL and i want that everytime a user clicks in content pane a new set of values gets displayed in grid without refreshing whole page. The problem is that data is not getting displayed in Grid. I am receiving an error by xhrget() error method.
The code for my script is ::
<script>
function populateGrid(){
dojo.xhrGet({
url: "http://localhost:8080/2_8_2012/jsp/GetJson.jsp",
load: fillGrid,
error:handleError,
preventCache:true
});
}
function fillGrid(data, ioArgs)
{
alert(data);
var newData = {
identifier: "ID",
items: data
};
var dataStore = new dojo.data.ItemFileReadStore({data: newData, id:"dataStoreId"});
var gridStructure =[[
{ field: "ID",
name: "ID_Emp",
width: "20%",
classes:"firstName"
},
{
field: "Names",
name: "Name",
width: "20%",
classes: "firstName"
},
{ field: "Email",
name: "Mail",
width: "20%",
classes:"firstName"
}
]
];
var grid = dijit.byId("grid.DataGrid");
grid.setStore(dataStore);
grid.startup();
}
function handleError() {
alert("An error occurred while invoking the service.");
}
</script>
Now , here the output of alert(data) and http://localhost:8080/2_8_2012/jsp/GetJson.jsp is same i.e ::
[{"ID":1,"Names":"Shantanu","Email":"shantanu.tomar#gmail.com"},{"ID":2,"Names":"Mayur","Email":"mayur.sharma#gmail.com"},{"ID":26,"Names":"Rohit"}]
My xhr.get function is working fine in terms of data retrieval. i.e when i update the values in a database. I do get the alert(data) output with that updated value without refreshing the whole page again. But data is not displayed in Data grid.
I am receiving an alert
An error occurred while invoking the service.
The code for http://localhost:8080/2_8_2012/jsp/GetJson.jsp is ::
<%# page language="java" contentType="application/json; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="MyPackage.PopulateTextbox" %>
<%
String temp1;
PopulateTextbox obj = new PopulateTextbox();
temp1 = obj.method();
%>
<%=temp1 %>
The markup code is ::
<div id="grid.DataGrid" data-dojo-type="dojox.grid.DataGrid" title="Simple Grid" data-dojo-props= "autoWidth:true, structure: gridStructure" style="width:900px; height:200px;"></div>
<div id="contentpaneid" dojoType="dijit.layout.ContentPane" title="Pending Activities" style="background-image: url('http://localhost:8080/2_8_2012/images/17.png');" onclick="populateGrid">
I am not getting what's the problem. Can u please help me out on why am i getting an error alert. thanks.
Pratik Chandra rightly alluded to the issue - the datagrid is being populated without any store being set. I suggest changing your datagrid to be populated programmatically
So your declaration:
<div id="grid.DataGrid" data-dojo-type="dojox.grid.DataGrid"
neeeds to be changed to:
<div id="mygrid" ></div>
and then change the line:
var grid = dijit.byId("grid.DataGrid");
to:
var grid = new dojox.grid.DataGrid({
id: "grid",
jsid: "grid",
store: dataStore,
structure: gridStructure,
style: 'width:900px;height:300px;'
}, dojo.byId("mygrid"));
grid.startup();
Also note that whenever you want to refresh the data in the grid, you do not need to repopulate the grid, you can just update the datastore with new values and the datagrid will automatically refresh with new data :-) Dojo takes care of that part.
To clean existing data in the datastore and populate it with new data, set the clearOnClose property on your IFRS. See: Updating Dojo Dijit FilteringSelect's store with asynchonous data to learn about clearOnClose

Categories