Laravel :Try Download Excel : Class 'XMLWriter' not found - excel

I am trying download html table as excel file, first in blade template I did this :
<form method="POST" action="{{url('/download')}}" id="download_form">
{{ csrf_field() }}
<table class="table font-weight-bold w-100" id="excel_table">
...........
<button type="submit" id="download" class="btn btn-success">Download to excel</button>
</div>
</form>
<script>
$(document).ready(function(){
$('#download').click(function(){
var table_content = '<table>';
table_content += $('#excel_table').html();
table_content+= '</table>';
$('#file_contente').val(table_content);
$('#download_form').html();
})
})
</script>
the in controller I tried this :
namespace App\Http\Controllers;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
public function download(Request $req)
{
$filename = $req->stage." ".$req->group . '.xlsx';
$temporary_html_file = './tmp_html/' .time() . '.html';
file_put_contents($temporary_html_file, $req->file_contente);
$reader = IOFactory::createReader('Html');
$spreadsheet = $reader->load($temporary_html_file);
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($filename);
header('Content-Type: application/x-www-form-urlencoded');
header('Content-Transfer-Encoding: Binary');
header("Content-disposition: attachment; filename=\"".$filename."\"");
readfile($filename);
unlink($temporary_html_file);
unlink($filename);
}
I get this error :
Class 'XMLWriter' not found A class import is missing You have a
missing class import. Try importing this class:
PhpOffice\PhpSpreadsheet\Shared\XMLWriter.
Note the download is works correctly in locahost server

Just enable gd and xmlwriter in your php extension.
extension=gd2

Related

Custom search using doctrine and symfony2

I want to create a searchController, that searches the db for whatever keywords the user enters into a textbox. I have looked at this article and this and many more.
This is what I have so far:
public function searchAction(Request $request) {
if ($request->getMEthod() == 'GET') {
$title = $request->get('Search_term');
//echo "<div class=\"searchText\">Search Results</div><hr/>";
$em = $this->getDoctrine()->getManager();
$Search_terms = explode(' ', $title); //splits search terms at spaces
$query = "SELECT * FROM Entity/Adverts WHERE ";
foreach ($Search_terms as $each) {
// echo $each."<br/>";
$i = 0;
$i++;
if ($i == 1)
$query .= "Adv_title LIKE '%$each%' ";
else
$query .= "OR Adv_title LIKE '%$each%' ";
}
$query = $em->createQuery($query);
$numRow = $query->count();
if ($numRow > 0) {
while ($query->fetch()) {
$repository = $em->getRepository('YCRYcrBundle:Adverts')->findBy(array(
'advTitle' => $title
));
/* echo "<h2><a href='#'> $title</a> </h2>";
echo "$desc <br /> <br />";
echo"<a href='/201308/View/YCR/index.php' class='link-button right'><span>Apply</span></a>"; */
}
}
/* else
echo "none found for \"<b>$SearchTerm </b>\"</br>Check spelling"; */
}
return $this->render('YCRYcrBundle:Search:search.html.twig', array('title' => $title->getAdvTitle()));
}
What is missing from this code to make it work, and or what is wrong?
Edit:
sorry of I was unclear. I am getting the following error:
FatalErrorException: Error: Call to undefined method Doctrine\ORM\Query::count() in C:\wamp\www\201308\src\YCR\YcrBundle\Controller\SearchController.php line 28
and do not know what is wrong as I am new to Symfony and doctrine.
This is what I have in my search.html.twig:
{% extends "YCRYcrBundle::layout.html.twig" %}
{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>YCR Job Search</title>
<link href="stylesheets/style.css" rel="stylesheet" type="text/css" />
<link href="stylesheets/colour.css" rel="stylesheet" type="text/css" />
</head>
<body onload="b = setInterval('clear()', 0);">
<div class="topDiv">
<div style="float: left;">
<img src="/201308/View/images/ycr.jpg" alt="ycr"></div>
<br/>
<!--<H2>Search for a Job</H2>-->
<div class="searchform">
<form id="formsearch" name="p" method="get" action="index.php">
<span>
<input name="Search_term" class="editbox_search" id="editbox_search" maxlength="80" value="<?php $this; ?>" type="text" />
</span>
<input type="image" name="button_search" src="images/search.gif" class="button_search" alt="" />
</form>
<br/>
<div id="search_results">
</div>
</div>
<!-- </div>-->
<script type="text/javascript" src="http://code.jquery.com/jquery- 1.7.2.min.js"></script><!--javascript jquery library-->
<script type="text/javascript" src="../View/scripts/Script.js"></script>
{% endblock %}
When the user searches, for example programmer, to display like this:
-Programmer
-a summary of the description of what a programmer entails
-a button/link that reads: read more, that takes me to a page with full description
You are pretty far off the mark. Query has no count function, that's a querybuilder function. You may write raw sql, but you are better served learning querybuilder : http://docs.doctrine-project.org/en/latest/reference/query-builder.html. Remember, doctrine is designed to give you a list of entities, that you pass to the twig to do stuff with.
Also, your twig won't do much, see the basics of usage in the very crude twig I've included. use {{entity.method}} or {{entity.field}} to get the various display properties of each entity. Use a twig foreach to loop through them all. Take a look at my example in your context, and then go read the twig documents to fill in the gaps. http://twig.sensiolabs.org/documentation
The Controller
public function searchAction(Request $request) {
if ($request->getMethod() == 'GET') {
$title = $request->get('Search_term');
$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository('YCRYcrBundle:Adverts')
->createQueryBuilder('a');
$searches= explode(' ', $title);
foreach ($searches as $sk => $sv) {
$cqb[]=$qb->expr()->like("CONCAT($sv, '')", "'%$sv%'");
}
$qb->andWhere(call_user_func_array(array($qb->expr(),"orx"),$cqb));
$adverts = $qb->getResult();
}
return $this->render('YCRYcrBundle:Search:search.html.twig'
, array('adverts' => $adverts));
}
And a twig file
{# Your other stuff #}
{% for advert in adverts %}
{{advert.getId}}
{# call the various method and fields for your display#}
{% endfor %}
you need to execute the query (with execute ) or you wont get an array. and you should be using the query builder instead DQL string concatenation. Read the doctrine doc on basic doctrine usage , the entity namespace seems to be incorrect too.
i quote you :
$query = $em->createQuery($query);
$numRow = $query->count();
should be at least :
$query = $em->createQuery($query);
$numRow = count($query->execute())
edit : not sure wether you would be getting an array or an ArrayCollection , check if the count fonction works on the ArrayCollection.

Geddy - create new item

I am an absolute beginner in node.js and geddy. I've followed a few tutorials and now I try to write something similar for my purposes.
When I try to create a new item, though, I get the following message:
/arithmetic_problem_types/function%20(id)%20%7B%20%20%20%20%20%20options.id%20=%20id;%20%20%20%20%20%20return%20helpersBase.urlFor.action(options);%20%20%20%20%7D not found.
I have no idea where this could come from. I've looked through the code and found nothing.
Controller:
var ArithmeticProblemTypes = function () {
this.respondsWith =[ 'html', 'json', 'xml', 'js', 'txt'];
this.index = function (req, resp, params) {
var self = this;
geddy.model.ArithmeticProblemType.all(function (err, arithmetic_problem_types) {
self.respond({
params: params, arithmetic_problem_types: arithmetic_problem_types
});
});
};
this.add = function (req, resp, params) {
this.respond({
params: params
});
};
this.create = function (req, resp, params) {
var self = this, arithmetic_problem_type = geddy.model.ArithmeticProblemType.create({
name: '1', title: 'open', numberType: '1', numberRanges: '1', operators: '1', askedFor: '1', specialProblemCategory: '1', askedForNumDenomOrBoth: '1',
reducedFractions:'1', mixedFractions: '1'
});
arithmetic_problem_type.save(function (err, data) {
if (err) {
params.errors = err;
self.transfer('add');
} else {
self.redirect({
controller: self.name
});
}
});
};
....................................................................
};
exports.ArithmeticProblemTypes = ArithmeticProblemTypes;
add.html.ejs
<div class="hero-unit">
<%= partial('_form', {params: params}); %>
</div>
index.html.ejs
<div class="hero-unit">
<h2>Arithmetic Problem Types List</h2>
<%- linkTo('Create a new Aritmetic Problem Type', addArithmeticProblemTypePath, {class: 'btn pull-right'}) %>
</div>
<% if (arithmetic_problem_types && arithmetic_problem_types.length) { %>
<% for (var i in arithmetic_problem_types) { %>
<div class="row todo-item">
<div class="span8">
<h3><%- linkTo(arithmetic_problem_types[i].title, arithmeticProblemTypePath(arithmetic_problem_types[i].id)) %></h3>
</div>
<div class="span4"><h3><i class="icon-list-alt"></i><%= arithmetic_problem_types[i].status; %></h3></div>
</div>
<% } %>
<% } %>
How can I get rid of that message and make it work?
EDIT:
This is the beginning of the _form.html.ejs file:
<%
var isUpdate = params.action == 'edit'
, formTitle = isUpdate ? 'Update this Arithmetic Problem Type' : 'Create a new Arithmetic Problem Type'
, action = isUpdate ? arithmeticProblemTypePath(params.id) + '?_method=PUT' : arithmeticProblemTypePath
, deleteAction = isUpdate ? arithmeticProblemTypePath(params.id) + '?_method=DELETE' : ''
, btnText = isUpdate ? 'Update' : 'Add'
, nameValue = isUpdate ? arithmeticProblemTypePath.name : ''
, errors = params.errors;
%>
<form id="arithmetic-problem-type-form" class="form-horizontal" action="<%= action %>" method="POST">
....
</form>
EDIT2:
Inspecting the page where I should write the name of the item and click the add button, I've found this
<div class="hero-unit">
<form id="arithmetic-problem-type-form" class="form-horizontal" action="function (id) {
options.id = id;
return helpersBase.urlFor.action(options);
}" method="POST">
<fieldset>
<legend>Create a new Arithmetic Problem Type</legend>
<div class="control-group">
<label for="title" class="control-label">Title</label>
<div class="controls">
<input class="span6" name="name" placeholder="enter name" type="text">
</div>
</div>
<div class="form-actions">
<input class="btn btn-primary" type="submit" value="Add">
</div>
</fieldset>
</form>
</div>
Indeed the message comes from the action attribute of the form element, but how can I solve it?
The message is telling you that the requested URL could not be found. AKA 404
/arithmetic_problem_types/function%20(id)%20%7B%20%20%20%20%20%20options.id%20=%20id;%20%20%20%20%20%20return%20helpersBase.urlFor.action(options);%20%20%20%20%7D
is definitely not a nice looking url. So i'm assuming there's something wrong with your form's action attribute. If that's what happened when you validate the form.
If that's what happened when you click the link to "Create a new arithmetic problem type" then you should probably put parenthesis after addArithmeticProblemTypePath

MODX - user profile photo upload

I am trying to allow users to upload photos to their profiles. I am sure I am doing something wrong...
What I currently have configured:
Update Profile Form
[[!UpdateProfile? &useExtended=`1` &preHooks=`user_profile_image` &postHooks=`redirect_profile_update`]]
<div class="update-profile">
<div class="updprof-error">[[+error.message]]</div>
[[+login.update_success:if=`[[+login.update_success]]`:is=`1`:then=`[[%login.profile_updated? &namespace=`login` &topic=`updateprofile`]]`]]
<form class="form" enctype="multipart/form-data" action="[[~[[*id]]]]" method="post">
<input type="hidden" name="nospam:blank" value="" />
<label for="fullname"><i class="icon-user"></i> <strong>[[!%login.fullname? &namespace=`login` &topic=`updateprofile`]]</strong>
<span class="error">[[+error.fullname]]</span>
</label>
<input type="text" name="fullname" id="fullname" value="[[+fullname]]" />
<label for="email"><i class="icon-envelope"></i> <strong>[[!%login.email]]</strong>
<span class="error">[[+error.email]]</span>
</label>
<input type="text" name="email:required:email" id="email" value="[[+email]]" />
<label for="test_field">Test Field
<span class="error">[[+error.custom_field]]</span>
</label>
<input type="text" name="test_field" id="test_field" value="[[+test_field]]" /><br/>
<div class="row clearfix">
<div class="label">Photo<span class="error">[[+fi.error.nomination_file]]</span></div>
<div class="input"><input id="nomination_file" name="nomination_file:required" type="file" value="[[+fi.nomination_file]]" maxlength="100000" /></div>
</div>
<br class="clear" />
<button class="btn-info btn btn-large" type="submit" name="login-updprof-btn">Update Profile</button>
</form>
</div>
User_profile_image snippet
<?php
// initialize output;
$output = true;
// get the current user name to create the file name as
$userName = $modx->user->get('username');
// valid extensions
$ext_array = array(`jpg', 'jpeg', 'gif', 'png');
// create unique path for this form submission
$uploadpath = 'assets/uploads/';
// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.
// EXAMPLE:
// this would put all file uploads into a new,
// unique folder every day.
// $uploadpath = 'assets/'uploads/'.date('Y-m-d').'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );
// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive
// is the file name empty (no file uploaded)
if($filename != '') {
// is this the right type of file?
if(in_array($ext, $ext_array)) {
//create file called the user name + pic
$filename = $userName . "pic".'.'.$ext ;
// full path to new file
$myTarget = $target_path . $filename;
// create directory to move file into if it doesn't exist
mkdir($target_path, 0755, true);
// is the file moved to the proper folder successfully?
if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
// set a new placeholder with the new full path (if you need it in subsequent hooks)
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
// set the permissions on the file
if (!chmod($myTarget, 0644)) { /*some debug function*/ }
} else {
// File not uploaded
$errorMsg = 'There was a problem uploading the file.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
} else {
// File type not allowed
$errorMsg = 'Type of file not allowed.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
// if no file, don't error, but return blank
} else {
$hook->setValue($sf, '');
}
}
return $output;
1) fix quote in this line
$ext_array = array(`jpg', 'jpeg', 'gif', 'png');
2) remove all :required in name fields.
3) instead
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
type
$hook->setValue($sf, $uploadpath . $filename);
4) after mkdir($target_path, 0755, true); add
if(file_exists($myTarget) {
chmod($myTarget,0755); //Change the file permissions if allowed
unlink($myTarget); //remove the file
}
For anyone who references this post:
move user_profile_image back to the prehooks like this:
&preHooks=`user_profile_image`
and at line 59 add the missing ")" like this:
if(file_exists($myTarget)) {

variable in class name jade

I can't set a variable name in a class in jade:
.flag_#{ session.locale } #{ session.locale }
I have:
<div class="flag_" >en</div>
And I'd like to have
<div class="flag_en" >en</div>
Thanks
Try this (have not tested):
div(class="flag_#{ session.locale }") session.locale
As for pug#2.0.0-alpha3 works this way:
div(class="flag_" + session.locale) session.locale
Here's another approach:
mixin formButton(text, type, extra_classes)
- var default_classes = 'btn btn-primary'
if extra_classes
- var classes = default_classes + ' ' + extra_classes
else
- var classes = default_classes
if type
button(class=classes type=type) !{text}
else
button(class=classes type="submit") !{text}
Example 1:
Usage:
+formButton('Text')
Result:
<button type="text" class="btn btn-primary" type="submit">Text</button>
Example 2:
Usage:
+formButton('Text', 'button')
Result:
<button type="text" class="btn btn-primary" type="button">Text</button>
Example 3:
Usage:
+formButton('Text', 'button', 'extra-class')
Result:
<button type="text" class="btn btn-primary extra-class" type="button">Text</button>
You can also use conditional statements to do this like
if liked == true
span.like.active
else
span.like
You can also use a template literal:
- const session = { locale: 'en' }
div(class=`flag_${session.locale}`) #{session.locale}
//- Just to show more options:
div(class=`flag_${session.locale}`)= session.locale
div(class=`flag_${session.locale}`) Current language is #{session.locale}
div(class=`flag_${session.locale}`)= `Current language is ${session.locale}`
Output (using Pug 2.0.4):
<div class="flag_en">en</div>
<div class="flag_en">en</div>
<div class="flag_en">Current language is en</div>
<div class="flag_en">Current language is en</div>

When I pass res.render object then in .ejs file it is undefined

I want to show values of post object in my profilearea.ejs file.But when it renders to profilearea.ejs then it gives an error that "post is not defined".
Here is the code in node.js
PersonalInfo.findOne({username:req.body.name}, function(err,post){
if(err || !post)
{
console.log("find is not done");
}
else
res.render('profilearea.ejs', {post:post});
}
})
This is the code in profilearea.ejs file
<section id="notification" data-role="page" >
<header data-role="header" data-theme="b"><h2>INFORMATION</h2></header>
<div data-role="content">
<p> <%= post%> </p>
</div>
</section>
I think part of the issue may be in not stringifying the object prior to rendering.
Try:
else {
var jpost = JSON.stringify(post);
res.render('profilearea.ejs', {post:jpost});
}

Resources