kendo clienttemplate with parameters - kendo-ui

I am trying to set up a Kendo MVC Grid using client templates for a set of columns.
I have this and it is working:
columns.Bound(m => m.FC_Sun).ClientTemplate("# if(FC_Sun != Base_Sun) {#" + "<span style='color:red;'>#:FC_Sun # </span>" + "# } else {#" + "#: FC_Sun #" + "# } #");
However I would like to move this to a client template instead as I need to add quite a few more items to the column and an inline template just seems a little 'clunky'.
The question is, how can I do this with a single client template. I have an existing one which works for a particular column (the same one as above).
<script id="columnTemplate" type="text/kendo-tmpl">
#if(FC_Sun != Base_Sun){#
<span style='color:orange'>#:FC_Sun #</span>
#}else{#
<span>#: FC_Sun #</span>
#}#
</script>
As you can see this is very much tied to one column, doing it this way I would need to create 7 templates, one for each day of the week, which just seems overkill.
So is there a way to pass extra parameters to the template which tell it which values to use in the if statement..?

As it turns out there is a way to pass parameters to the template, in the grid:
"#=customColumnTemplate($.extend({}, data, { field: 'FC_Sun' }))#"
And the template:
<script id="columnTemplate" type="text/kendo-tmpl">
<p>#= data[field] #</p>
</script>
<script>
var customColumnTemplate = kendo.template($('#columnTemplate').html());
</script>
The way I actually did it in the end though was to skip the external template and use a function directly:
"#=customColumnTemplate(data, 'FC_Sun', 'Base_Sun')#"
.
function customColumnTemplate(data, field, baseField) {
var fc = data[field];
var fcBase = data[baseField];
if (fc != fcBase) {
return "<span style='color:red;'/>" + fc + "</span>";
}
return fc;
}

There isn't a way to pass parameters directly to a Kendo template, unfortunately. However, you could try using a switch statement in your template, and add an enumeration (or whatever would work) to your model for the switch key:
<script id="columnTemplate" type="text/kendo-tmpl">
# switch (DayofWeek) {
case "Sunday": #
<span style='color:orange;'>#:FC_Sun #</span>
# break; #
# case "Monday": #
<span style='color:red;'>#:FC_Mon #</span>
# break; #
...
# } #
</script>
This should allow you to "pass parameters" via the model, and control the appearance of the template per model instance.
Hope this helps.

Related

If condition in Kendo UI grid template

field: 'Status' ,
width: '70px' ,
template: "#if(Status == 'On Request') {#<div class='redAndBold'>#:Status</div>#}#"
I have a kendo UI grid where the "Status" is being filled in from the javascript file. The Status in the model can be "On Request", and what I want is: if it is "On Request", add a class to it, "redAndBold". The syntax in this particular example gives a "user is not defined" error.
Could anyone give me some pointers on how to correctly do this?
The kendo.templates depend on #=fieldName# or #:fieldName#. In the current case, there is a missing closing "#" after 'Status'. The templates are evaluated with the value of the field when bound to a data item during initialization. For executing JavaScript logic use only "#JS logic goes here#". Further information can be found here Kendo UI templates.
To avoid confusion of the template syntax, plain JavaScript function can be used instead:
template: "#=templateFunc(data)#"
// JS hander
function templateFunc(dataItem){
if(dataItem.Status== 'On Request') {
return "<div class='redAndBold'>"+dataItem.Status+"</div>";
} else{
return dataItem.Status;
}
}
I think you are missing a # after Status. When you inject the value of a variable it needs a # before and after. If you split the template code over several lines whilst you write it, it can be easier to get it right.
#if(Status == 'On Request') {#
<div class='redAndBold'>
#:Status#
</div>
#}#
A good check is to count the number of # symbols in your template. It should always be an even number.
As many people pointed out, you're missing a pound sign. I would like to point out that you can set the template as a function that returns a string. I generally do this because there are nuances with the string template such as escaping pound signs among other things:
field: 'Status',
width: '70px',
template: function(dataItem) {
var div = $('<div />');
if (dataItem.Status === 'On Request') {
div.addClass('redAndBold');
}
return div.prop('outerHTML');
}
Just use function for a template :
}, {
field: "TrackingNumber",
title: "#T("Admin.Orders.Shipments.TrackingNumber")",
}, {
field: "ShippingMethodName",
title: "#T("Admin.Orders.Shipments.ShippingMethodName")",
template:function(dataItem) {
var template;
var ShippingMethodPluginName = dataItem.ShippingMethodPluginName;
var IsReferanceActive = dataItem.IsReferanceActive;
var ShippingMethodName = dataItem.ShippingMethodName;
var CargoReferanceNo = dataItem.CargoReferanceNo;
var ShipmentStatusId = dataItem.ShipmentStatusId;
if (ShipmentStatusId == 7) {
return "<div align='center'><label class='label-control'><b style='color:red'>Sipariş İptal Edildi<b></label></div>";
} else {
if (ShippingMethodPluginName == "Shipping.ArasCargo" || ShippingMethodPluginName == "Shipping.ArasCargoMP") {
template =
"<div align='center'><img src = '/content/images/aras-kargo-logo.png' width = '80' height = '40'/> <label class='label-control'><b>Delopi Aras Kargo Kodu<b></label>";
if (IsReferanceActive) {
template =
template +
"<label class='label-control'><b style='color:red; font-size:20px'>"+CargoReferanceNo+"<b></label></div>";
}
return template;
}

How do I pass custom values to CKFinder3 when instantiating a CKEditor4 instance?

I'm having some trouble using pass to pass variables to my CKFinder3 (ASP) connector when using CKEditor4.
I create my editor instance with:
CKFinder.setupCKEditor( myEditor, {
pass: 'testVar',
testVar: 'nooice',
...
});
but the variable just doesn't seem to make it over to CKFinder.
If I add this code to the CKFinder config directly it does work though:
config.pass = 'testVar';
config.testVar = 'nooice';
That's great, but the values I want to pass will be dynamic, so I need to pass them in when I call .setupCKEditor() on the page. I've also tried using connectorInfo: 'testVar=nooice', but that doesn't work either.
Has anyone run into this? I found a great answer and example on this question, How to pass query string parameters in ckeditor for the picture (ckfinder) button?, but the described solution is basically what I'm doing and has no affect for me.
I have been able to get this working in a CKEditor5 test using:
ClassicEditor.create( document.querySelector( '#bodyContent' ), {
ckfinder: {
uploadUrl: '/ckfinder3/connector?command=QuickUpload&type=Images&responseType=json',
options: {
pass: 'testVar',
testVar: 'nooice'
}
},
...
} );
But I cannot figure it out in CKEditor4.
You pass them like so:
var editor = CKEDITOR.replace( 'editor1', {
language : 'en',
} );
CKFinder.setupCKEditor( editor, {
test : 'testvalA',
token : '7901a26e4bc422aef54eb45A',
pass : 'token,test'
});
In the example above you are passing test and token parameters.
If you are using manual integration method, you need to attach parameters to filebrowserXYZBrowseUrl configuration settings as shown below:
var editor = CKEDITOR.replace( 'editor1', {
filebrowserBrowseUrl: '../ckfinder/ckfinder.html?id=abc&foo=bar&test=custom',
filebrowserImageBrowseUrl: '/ckfinder/ckfinder.html?type=Images&id=abc&foo=bar&test=custom',
filebrowserUploadUrl: '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files&id=abc&custom=test',
filebrowserImageUploadUrl: '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images&id=abc&custom=test',
} );
Now the problem is that CKFinder will only pass a predefined set or URL parameters: id, type, resourceType, langCode, CKEditor and CKEditorFuncNum. If you would like to use more parameters, you need to pass them manually as CKFinder configuration settings and you need to do that in ckfinder/ckfinder.html file (you need to modify it) e.g.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
<title>CKFinder 3 - File Browser</title>
</head>
<body>
<script src="ckfinder.js"></script>
<script>
function getUrlParams() {
var vars = {};
window.location.href.replace( /[?&]+([^=&]+)=([^&]*)/gi, function( match, key, value ) {
vars[ key ] = value;
} );
return vars;
}
var params = getUrlParams(),
config = { pass : '' },
ckfServicedParams = [ 'id', 'type', 'resourceType', 'langCode', 'CKEditor', 'CKEditorFuncNum' ];
for( var key in params ){
if ( ckfServicedParams.indexOf( key ) < 0 ) {
config.pass = config.pass.concat( config.pass ? ','+key : key);
config[key] = params[key];
}
}
CKFinder.start( config );
</script>
</body>
</html>
NOTES:
If you would like extra parameters to be sent when you upload files using CKEditor Image Dialog Upload Tab, you need to add them to filebrowserXYZUploadUrl configuration settings as well (you can use different parameters as shown in example above).
Please note these parameters aren't exactly dynamic. You define them once per editor load and can't change them afterwards unless you destroy/create editor instance or reload page with the editor.

dompdf page_script() variables

I'm trying to generate a PDF with multiple sets of page numberings and with unnumbered pages as well. I will not be able to tell in advance how long each set of pages is as they are dynamically generated. For example, the PDF may contain 10 total pages where pages 1-4 have "Page X of 4" in the footer, page 5 is unnumbered, pages 6-8 have "Page X of 3", and pages 9-10 are unnumbered.
Right now I have page numberings implemented using the page_script() and text() functions. Essentially, what I think I need, is a way to be able to pass variable from the document to the page_script() function as the PDF is generated. This would allow me to add something like <?php $page_count = false; ?> or <?php $page_count_reset = true; ?> at different places in the document and act accordingly in the page_script() function. As far as I can tell, this doesn't seem possible.
I am able to set globals within the document <?php $GLOBALS['page_count'] = false; ?> and read them from within page_script() BUT these are processed all at once. So whatever I set the last $GLOBALS['page_count'] to in the document is what $GLOBALS['page_count'] is in the entire page_script() function.
I hope this makes some kind of sense. My next step is to generate multiple PDFs and join them together but that's something I don't want to do unless I have to. Does anyone have any thought?
You're on the right track. Almost there, actually. What you need to do is track your sections in your global variable. The following snippets can be placed in your HTML for use with dompdf 0.6.1.
1) Set up some global variables first thing in the body:
$GLOBALS['start_pages'] = array( );
$GLOBALS['current_start_page'] = null;
$GLOBALS['show_page_numbers'] = false;
2) At the start of each section fill out the start_pages global:
$GLOBALS['current_start_page'] = $pdf->get_page_number();
$GLOBALS['start_pages'][$pdf->get_page_number()] = array(
'show_page_numbers' => true,
'page_count' => 1
);
3) At the end of each section, record the number of pages:
$GLOBALS['start_pages'][$GLOBALS['current_start_page']]['page_count'] = $pdf->get_page_number() - $GLOBALS['current_start_page'] + 1;
4) Use page script to write out your page numbering for each section:
$pdf->page_script('
if ($pdf) {
if (array_key_exists($PAGE_NUM, $GLOBALS["start_pages"])) {
$GLOBALS["current_start_page"] = $PAGE_NUM;
$GLOBALS["show_page_numbers"] = $GLOBALS["start_pages"][$GLOBALS["current_start_page"]]["show_page_numbers"];
}
if ($GLOBALS["show_page_numbers"]) {
$font = Font_Metrics::get_font("helvetica", "bold");
$pdf->text(10, 10, "Page " . ($PAGE_NUM - $GLOBALS["current_start_page"] + 1) . " of " . $GLOBALS["start_pages"][$GLOBALS["current_start_page"]]["page_count"], $font, 12);
}
}
');
The final document would look something like this:
<html>
<body>
<script type="text/php">
// setup
$GLOBALS['start_pages'] = array( );
$GLOBALS['current_start_page'] = null;
$GLOBALS['show_page_numbers'] = false;
</script>
<script type="text/php">
// section start
$GLOBALS['current_start_page'] = $pdf->get_page_number();
$GLOBALS['start_pages'][$pdf->get_page_number()] = array(
'show_page_numbers' => true,
'page_count' => 1
);
</script>
<p>lorem ipsum ... <!-- lots of text -->
<script type="text/php">
// record total number of pages for the section
$GLOBALS['start_pages'][$GLOBALS['current_start_page']]['page_count'] = $pdf->get_page_number() - $GLOBALS['current_start_page'] + 1;
</script>
<div style="page-break-before: always;"></div>
<script type="text/php">
// section start
$GLOBALS['current_start_page'] = $pdf->get_page_number();
$GLOBALS['start_pages'][$pdf->get_page_number()] = array(
'show_page_numbers' => false,
'page_count' => 1
);
</script>
<p>lorem ipsum ... <!-- lots of text -->
<script type="text/php">
// record total number of pages for the section
$GLOBALS['start_pages'][$GLOBALS['current_start_page']]['page_count'] = $pdf->get_page_number() - $GLOBALS['current_start_page'] + 1;
</script>
<script type="text/php">
$pdf->page_script('
if ($pdf) {
if (array_key_exists($PAGE_NUM, $GLOBALS["start_pages"])) {
$GLOBALS["current_start_page"] = $PAGE_NUM;
$GLOBALS["show_page_numbers"] = $GLOBALS["start_pages"][$GLOBALS["current_start_page"]]["show_page_numbers"];
}
if ($GLOBALS["show_page_numbers"]) {
$font = Font_Metrics::get_font("helvetica", "bold");
$pdf->text(10, 10, "Page " . ($PAGE_NUM - $GLOBALS["current_start_page"] + 1) . " of " . $GLOBALS["start_pages"][$GLOBALS["current_start_page"]]["page_count"], $font, 12);
}
}
');
</script>
</body>
</html>
You can see a sample of this in practice here: http://eclecticgeek.com/dompdf/debug.php?identifier=e980df4efacf5202c2f1d31579f09c56

strict with CGI::AJAX

I have set of code for updating a password in the table, here I'm using CGI::AJAX module to update the password and get the popup screen on corresponding execution.When using that code with my application it is executing properly but I didn't get the output(means Perl subroutine is not called when JavaScript function to get use.password is not updated into table). I don't get any error either.
#!/usr/bin/perl -w
use strict;
use CGI;
use DBI;
use Data::Dumper;
my $p = new CGI qw(header start_html end_html h1 script link);
use Class::Accessor;
use CGI::Ajax;
my $create_newuser;
my $ajax = new CGI::Ajax('fetch_javaScript' => $create_newuser);
print $ajax->build_html($p,\&Show_html,{-charset=>'UTF-8', -expires=>'-1d'});
sub Show_html
{
my $html = <<EOHTML;
<html>
<body bgcolor="#D2B9D3">
<IMG src="karvy.jpg" ALT="image">
<form name='myForm'>
<center><table><tr><td>
<div style="width:400px;height:250px;border:3px solid black;">
<center><h4>Create New Password's</h4>
<p>&nbsp User Name</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<INPUT TYPE="text" NAME="user" id = "user" size = "15" maxlength = "15" tabindex = "1"/></p>
<p>&nbsp Password:</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<INPUT TYPE=PASSWORD NAME="newpassword" id = "newpassword" size = "15" maxlength = "15" tabindex = "1"/></p>
<p>&nbsp Re-Password:</b>&nbsp&nbsp&nbsp<INPUT TYPE=PASSWORD NAME="repassword" id = "repassword" size = "15" maxlength = "15" tabindex = "1"/></p>
<input type="submit" id="val" value="Submit" align="middle" method="GET" onclick="fetch_javaScript(['user','newpassword','repassword']);"/><INPUT TYPE="reset" name = "Reset" value = "Reset"/>
<p>Main Menu <A HREF = login.pl>click here</A>
</center>
</div>
</td></tr></table></center>
</form>
</body>
</html>
EOHTML
return $html;
}
$create_newuser =sub
{
my #input = $p->params('args');
my $user=$input[0];
my $password=$input[1];
my $repassword=$input[2];
my $DSN = q/dbi:ODBC:SQLSERVER/;
my $uid = q/123/;
my $pwd = q/123/;
my $DRIVER = "Freetds";
my $dbh = DBI->connect($DSN,$uid,$pwd) or die "Coudn't Connect SQL";
if ($user ne '')
{
if($password eq $repassword)
{
my $sth=$dbh->do("insert into rpt_account_information (user_id,username,password,user_status,is_admin) values(2,'".$user."','".$password."',1,1)");
my $value=$sth;
print $value,"\n";
if($value == 1)
{
print 'Your pass has benn changed.Return to the main page';
}
}
else
{
print "<script>alert('Password and Re-Password does not match')</script>";
}
}
else
{
print "<script>alert('Please Enter the User Name')</script>";
}
}
my $create_newuser;
my $ajax = new CGI::Ajax('fetch_javaScript' => $create_newuser);
...;
$create_newuser =sub { ... };
At the moment when you create a new CGI::Ajax object, the $create_newuser variable is still undef. Only much later do you assign a coderef to it.
You can either assign the $create_newuser before you create the CGI::Ajax:
my $create_newuser =sub { ... };
my $ajax = new CGI::Ajax('fetch_javaScript' => $create_newuser);
...;
Or you use a normal, named subroutine and pass a coderef.
my $ajax = new CGI::Ajax('fetch_javaScript' => \&create_newuser);
...;
sub create_newuser { ... }
Aside from this main error, your script has many more problems.
You should use strict instead of the -w option.
For debugging purposes only, use CGI::Carp 'fatalsToBrowser' and sometimes even with warningsToBrowser can be extremely helpful. Otherwise, keeping a close eye on the error logs is a must.
my $p = new CGI qw(header start_html end_html h1 script link) doesn't make any sense. my $p = CGI->new should be sufficient.
use Class::Accessor seems a bit random here.
The HTML in Show_html is careless. First, your heredocs allows variable interpolation and escape codes – it has the semantics of a double quoted string. Most of the time, you don't want that. Start a heredoc like <<'END_OF_HTML' to avoid interpolation etc.
Secondly, look at that tag soup you are producing! Here are some snippets that astonish me:
bgcolor="#D2B9D3", align="middle" – because CSS hasn't been invented yet.
<center> – because CSS hasn't been invented yet, and this element isn't deprecated at all.
<table><tr><td><div ... </div></td></tr></table> – because there is nothing wrong with a table containing a single cell. (For what? This isn't even for layout reasons!) This table cell contains a single div …
… which contains another center. Seriously, what is so great about unneccessary DOM elements that CSS isn't even an option.
style="width:400px;height:250px;border:3px solid black;" – because responsive design hasn't been invented yet.
<p> ... </b> – Oh, what delicious tag soup!
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp – this isn't a typewriter, you know. Use CSS and proper markup for your layout. There is a difference between text containing whitespace, and empty areas in your layout.
tabindex = "1" … tabindex = "1" … tabindex = "1" – I don't think you know what tabindex does.
<A HREF = login.pl> – LOWERCASING OR QUOTING YOUR ATTRIBUTES IS FOR THE WEAK!!1
onclick="fetch_javaScript(['user','newpassword','repassword']);" – have you read the CGI::Ajax docs? This is not how it works: You need to define another argument with the ID of the element where the answer HTML is displayed.
In your create_newuser, you have an SQL injection vulnerability. Use placeholders to solve that. Instead of $sth->do("INSERT INTO ... VALUES('$foo')") use $sth->do('INSERT INTO ... VALUES(?)', $foo).
print ... – your Ajax handler shouldn't print output, instead it should return a HTML string, which then gets hooked into the DOM at the place your JS function specified. You want something like
use HTML::Entities;
sub create_newuser {
my ($user, $password, $repassword) = $p->params('args');
my ($e_user, $e_password) = map { encode_entities($_) } $user, $password;
# DON'T DO THIS, it is a joke
return "Hello <em>$e_user</em>, your password <code>$e_password</code> has been successfully transmitted in cleartext!";
}
and in your JS:
fetch_javaScript(['user','newpassword','repassword'], ['answer-element'], 'GET');
where your HTML document somewhere has a <div id="answer-element" />.

pass variables to php with ajax load()

I found some close answers for this, but none of them worked in my case. I have:
Input tag:
<input name="title" id="title">
Ajax:
<script language="javascript">
function example_ajax_request() {
$('#example-placeholder').html('<p><img src="/img/ajax-loader.gif" /></p>');
setTimeout('example_ajax_request_go()', 0);
}
function example_ajax_request_go() {
$j(document).ready(function () {
var inputField = $j('#inputText').val();
$j(".button").click(function () {
$('#example-placeholder').load('preview.php?title=' + title + ' .aClass');
}
</script>
Button to call the function:
<input type="button" onclick="example_ajax_request()" value="Preview" />
I'm trying to pass 'title' var from the input tag via ajax to 'preview.php'. This code above has errors and is not running, can you suggest correct one? Thanks!
You have not put in exact error messages (from your browser's console, please put them in and update your question). I am just putting across some suggestions/improvements:
Whenever you are passing GET parameters, always URIEncode the value(the xyz and value in url?abc=xyz&blah=value). In javascript there is a function call EncodeURIComponent(..). You would use it like:
'preview.php?title=' + EncodeURIComponent(title +' .aClass')
A possible typo, you have have a space in the URL, before the + ' .aClass'. If you need one, explicitly replace it with a + or %20.
Found a way. Here it is:
<script type="text/javascript">
function example_ajax_request() {
$('#example-placeholder').html('<p><img src="img/ajax-loader.gif" /></p>');
$('#example-placeholder').load("preview.php?title="+$('#title').val());
}
</script>
Thanks!

Resources