How to load file JS and CSS using herbert, enqueue - wordpress

I'm following the example of the official website.
$enqueue->front([
'as' => 'vueJS',
'src' => Helper::assetUrl('/js/vue.js')
]);
And I need it to load in a view, I use the example of the official page.
<!DOCTYPE html>
<html>
<head>
<title>Profesores</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</body>
</html>
I use a controller to load the view
public function getProfesores()
{
$profesores = Profesor::all();
return view('#MyPlugin/profesores/lista.twig', [
'title' => 'My Demo',
'content' => 'Congrats on your demo view.',
'data'=> json_response($profesores->toArray())
]);
}
Maybe it's easy but it does not work for me, can someone help me?

Related

How to use Select2 Ajax in Symfony combined with Twig

I'm trying to use Select2 Ajax in my HTML page to seach through my dataset. I have multiple errors:
Search bar is almost invisible
If does not shown any data
ProductController
/**
* #Route("/api/product/v1/select2search", name="api_product_search")
*/
public function viewAction()
{
$products = $this->productRepository->findAll();
foreach ($products as $entity) {
$response1[] = array(
'id' => $entity['id'],
);
$response2[] = array(
'name' => $entity['name'],
);
}
return new JsonResponse(([$response1,$response2]));
}
My twig file:
{% extends 'base.html.twig' %}
{% block body %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- select2 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/gh/ttskch/select2-bootstrap4-theme#master/dist/select2-bootstrap4.min.css" rel="stylesheet">
<select class="js-data-example-ajax"></select>
<script>
$('.js-data-example-ajax').select2({
ajax: {
url: 'http://127.0.0.1:8000/api/product/v1/select2search',
dataType: 'json'
// Additional AJAX parameters go here; see the end of this chapter for the full code of this example
}
});
</script>
{% endblock %}
The current visual screen:
You can not see the bar as described above.
My goal to achieve is this:

Snappy footer generate a weird margin proportional to its size

first, let me show you the piece of code that makes the bug happen.
Here is the code of my footer :
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div style="height: 1rem; background-color: #1C440C">
<span>Hello world</span>
</div>
</body>
</html>
The main page :
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
Hello world page
</body>
</html>
And the controller :
/**
* #Route("/path", name="myurl")
*/
public function toPdf()
{
$html = $this->renderView('pdf/page.html.twig');
$footer = $this->renderView('pdf/footer2_pdf.html.twig');
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
'footer-html' => $footer
)),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
Il I set the footer height to 1 (like it is in the code sample), I get this kind of pdf footer :
the distance between the "hello world" and the bot of the page looks like the default margin of the pdf, so it looks like it is ok.
Then, if I change the height to 5rem to get a larger footer, I get this :
The footer is larger, but the margin between the footer and the end of the page just increased like crazy. I don't really understand why.
Thank you for reading, if you know the answer, feel free to answer.
For future reference, just set the bottom margin with this solution :
pdf page margins with snappy and symfony2
Cheers !

Flash message is not shown when trying to use getFlashBag()

Hello friendly people,
I am following a tutorial on Symfony, in which I try to display a flash message, but even though I followed the instructions, no flash message is shown.
Here is my function viewAction in my AdvertController:
public function viewAction($id)
{
return $this->render('NeoPlatformBundle:Advert:view.html.twig', array('id' => $id));
}
public function addAction(Request $request)
{
$session = $request->getSession();
$session->getFlashBag()->add('info' , 'This is a flash message');
$session->getFlashBag()->add('info', 'This is a second flash message');
return $this->redirectToRoute('neo_platform_view', array('id' => 5));
}
When I go to
http://localhost/Symfony/web/app_dev.php/platform/add
I only get this:
My view.html.twig is as follows:
{# src/Neo/PlatformBundle/Resources/view/Advert/view.html.twig #}
<!DOCTYPE html>
<html>
<head>
<title>Display of the announcement {{id}}</title>
</head>
<body>
<h1>Display of the announcement n°{{id}}!</h1>
<div>
{#We display all flash messages, whose name is "info" #}
{% for message in app.session.flashbag.get('info') %}
<p>Flash message : {{message}}</p>
{% endfor %}
</div>
</body>
</html>
Any clue?
Thanks in advance!

The exit status code '1' says something went wrong [knp snappy]

I'm working with knp snappy bundle for generate reports from my app. But doesn't work, when I call my controller for generate the pdf throws the next error:
The exit status code '1' says something went wrong:
stderr: "Loading pages (1/6)
[> ] 0%
[======> ] 10%
[=======> ] 12%
Warning: Failed to load file:///gestionresiduospel/web/bundles/usuario/css/bootstrap.css (ignore)
Warning: Failed to load file:///gestionresiduospel/web/bundles/usuario/js/bootstrap.js (ignore)
[============================================================] 100%
Counting pages (2/6)
[============================================================] Object 1 of 1
Resolving links (4/6)
[============================================================] Object 1 of 1
Loading headers and footers (5/6)
Printing pages (6/6)
[> ] Preparing
[============================================================] Page 1 of 1
Done
Exit with code 1 due to network error: ContentNotFoundError
"
stdout: ""
command: "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" --lowquality "C:\Users\rodrigo\AppData\Local\Temp\knp_snappy5682878973ade7.09664058.html" "C:\Users\rodrigo\AppData\Local\Temp\knp_snappy56828789746968.46649162.pdf".
My controller is this:
public function historicosDetallePdfAction($id)
{
$em = $this->getDoctrine()->getManager();
//gets residuos peligrosos.
$solicitudRetiro= $em->getRepository('SolicitudRetiroBundle:SolicitudRetiro')->find($id);
//gets residuos no peligrosos
$residuosPRetirados = $em->getRepository('SolicitudRetiroBundle:RetiroResiduo')->findResiduos($id);
//retorna los residuos no peligrosos en la solicitud
$residuosNPRetirados = $em->getRepository('SolicitudRetiroBundle:RetiroResiduoNoPeligroso')->findResiduosNoPeligrosos($id);
// view generator
$html = $this->renderView('SolicitudRetiroBundle:Pdf:resumenSolicitudResiduoRetirado.html.twig', array(
'solicitudRetiro' => $solicitudRetiro,
'residuosRetirados' => $residuosPRetirados,
'residuosNoPel' => $residuosNPRetirados ));
// pdf generator
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="historico.pdf"'
)
);
}
I copied my url and run into console[CMD] with wkhtmltopdf.exe. In console my pdf is created but when I see the file only shows my login screen. So I think could be a issue about permission into my controller but I don't know how I pass this.
In other hand, if you know about another pdf generator(from html) that working into symfony this could be help me too.
I'm working under symfony2.7
This mean's that one of the resources in your HTML file can't be loaded by wkhtmltopdf, check in your HTML file if all your resources have an absolute URL like this : http://www.yourserver.com/images/myimage.jpg
If it's not the case try to set it :
{{ app.request.schemeAndHttpHost ~ 'resource relative url' }}
If you are loading assets with assetic in {% stylesheets %} or {% javascript %} or {% image %} you can also do
{{ app.request.schemeAndHttpHost ~ asset_url }}
I had two kind of problems here once:
The first one was because kpn snappy fails when trying to convert a *.js file. So I had to take *.js files in my case.
The second one was because of the path. I had to use the absolute filesystem path. By this, I mean, something like: /home/ubuntu/workspace/bootstrap/css/bootstrap.css this is used in href tag used in *html.twig file that is then transformed to pdf by snappy.
By doing this, I used some twig global variables.
twig:
form:
resources:
- 'MyBundle:Form:fields.html.twig'
- 'MyUploaderBundle:Form:fields.html.twig'
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
globals:
pathToWeb: "%kernel.root_dir%/../web"
bootstrapCss: "/home/ubuntu/workspace/MyApp/web/bootstrap/css/bootstrap.css"
mainCss: "/home/ubuntu/workspace/MyApp/web/css/main.css"
layoutCss: "/home/ubuntu/workspace/MyApp/web/css/layout.css"
In twig
<link rel="stylesheet" type="text/css" href="{{ bootstrapCss }}">
<link rel="stylesheet" type="text/css" href="{{ layoutCss }}">
<link rel="stylesheet" type="text/css" href="{{ mainCss }}">
You can use absolute_url() twig function{{ absolute_url(asset('assets/image.jpg')) }}
For me this worked, the error was from html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
{% for path in encore_entry_css_files('app') %}
<link rel="stylesheet" href="{{ absolute_url(path) }}">
{% endfor %}
</head>
This problem never gets old, I encountered this just now and I manage to solve it, here's how.
This problem mostly happens in Windows so this solution is for that.
1. Install this composer dependency wemersonjanuario/wkhtmltopdf-windows
composer require wemersonjanuario/wkhtmltopdf-windows "0.12.2.3"
2. Open your config/snappy.php and use this config.
<?php
return [
'pdf' => [
'enabled' => true,
'binary' => base_path('vendor\wemersonjanuario\wkhtmltopdf-windows\bin\64bit\wkhtmltopdf'),
'timeout' => false,
'options' => [],
'env' => [],
],
'image' => [
'enabled' => true,
'binary' => base_path('vendor\wemersonjanuario\wkhtmltoimage-windows\bin\64bit\wkhtmltoimage'),
'timeout' => false,
'options' => [
'enable-local-file-access' => true,
'keep-relative-links' => true,
],
'env' => [],
],
];
3. Make sure the blade file you loading for pdf does not contain external links, like the one below.
<head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght#0,300;0,400;0,600;0,700;1,300;1,400;1,600;1,700&display=swap" rel="stylesheet">
</head>
4. Make sure you load assets using public_path()
<link href="{{ public_path('css/pdf.css') }}" rel="stylesheet">
<img src="{{ public_path('fancy-image.png') }}">

Telerik TreeView for ASP.NET MVC ajax woes

Telerik's TreeView control, although fancy and with a lot of functionality is proving to be a nightmare for me now. However I could not find a better TreeView control which supports collapsing/expanding etc. and has a little bit of documentation. Here's my problem.
This is the site master : _Layout.cshtml
<!DOCTYPE HTML>
<html>
<head>
<title>#ViewBag.Title</title>
<!--
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/custom.css")" rel="stylesheet" type="text/css" />-->
#(Html.Telerik().StyleSheetRegistrar()
.DefaultGroup(group =>
group.Add("telerik.common.css")
.Add("~/Content/Site.css")
.Add("~/Content/custom.css")
.Add("~/Content/themes/humanity/jquery-ui-1.8.18.custom.css")
.Combined(true)
.Compress(true)))
</head>
<body>
<div class="page">
<header>
<div id="header-logo">
<img alt="X" src="../../Content/Images/logo100.png"/>
</div>
<div id="title">
<h1>title</h1>
</div>
#(Html.Telerik().Menu()
.Name("menu")
.Items(menu =>
{
menu.Add().Text("Home").Action("Index", "Home");
menu.Add().Text("Products")
.Items(item =>
{
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
});
menu.Add().Text("Events").Action("Index", "Events");
menu.Add().Text("About Us").Action("About", "Home");
menu.Add().Text("Admin").Action("Index", "Admin");
})
.HtmlAttributes(new { style = "text-align:left;" }))
</header>
<section id="main">
#RenderBody()
</section>
<footer>
</footer>
</div>
#(Html.Telerik().ScriptRegistrar()
.Scripts(script=>script.Add("~/Scripts/custom.js"))
.Globalization(true)
.DefaultGroup(group => group.Combined(true)
.Compress(true)))
</body>
</html>
This is the base page view : Index.cshtml
#{
ViewBag.Title = "Admin";
}
<h2>
Admin Index</h2>
<div id="navAdminLeft">
#(Html.Telerik().TreeView()
.Name("AdminNavTree")
.Items(item =>
{
item.Add().Text("Products");
item.Add().Text("Categories");
item.Add().Text("Materials");
item.Add().Text("Finishes");
item.Add().Text("Packaging");
item.Add().Text("File Manager");
item.Add().Text("CategoryTree");
})
.ClientEvents(events => events.OnSelect("loadAdminContent"))
)
</div>
<div id="adminContent">
</div>
<script type="text/javascript">
function loadAdminContent(e) {
$.ajax({
type: "GET",
cache: false,
url: "Admin/" + e.item.innerText,
data: {},
success: function (data) {
$("#adminContent").html(data);
}
});
}
</script>
whenever the user selects a node on the #AdminNavTree the page fetches the content to be displayed and populates #adminContent. I am trying to build an edit page where there is a category tree listed in one div and when the user clicks on any of the category on that div, the details are ajax loaded into another div on the same page. Here is the partial view with the category tree that gets loaded into #adminContent: _CategoryTree.cshtml
#using xxx.Models.Navigation
#model IEnumerable<NavigationItem>
<div id="categoryTree">
#{Html.Telerik().TreeView()
.Name("ctree")
.BindTo(Model, mappings =>
mappings.For<NavigationItem>(binding => binding
.ItemDataBound((currentItem, navigationItem) =>
{
currentItem.Text = navigationItem.Text;
currentItem.Expanded = true;
})
.Children(child => child.Items)
))
.ClientEvents(events=>events.OnSelect("loadContent"))
.Render();
}
</div>
<div id="detail"></div>
<script type="text/javascript">
function loadCategoryDetail(e) {
$.ajax({
type: "POST",
url: "Admin/CategoryDetails",
data: { id: $("#ctree").data("tTreeView").getItemText(e.item) },
success: function (data) {
$("#detail").html(data);
}
});
}
</script>
the detail page that is ajax loaded does not contain any telerik controls so listing code for that is a non issue.
The PROBLEM : this will not render. As soon as it tries rendering #ctree treeview it starts throwing all kind of script errors, specifically it ignores loadCategories (says not found). So far I think what is happening is the ajax loaded partial page that contains the treeview is reloading the jquery lib destroying all old bindings and functions in the script. Is there a way to make this work, two treeviews on one page, one previously loaded, one in a ajax loaded partial view, both binding to separate data?
I've had good success with jsTree... doesn't help with your telerik question, but might be worth checking out.
http://www.jstree.com/

Resources