How to show image in Excel file download by Maatwebsite package in Laravel 8 project? - excel

I want to show images from the database in an Excel file downloaded using the Laravel Maatwebsite package.
Controller
$data['company_names'] = Company::where('id', Auth::user()->com_id)
->first(['company_name']);
$data['companies'] = $companies;
$data['users'] = $users;
$data['regions'] = $regions;
$data['roles'] = $roles;
$exl = Excel::download(new EmployeeReportExport($data),
'Employee-Report.xlsx');
ob_end_clean();
return $exl;
Export Code
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
class EmployeeReportExport implements FromView
{
public function __construct($data)
{
$this->data = $data;
}
public function view(): View
{
return view('back-end.premium.hr-reports.employee-report.employee-bulk-report-excel', [
'data' => $this->data
]);
}
}
Blade
<td>{{ $i++ }}</td>
<td>{{ $usersData->company_assigned_id ?? '' }}</td>
<td>{{ $usersData->first_name . ' ' . $usersData->last_name }}</td>
<td><img src="{{ asset($usersData->profile_photo) ?? '' }}" alt=""></td>
<td>{{ $usersData->email ?? null }}</td>
<td>{{ $usersData->phone }}</td>
But it's not showing in the Excel file; it returns the following error.
file_get_contents(http://127.0.0.1:8000/uploads/profile_photos/1667727818.jpg):
failed to open stream: HTTP request failed!

Related

Twig : Unset element from array

I have an array of elements composed of key => value for example:
arr = { 156 : 'one', 99 : 'tow' }
I want to remove an element from the array depending on the key. Like doing unset() in php ? Is it possible ?
You can also use the filter pipe like this:
{% set arr = arr | filter((v, k) => k != '99') %}
You can extend twig to do this
<?php
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension {
public function getFunctions(){
return [
new \Twig\TwigFunction('unset', [$this, 'unset'], [ 'needs_context' => true, ]),
];
}
/**
* $context is a special array which hold all know variables inside
* If $key is not defined unset the whole variable inside context
* If $key is set test if $context[$variable] is defined if so unset $key inside multidimensional array
**/
public function unset(&$context, $variable, $key = null) {
if ($key === null) unset($context[$variable]);
else{
if (isset($context[$variable])) unset($context[$variable][$key]);
}
}
}
Usage inside twig:
<h1>Unset</h1>
{% set foo = 'bar' %}
{% set bar = { 'foo' : 'bar', } %}
<h2>Before</h2>
<table>
<tr>
<td>foo</td><td>{{ foo | default('not applicable') }}</td>
</tr>
<tr>
<td>bar.foo</td><td>{{ bar.foo | default('not applicable') }}</td>
</tr>
</table>
{% do unset('foo') %}
{% do unset('bar', 'foo') %}
<h2>After</h2>
<table>
<tr>
<td>foo</td><td>{{ foo | default('not applicable') }}</td>
</tr>
<tr>
<td>bar.foo</td><td>{{ bar.foo | default('not applicable') }}</td>
</tr>
</table>
output
Before
|------------------------------|------------------------------|
| foo | bar |
| bar.foo | bar |
|------------------------------|------------------------------|
After
|------------------------------|------------------------------|
| foo | not applicable |
| bar.foo | not applicable |
|------------------------------|------------------------------|

Files with .twig extension don't work

I am new with twig and the problem is that when I want to use .twig files it doesn't work same with .html.twig. But when I switch to .html file is working fine. Where is the problem?
EDIT:
index.php:
<?php
use App\Kernel;
use Symfony\Component\Debug\Debug;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
require __DIR__.'/../vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('../templates');
$twig = new Twig_Environment($loader, array(
'cache' => '../compilation_cache',
));
$collection = new RouteCollection();
$collection->add('index', new Route('/', array(
)));
// Twig
if (!isset($_SERVER['APP_ENV'])) {
if (!class_exists(Dotenv::class)) {
throw new \RuntimeException('APP_ENV environment variable is not
defined. You need to define environment variables for configuration or
add "symfony/dotenv" as a Composer dependency to load variables from a
.env file.');
}
(new Dotenv())->load(__DIR__.'/../.env');
}
$env = $_SERVER['APP_ENV'] ?? 'dev';
$debug = $_SERVER['APP_DEBUG'] ?? ('prod' !== $env);
if ($debug) {
umask(0000);
Debug::enable();
}
if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) {
Request::setTrustedProxies(explode(',', $trustedProxies),
Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) {
Request::setTrustedHosts(explode(',', $trustedHosts));
}
$kernel = new Kernel($env, $debug);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
//Product list TEST TWIG->Delete if not using!
$products = 'products';
$products = array(
array('name' => 'Notebook', 'description' => 'Core i7', 'value' =>
800.00, 'date_register' => '2017-06-22',),
array('name' => 'Mouse', 'description'=> 'Razer', 'value' => 125.00,
'date_register' => '2017-10-25',),
array('name' => 'Keyboard', 'description' => 'Mechanical Keyboard',
'value'=> 250.00, 'date_register' => '2017-06-23',)
);
$template = $twig->load('index.twig');
echo $template->display(array('products' => $products));
index.twig:
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Twig Example</title>
</head>
<body>
<table border="1" style="width: 80%;">
<thead>
<tr>
<td>Product</td>
<td>Description</td>
<td>Value</td>
<td>Date</td>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>{{ product.name }}</td>
<td>{{ product.description }}</td>
<td>{{ product.value }}</td>
<td>{{ product.date_register|date("m/d/Y") }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
I want to load the array from the index.php file but it throw me error:
Unable to find template "layout.html" (looked into: ../templates) in index.twig at line 1.
I am not using file layout.html anymore the file is deleted. When I refactor index.twig file to index.html it disappears.
EDIT(2):
twig.yaml(/config/packages/twig.yaml):
twig:
paths: ['%kernel.project_dir%/templates']
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
The problem was in the index.php file. When I commented/deleted part:
if (!isset($_SERVER['APP_ENV'])) {
if (!class_exists(Dotenv::class)) {
throw new \RuntimeException('APP_ENV environment variable is not
defined. You need to define environment variables for configuration or
add "symfony/dotenv" as a Composer dependency to load variables from a
.env file.');
}
(new Dotenv())->load(__DIR__.'/../.env');
}
$env = $_SERVER['APP_ENV'] ?? 'dev';
$debug = $_SERVER['APP_DEBUG'] ?? ('prod' !== $env);
if ($debug) {
umask(0000);
Debug::enable();
}
if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) {
Request::setTrustedProxies(explode(',', $trustedProxies),
Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) {
Request::setTrustedHosts(explode(',', $trustedHosts));
}
$kernel = new Kernel($env, $debug);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Everything works fine...

Cannot use Ember associations

I have been trying to make this work for several days now. I cannot access a profile object from its associated user object. I have the latest versions of Ember and ember-data
Ember-data: 1.0.0-beta15
Ember: 1.10.0 production
I have a simple table view that lists my users and a couple properties. Here is the view:
<script type="text/x-handlebars" data-template-name="users/verification-candidates">
<div class="small-12 column">
<h1>Candidates for Verification</h>
<table>
<tr>
<th>System ID</th>
<th>Email</th>
<th>Created At</th>
<th>Legal First Name</th>
<th>Legal Last Name</th>
<th></th>
<th></th>
</tr>
{{#each user in model itemController="candidate" }}
<tr>
<td> {{ user.id }}</td>
<td> {{ user.email }}</td>
<td>{{ user.created_at }}</td>
<td>{{ user.legal_first_name }}</td>
<td>{{ user.legal_last_name }}</td>
<td><button id="verify" {{ action "markVerified" }}>Verify</button></td>
<td><button id="disable" {{ action "markDisabled" }}>Disable</button></td>
</tr>
{{/each}}
</table>
</div>
</script>
The models are like so:
App.Profile = DS.Model.extend({
user: DS.belongsTo('user'),
incognito_name : DS.attr('string'),
advisor_id : DS.attr('number'),
created_at : DS.attr('date'),
//etc..
App.User = DS.Model.extend({
profile: DS.belongsTo('profile',{ async: true }),
email: DS.attr('string'),
sign_in_count: DS.attr('number'),
last_sign_in_at: DS.attr('date'),
//etc...
I am using the rest adapter:
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://localhost:1337',
defaultSerializer: 'json'
});
Pertinent routes:
App.Router.map(function(){
this.resource('users', { path: '/users'}, function(){
this.route('verification-candidates');
});
this.resource('profiles', { path: '/profiles' }, function(){
})
});
App.UsersRoute = Ember.Route.extend({
model: function(){
return this.store.find('user');
}
});
App.ProfilesRoute = Ember.Route.extend({
model: function(){
return this.store.find('profile');
}
})
App.UsersVerificationCandidatesRoute = Ember.Route.extend({
model : function(){
var items = this.store.find('user', { role: "advisor", disabled: false, is_verified: false });
return items;
},
})
My server is a sails.js back end, which accesses a database created by a Rails application.
I want to alter the profile in this object controller, but cannot access it in any meaningful form:
App.CandidateController = Ember.ObjectController.extend({
actions: {
markVerified: function(){
var user = this.get('model');
var profile = user.get('profile');
console.log(profile); //output 1
console.log(profile.incognito_name); //output 2
}
}
});
The output2 is undefined. Output 1 gives me some sort of object with properties __nextSuper, __ember_meta, a bunch of other things, isFulfilled, and content. But, no object properties from the model definition. This appears to be a promisearray,but, I thought this was the way to get a related object. Meanwhile, when I try to treat it as a PromiseArray, per the documentation, i get null, like this:
App.CandidateController = Ember.ObjectController.extend({
actions: {
markVerified: function(){
var user = this.get('model');
user.get('profile').then(function(content){
console.log("promise content is " + content);
//prints 'promise content is null'
})
//console.log(profile);
//console.log(profile.incognito_name);
}
}
I am fairly certain all my back end server/client things are in order, as I can access the user objects and work with them on the page. I am thinking it may be related to how the profile relates to the user via advisor_id, but, I am so confused right now. I am very much at my wit's end.

Only Display a # of Characters in Twig

I am very unfamiliar with twig. Here's what I have:
{% if wp.get_post_meta(post.ID, '_property_website').0 %}
<tr>
<th>{{ wp.__('Website', 'aviators') }}:</th>
<td>{{ wp.get_post_meta(post.ID, '_property_website').0 }}
</td>
</tr>
{% endif %}
I need to restrict this output to 35 characters without killing the link. It needs to still be active but only display 35 characters, plus ideally it would end with... to designate that the url is cut off but that's a bonus. Can anyone help?
I believe http://twig.sensiolabs.org/doc/filters/slice.html is what you are looking for
EDIT
Just found that Twig has an extension called text it includes the wordwrap filter that is exactly what you're looking for
Link: https://github.com/fabpot/Twig-extensions/blob/master/lib/Twig/Extensions/Extension/Text.php
You can make your own Twig Extension. It's very easy.
First you must create the file with the filter code:
<?php
//Acme/AcmeBundle/Twig/AnExtension.php
namespace Acme\AcmeBundle\Twig;
class AnExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('cutText', array($this, 'cutTextFilter'))
);
}
public function cutTextFilter($text, $size = 50)
{
if (strlen($text) > $size)
{
return substr($text, 0, $size) . '...';
}
else
{
return $text;
}
}
public function getName()
{
return 'an_extension';
}
}
Then edit the services.yml file from this bundle, located at: /Acme/AcmeBundle/Resources/config/services.yml and add:
services:
acme.twig.an_extension:
class: Acme\AcmeBundle\Twig\AnExtension
tags:
- { name: twig.extension }
and now you can use the filter in your code:
<a href="http://{{ wp.get_post_meta(post.ID, '_property_website').0 }}">
{{ wp.get_post_meta(post.ID, '_property_website').0 | cutText(30) }}
</a>
More info: http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Pylons controller loose formating YUI

I have the following controller:
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from webhelpers.html.tags import HTML
from improve.lib.base import BaseController, render
from improve import model
import improve.model.meta as meta
import improve.lib.helpers as h
log = logging.getLogger(__name__)
class AlarmsController(BaseController):
def list(self):
c.alarms = meta.Session.query(model.Alarms).all()
return render('../public/listalarms_table.html')
rendered by this template (listalarms_table.html):
...
<div id="markup">
<table id="alarms">
<thead>
<tr>
<th>Id</th>
<th>Severity</th>
<th>Node</th>
<th>Count</th>
<th>Last Alarm</th>
<th>Log Msg</th>
<th>AckUser</th>
</tr>
</thead>
<tbody>
% for alarms in c.alarms:
<tr>
<td>${alarms.alarmid.__repr__()|n}</td>
<td>${alarms.severity.__repr__()|n}</td>
<td>${alarms.nodeid.__repr__()|n}</td>
<td>${alarms.counter.__repr__()|n}</td>
<td>${alarms.lasteventtime.__repr__()|n}</td>
<td>${alarms.logmsg.__repr__()|n}</td>
<td>${alarms.alarmackuser.__repr__()|n}</td>
</tr>
% endfor
</tbody>
</table>
</div>
<script type="text/javascript">
YAHOO.util.Event.addListener(window, "load", function() {
YAHOO.example.EnhanceFromMarkup = new function() {
var myColumnDefs = [
{key:"id",label:"Id", sortable:true},
{key:"severity",label:"Severity", sortable:true}
{key:"node",label:"Node", sortable:true}
{key:"count",label:"Count",formatter:YAHOO.widget.DataTable.formatNumber,sortable:true},
{key:"lastalarm",label:"LastAlarm",formatter:YAHOO.widget.DataTable.formatCurrency,sortable:true},
{key:"logmsg",label:"Log Msg"}
];
this.myDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get("alarms"));
this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
this.myDataSource.responseSchema = {
fields: [{key:"id"},
{key:"severity"},
{key:"node"},
{key:"count", parser:"number"},
{key:"lastalarm", parser:"date"} // point to a custom parser
]
};
this.myDataTable = new YAHOO.widget.DataTable("markup", myColumnDefs, this.myDataSource,
{caption:"Example: Progressively Enhanced Table from Markup",
sortedBy:{key:"id",dir:"asc"}}
);
};
});
The problem:
If I call it using http://myserver:port/listalarms_table.html , I see the correct formating of the YUI table but instead of the data I get the alarms.alarmid.repr()|n instead of the real data
If i call it http://myserver:port/alarms/list I get the data correctly but I loose the YUI format...
How can i get the data with the correct YUI layout?
Thx

Resources