Including dynamic auto suggest javascript code in twig - symfony-3.4

I wanted to add an auto suggest list of students' code into input box
public function autoCodeSuggest()
{
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery("SELECT s.studentLogin FROM AppBundle:StudentLogin s ORDER BY s.studentLogin");
$code = $query->getArrayResult();
$strJavascript = '';
if (!empty($code)){
$strJavascript = '
var ArrayCode = new Array(';
for ($i=0; $i<count($code); $i++){
$strJavascript .= '"'.$code[$i]['studentLogin'].'",';
} // for ($i=0; $i<count($code); $i++)
$n = strlen($strJavascript)-1;
$strJavascript = substr_replace($strJavascript,'',$n); // remove last ,
$strJavascript .= ');';
} // if (!empty($code))
return $strJavascript;
} // end function
in my controller
public function studentSearchAction()
{
$LoginJS = $this->get('utilities_student_tools')->autoCodeSuggest();
return $this->render('student/student_search.html.twig', array(
'LoginJS' => $LoginJS,
));
}
student_search.html.twig contains
{% block body %}
<script language="javascript" type="text/javascript">
{{ LoginJS }}
</script>
{{ include('student_code.html.twig') }}
{% endblock %}
it doesn't work because when I view the source code of my page I have
<script language="javascript" type="text/javascript">
var ArrayCode = new Array("AA0951","AA1825","AA2802","AA2886","AA3418",.....
</script>
when I add a \ to the javascript code generator
$strJavascript .= '\"'.$code[$i]['studentLogin'].'\",';
the output become
var ArrayCode = new Array(\"AA0951\",\"AA1825\",\"AA2802\",\"AA2886\"
It works if the output is like
var ArrayCode = new Array("AA0951","AA1825","AA2802","AA2886",
the " is converted to " .
How can I avoid the conversion in twig?

I just find the answer.
{{ LoginJS|raw }}

Related

Hide the meta prices of the product shopify

In Shopify.
My site hides prices if the user is not logged in. And I have hidden prices everywhere, but I only have to do it in window.ShopifyAnalytics.meta (meta prices), which is displayed as a json.
I end up seeing this structure:
<script>
window.ShopifyAnalytics = window.ShopifyAnalytics || {};
window.ShopifyAnalytics.meta = window.ShopifyAnalytics.meta || {};
window.ShopifyAnalytics.meta.currency = 'USD';
var meta = {"product":{
...
};
for (var attr in meta) {
window.ShopifyAnalytics.meta[attr] = meta[attr];
}
</script>
But how do I hide the prices here?
{% if customer == null %}
<script>
window.ShopifyAnalytics = window.ShopifyAnalytics || {};
window.ShopifyAnalytics.meta = window.ShopifyAnalytics.meta || {};
setTimeout(function()
{
delete window.ShopifyAnalytics.meta.product
}, 100);
</script>
{% endif %}
paste it on the head tag of your theme.liquid.
the value is not yet evaluated before clicking the > to show the object tree on console.log

Can you pretty print IHtmlContent?

If I have a IHtmlContent can I pretty print it?
Example:
var html = new HtmlString("<article><h2>Hello!</h2></article>");
I want it pretty printed with line breaks and indention into:
<article>
<h2>Hello!</h2>
</article>
I do not want:
<article><h2>Hello!</h2></article>
You could try to JavaScript to add the line breaks and indention into, then, use <pre> tag to render the html content. Please check the following sample:
Index.cshtml:
#{
var html ="<article><h2>Hello!</h2></article>";
}
<div id="printdiv">
#Html.Raw(html)
</div>
<div id="output">
</div>
<input type='button' id='btn' value='Print' onclick='printDiv();'>
#section Scripts{
<script>
function printDiv() {
var divToPrint = document.getElementById('printdiv');
//display the pretty html content in the web page.
document.getElementById("output").innerHTML = "<pre>" + process(divToPrint.innerHTML).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") + "</pre>";
//create a new window to print the div content.
var newWin = window.open('', 'Print-Window');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()"><pre>' + process(divToPrint.innerHTML).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") + '</pre></body></html>');
newWin.document.close();
setTimeout(function () { newWin.close(); }, 10);
}
function process(str) {
var div = document.createElement('div');
div.innerHTML = str.trim();
return format(div, 0).innerHTML;
}
function format(node, level) {
var indentBefore = new Array(level++ + 1).join(' '),
indentAfter = new Array(level - 1).join(' '),
textNode;
for (var i = 0; i < node.children.length; i++) {
textNode = document.createTextNode('\n' + indentBefore);
node.insertBefore(textNode, node.children[i]);
format(node.children[i], level);
if (node.lastElementChild == node.children[i]) {
textNode = document.createTextNode('\n' + indentAfter);
node.appendChild(textNode);
}
}
return node;
}
</script>
}
The result like this:
You can parse it XML with XDocument.Parse then use XmlWriter with its settings set to Indent to true. Worked for me on my HTML too.
var html = new HtmlString("<article><h2>Hello!</h2></article>");
using var writer = new StringWriter();
html.WriteTo(writer, HtmlEncoder.Default);
var htmlString = writer.ToString();
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Encoding = Encoding.UTF8,
Indent = true,
};
var sb = new StringBuilder();
using (var writer = XmlWriter.Create(sb, settings))
{
XDocument.Parse(htmlString).Save(writer);
}
Console.WriteLine(sb.ToString());

Getting data from another page using XMLHttpRequest

Good morning everyone. I tried creating a site that could get information from another page and feed the response into a div tag, but it didnt work. I checked with a very similar one i learnt from. Here is the HTML code.
<html>
<head>
<script>
function checkit(){
var samxml; var username;
if (window.XMLHttpRequest){
samxml = new XMLHttpRequest();}
else {
samxml = new ActiveXObject("Microsoft.XMLHTTP");
}
samxml.onreadystatechange = function() {
if (samxml.readyState == 4 && samxml.status == 200){
document.getElementById("check").innerHTML = samxml.responseText;}
}
username = document.getElementById("username").value;
samxml.open("POST", "check.php",true);
samxml.send( "username" );
}
}
</script>
</head>
<body>
<form>
<label for ="username">User ID:</label>
<input type = "text" name = "username" id = "username"/>
<div id = "check"></div>
<button type = "button" onclick = "checkit()">Check</button>
</form>
</body>
</html>
Here is the PHP page:
//php file
<?php
$user = $_POST["username"];
if ($user == "samuel") {
echo "Hmm. Chosen! Choose another one";}
else {
echo "Nice one";}
?>
Thanks so much.

Codeigniter get random record with limit

I've created a page that load 4 products everytime you scroll down the page with codeigniter and Ajax.
I followed this tutorial for create pagination with codeigniter and jQuery.Everything works fine, moreover I've changed the load type from database using Ajax.
I've got a problem with codeigniter.
When I try to get random record from the table I've got duplicate products.
This is the functions in codeigniter:
UPDATE CONTROLLER
function index()
{
$this->load->helper('url');
$data['description'] = "Description";
$data['keywords'] = "Keywords";
$data['products'] = $this->abitainterni->getAllProductsLimit();
$data['get_products'] = $this->abitainterni->get_products();
$this->load->view('welcome', $data);
}
function get_products($offset)
{
$already_used = $this->input->post('already_used');
$already = explode(',', $already_used);
$data['products'] = $this->abitainterni->getAllProductsLimit($offset, $already);
$arr['view'] = $this->load->view('get_products', $data, true);
$bossy = '';
foreach($data['products'] as $p) {
$bossy .= $p->productID.',';
}
$arr['view'] = $bam;
$arr['ids'] = $bossy;
echo json_encode($arr);
return;
}
UPDATE SCRIPT
<script type="text/javascript">
$(document).ready(function(){
<?
$like_a_boss = "";
foreach($products as $gp):
$like_a_boss .= $gp->productID.',';
endforeach;
?>
var products = '<?= $like_a_boss; ?>';
var loaded_products = 0;
$(".loadMoreProducts").click(function(){
loaded_products += 4;
var dati = "welcome/get_products/" + loaded_products;
$.ajax({
url:'welcome/get_products/' + loaded_products,
type: 'post',
data: {already_used: products},
cache: false,
success: function(data) {
var obj = $.parseJSON(data);
$("#mainContainerProductWelcome").append(obj.view);
already_used += obj.ids;
if(loaded_products >= products - 4) {
$(".loadMoreProducts").hide();
} else {
// load more still visible
}
},
error: function() {
// there's something wrong
}
});
// show spinner on ajax request starts
$(".loading-spinner").ajaxStart(function(){
$(".loading-spinner").show();
$(".text-load").hide();
});
// ajax request complets hide spinner
$(".loading-spinner").ajaxStop(function(){
$(".loading-spinner").delay(5000).hide();
$(".text-load").show();
});
return false;
});
// submit form contact
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
// click on load more btn
$(".loadMoreProducts").click();
return false;
}
});
});
</script>
you'll need to keep track of the products you've already queried, throw their id's in an array, and then use something like a where not in. So something like this:
function getAllProductsLimit($offset=0, $already_used = array(0))
{
$this->db->order_by('productID', 'RANDOM');
$this->db->where_not_in('productID', $already_used);
$query = $this->db->get('product', 4, $offset);
if($query->num_rows() > 0){
return $query->result();
} else {
return 0;
}
}
NEW CONTROLLER
function index()
{
$this->load->helper('url');
$data['title'] = "Scopri i nostri prodotti";
$data['description'] = "Description";
$data['keywords'] = "Keywords";
$data['products'] = $this->abitainterni->getAllProductsLimit();
$data['get_products'] = $this->abitainterni->get_products();
$this->load->view('welcome', $data);
}
function get_products($offset)
{
$already_used = $this->input->post('already_used');
$already = explode(',', $already_used);
$data['products'] = $this->abitainterni->getAllProductsLimit($offset, $already);
$arr['view'] = $this->load->view('get_products', $data, true);
$bossy = '';
foreach($data['products'] as $p)
{
$bossy .= $->productID.',';
}
$arr['view'] = $bam;
$arr['ids'] = $bossy;
echo json_encode($arr);
return;
}
NEW SCRIPT
<script type="text/javascript">
$(document).ready(function(){
<?
$like_a_boss = '';
foreach($get_products as $gp):?>
$like_a_boss .= $gp->productID.',';
endforeach;?>
var products = '<?= $like_a_boss; ?>';
var loaded_products = 0;
$(".loadMoreProducts").click(function(){
loaded_products += 4;
var dati = "welcome/get_products/" + loaded_products;
$.ajax({
url:'welcome/get_products/' + loaded_products,
type: 'post',
data: {already_used: products},
cache: false,
success: function(data) {
var obj = $.parseJSON(data);
$("#mainContainerProductWelcome").append(obj.view);
already_used += obj.ids;
if(loaded_products >= products - 4) {
$(".loadMoreProducts").hide();
} else {
// load more still visible
}
},
error: function() {
// there's something wrong
}
});
// show spinner on ajax request starts
$(".loading-spinner").ajaxStart(function(){
$(".loading-spinner").show();
$(".text-load").hide();
});
// ajax request complets hide spinner
$(".loading-spinner").ajaxStop(function(){
$(".loading-spinner").delay(5000).hide();
$(".text-load").show();
});
return false;
});
// submit form contact
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
// click on load more btn
$(".loadMoreProducts").click();
return false;
}
});
});
</script>
Then whereever your using that function, before you echo out your results to your ajax function, run a quick foreach to add the ids of the products you just got to the already used array. You can either store this is session, or pass it back and forth between your ajax stuff, or if your ajax stuff is written fine, you don't need to worry about it, just attach the product id's to each product you're displaying using a data attribute or something and generate the array that way.

Rally App SDK: Is there a way to have variable columns for table?

Using the Rally App SDK, is there a way to create a table with a variable number of columns? For example, for a selected release, the columns are the iterations within that release date range, and the rows are each project.
I have all of the data I want to display, but not sure how to create the table.
Here's an example app that dynamically builds a table config with Iteration Names as columns and then adds some dummy data to it. Not too exciting, but it illustrates the idea.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<!-- Copyright (c) 2002-2011 Rally Software Development Corp. All rights reserved. -->
<html>
<head>
<title>Iterations as Table Columns</title>
<meta name="Name" content="App: Iterations as Table Columns"/>
<script type="text/javascript" src="https://rally1.rallydev.com/apps/1.29/sdk.js"></script>
<script type="text/javascript">
function iterationsAsTableColumns(rallyDataSource)
{
var wait = null;
var table = null;
var tableHolder = null;
// private method the builds the table of Iteration columns and your info
function showResults(results)
{
if (wait) {
wait.hide();
wait = null;
}
if (table) {
table.destroy();
}
var myIterations = results.iterations;
if (myIterations.length === 0) {
tableHolder.innerHTML = "No iterations were found";
return;
}
var columnKeys = new Array();
var columnHeaders = new Array();
var columnWidths = new Array();
var columnWidthValue = '80px';
var keyName;
// Dynamically build column config arrays for table config
for (i=0; i<myIterations.length;i++){
keyName = "Column"+i;
columnKeys.push(keyName);
columnHeaders.push("'" + myIterations[i].Name + "'");
columnWidths.push("'" + columnWidthValue + "'");
}
var config = { 'columnKeys' : columnKeys,
'columnHeaders' : columnHeaders,
'columnWidths' : columnWidths
};
table = new rally.sdk.ui.Table(config);
var cellValue;
var propertyAttributeStatement;
var rowData = new Array();
for (i=0;i<10;i++){
// create Object for row data
rowItem = new Object();
for (j=0; j<columnKeys.length;j++){
cellValue = "Cell[" + i + "][" + j + "] = Your Data Here";
propertyAttributeStatement = "rowItem." + columnKeys[j] + " = '"+cellValue+"';";
eval(propertyAttributeStatement);
}
rowData.push(rowItem);
}
table.addRows(rowData);
table.display(tableHolder);
}
//private method to query for iterations that get listed as columns
function runMainQuery(sender, eventArgs) {
var queryCriteria = '(Project.Name = "Avalanche Hazard Mapping"")';
var queryConfig =
{
key : "iterations",
type : "Iteration",
fetch : "FormattedID,Name,Project,StartDate,EndDate,CreationDate",
order : "CreationDate desc",
};
tableHolder.innerHTML = "";
wait = new rally.sdk.ui.basic.Wait({});
wait.display(tableHolder);
rallyDataSource.findAll(queryConfig, showResults);
}
//private method to start building controls on page
function initPage() {
buttonSpan = document.getElementById('buttonSpan');
tableHolder = document.getElementById('table');
var buttonConfig = {
text: "Show Table",
value: "myValue"
};
var showTableButton = new rally.sdk.ui.basic.Button(buttonConfig);
showTableButton.display(buttonSpan, runMainQuery);
}
// only public method
this.display = function() {
rally.sdk.ui.AppHeader.showPageTools(true);
initPage();
};
}
</script>
<script type="text/javascript">
rally.addOnLoad(function() {
var rallyDataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
var iterationsAsTableColumnsExample = new iterationsAsTableColumns(rallyDataSource);
iterationsAsTableColumnsExample.display();
});
</script>
</head>
<body>
<div>
<span id="buttonSpan"></span>
</div>
<div style="height: 15px;"> </div>
<div id="table"></div>
</body>
</html>