I am struggling with my final project. I need to join 2 Tables "book" and "idlist" and execute the values in index.html.
Here is python and html code (also idlist Tablebook Table).
If someone knows where is a mistake, I will be grateful!
#app.route("/", methods=["GET", "POST"])
#login_required
def index():
"""Show reading list"""
if request.method == "GET":
# Execute list joining "book" and "idlist" tables
list = db.execute("SELECT Title1, Status, LastUpdate, Author, Year, Country, Language FROM idlist INNER JOIN book on idlist.Title1=book.Title WHERE id=:id",
id=session["user_id"])
# If the user has no list yet
if not list:
el = {'Title1': "No", 'Author': "No", 'Year': "No", 'Country': "No", 'Language': "No", 'Status': "No", 'LastUpdate': "No"}
return render_template("index.html")
else:
return render_template("index.html")
return render_template("index.html")
html should execute the values from the joined tables
{% extends "layout.html" %}
{% block title %}
Index
{% endblock %}
{% block main %}
<table style="width:100%">
<tr>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Country</th>
<th>Language</th>
<th>Status</th>
<th>Last update</th>
</tr>
{% for el in list %}
<tr>
<td>
{{ el.Title1 }}
</td>
<td>
{{ el.Author }}
</td>
<td>
{{ el.Year }}
</td>
<td>
{{ el.Country }}
</td>
<td>
{{ el.Language }}
</td>
<td>
{{ el.Status }}
</td>
<td>
{{ el.LastUpdate }}
</td>
</tr>
{% endfor %}
</table>
{% endblock %}
Here is the error while I login with user id 16:
RuntimeError: near "update": syntax error [SQL: 'SELECT Title, Status, update, Author, Year, Country, Language FROM idlist INNER JOIN book on idlis
t.Title=book.Title WHERE id=16']
My program should join 2 Tables "book" and "idlist" and execute the values in index.html.
The main issue was in the wrong use of the "render_template()" more presisely that I haven't passed any data into it. As I needed to express my "list" in html form, the right use would be "return render_template("index.html", list=list)"
Below is the solution:
#app.route("/", methods=["GET", "POST"])
#login_required
def index():
"""Show reading list"""
if request.method == "GET":
quote1 = db.execute("SELECT quote FROM quotes ORDER BY random() LIMIT 1")
# Execute list joining "book" and "idlist" tables
list = db.execute("SELECT Title1, Status, LastUpdate, Author, Year, Country, Language FROM idlist INNER JOIN book on idlist.Title1=book.Title WHERE id=:id",
id=session["user_id"])
# If the user has no list yet
if not list:
el = {'Title1': "No", 'Author': "No", 'Year': "No", 'Country': "No", 'Language': "No", 'Status': "No", 'LastUpdate': "No"}
return render_template("index.html", yourquote=quote1[0]["quote"])
return render_template("index.html")
Here is html form:
{% extends "layout.html" %}
{% block title %}
Index
{% endblock %}
{% block main %}
<table style="width:100%">
<tr>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Country</th>
<th>Language</th>
<th>Status</th>
<th>Last update</th>
</tr>
{% for el in list %}
<tr>
<td>
{{ el.Title1 }}
</td>
<td>
{{ el.Author }}
</td>
<td>
{{ el.Year }}
</td>
<td>
{{ el.Country }}
</td>
<td>
{{ el.Language }}
</td>
<td>
{{ el.Status }}
</td>
<td>
{{ el.LastUpdate }}
</td>
</tr>
{% endfor %}
</table>
<tr>
<p> </p>
</tr>
<a class="card-header" href="/"><span class="blue">Inspire yourself</span></a>
<tr>
<p> </p>
</tr>
<a class="card-title"><span class="grey"><p>{{ yourquote }}</p></span></a>
{% endblock %}
Related
I'm trying to style my line of code:
<td class="{% if inven < 10 %}color-green-primary{% else %}color-red-primary{% endif %}">{{inven.quantityInventory}}</span></td>
It should change color depending on the value that is presented.
The bad thing is that it always shows it to me in red (in else). what am I doing wrong?
html
{% for inven in inventory %}
<tr>
<td><strong>{{inven.codigoInventory}}</strong></td>
<td>{{inven.descriptionInventory}}</td>
<td>${{inven.unitPriceInventory}}</td>
<td class="{% if inven < 10 %}color-green-primary{% else %}color-red-primary{% endif %}">{{inven.quantityInventory}}</span></td>
<td>{{inven.dealer}}</td>
<td>{{inven.invoiceNumber}}</td>
<td>
<div class="badge bg-soft-danger font-size-12">{{inven.status}}</div>
</td>
<td>Detail</td>
<td>Edit</td>
<td><a href="{% url 'inventory:eliminar_inventory' inven.id%}" class="text-danger" >Delete</a></td>
</tr>
{% endfor %}
views.py
def list_inventory(request):
if request.method == 'POST':
fromdate=request.POST.get('fromdate')
todate = request.POST.get('todate')
searchresult = Inventory.objects.filter(fecha_registro__range=(fromdate, todate))
return render(request,'inventory/inventory-list.html',{'inventory':searchresult})
else:
displaydata = Inventory.objects.all()
return render(request, 'inventory/inventory-list.html', {'inventory': displaydata})
You should be comparing against inven.quantityInventory not just inven. It does not make sense to compare a model instance with an int, compare against an int attribute
<td class="{% if inven.quantityInventory < 10 %}color-green-primary{% else %}color-red-primary{% endif %}">{{ inven.quantityInventory }}</span></td>
Try:
{% if inven.quantityInventory < 10 %}
<td class="color-green-primary">{{inven.quantityInventory}}</span></td>
{% else %}
<td class="color-red-primary">{{inven.quantityInventory}}</span></td>
{% endif %}
how i get user_id of table : user_evento ?
i need compare who user join on table : evento,
enter image description here
controller
public function evento_detalle(Evento $evento){
if(!$evento){
return $this->redirectToRout('ver_eventos');
}
$salas = $this->getDoctrine()->getRepository(Sala::class)->findBy([],['id' => 'desc']);
$users = $this->getDoctrine()->getRepository(User::class) ->findBy([],['id' => 'ASC']);
return $this->render('evento/ver-evento.html.twig',[
'eventos' =>$evento,
'users' =>$users,
'salas' =>$salas
]);
}
twig
{% for user in users %}
{% if user.id == eventos.getUsers.evento %}
<tr>
<td>
{{ user.nombre }}
</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
{%endif%}
{% endfor %}
If you are trying to list Users associated with a particular Evento you should find them all in the collection returned by the Evento::getUsers() method, provided you have followed best practices for Symfony.
{% for user in eventos.getUsers %}
...
{{ user.nombre }}
...
{% endfor %}
This question already has an answer here:
Getting column names in a doctrine2 entity
(1 answer)
Closed 5 years ago.
I was trying to display the field name from a database to be used in the table header to be displayed in the twig for admin section propose!
I have my database like this one
id | Gram | Height | Kilos |
1 | 27.1 | 126 cm | 29 kg |
and I want to get the field name "Gram, Height etc" and make it as table header, I was going to make a translation for this like English to Japanese and so on, "the problem is how do I get the data field name and display it like a text any advice for this on", Thank you in advance!
Code for controller
/**
* #Route("/ingredients/header-translation", name = "z_recipe_header_translation")
* #Template("NutritionMainBundle:Admin\create\recipe\ingredients:translate-headers.html.twig")
*/
public function headerTranslationAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$nutrients = $em->getRepository("NutritionAdminBundle:NutritionValue")->findAll();
return array(
'header' => $nutrients
);
}
Twig code
<table class="table" style="width:100%;">
<thead>
<tr>
<th>header</th>
{% for ii in 1..9 %}
<th>language {{ii}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for i in 1..10 %}
<tr>
<td>header label {{i}}</td>
{% for ii in 1..9 %}
<td><input type="text"/></td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
Oh this is a duplicate question so sorry about that, i'll just make it as an example, The code below will be my final answer, Thank for the help!
controller code:
/**
* #Route("/ingredients/header-translation", name = "z_recipe_header_translation")
* #Template("NutritionMainBundle:Admin\create\recipe\ingredients:translate-headers.html.twig")
*/
public function headerTranslationAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$NutritionValueField = $em->getClassMetadata('NutritionAdminBundle:NutritionValue')->getFieldNames();
$languages = $em->getRepository("NutritionLanguageBundle:Language")->findAll();
$form = $this->createForm(new NutritionValueType());
$form->handleRequest($request);
return array(
'header' => $NutritionValueField,
'languages' => $languages,
'form' => $form->createView()
);
}
For my Twigs display
<table class="table" style="width:100%;">
<thead>
<tr>
<th>header</th>
{% for languages in languages %}
<th>{{languages.langLabel}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for header in header %}
<tr>
{% if header == 'NDB_NO'%}
{#do nothing#}
{% else %}
<td>{{ header|replace({'_':' '}) }}</td>
{% for languages in languages %}
<td><input id="{{header}}_{{ languages.id }}" type="text" value="{{header|replace({'_':' '})}}"/> </td>
{% endfor %}
{% endif %}
</tr>
{% endfor %}
</t
body>
You can use the database information schema:
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA` = 'databasename'
AND `TABLE_NAME` = 'tablename';
use sql sentence:desc tablename;
I have an entity with 3,000 records, and when I render my index.html.twig that information takes about 35 seconds to display the datatable.
My question here is, how can I perform the rendering of the table?
I have looked around but no luck!
Please help me.
Thanks,
Controller
public function indexAction()
{
if ($this->getUser() == NULL){
return $this->redirect($this->generateUrl('login_route'));
}
$em = $this->getDoctrine()->getManager();
$session = $this->get('session');
$id_empresaa = $session->get('idempresa');
$session->set('viewProd', 1);
$entities = $em->getRepository('NivalInventarioBundle:InProducto')->findBy(array(
'idEmpresaa' => $id_empresaa
));
return $this->render('NivalInventarioBundle:InProducto:index.html.twig', array(
'entities' => $entities,
));
}
Twig:
{% extends 'NivalInventarioBundle:Default:index.html.twig' %}
{% block content %}
{% block inventario_menu %}
{{ parent() }}
{% endblock %}
<h3>Productos</h3>
<div class="row" style = margin-bottom:55px;">
<div class="col-md-12">
<table id="ftable" class="table table-condensed table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Código</th>
<th>Nombre</th>
<th>Unidad</th>
<th>Costo</th>
<th>Sub-Linea</th>
<th>Linea</th>
<th>Invent.</th>
<th>Factura</th>
<th>Activo</th>
<th width="60px">Opción</th>
</tr>
</thead>
<tbody>
{% for entity in entities %}
<tr>
<td>{{ entity.idProducto }}</td>
<td>{{ entity.nombre }}</td>
<td>{{ entity.unidadMedida.nombre }}</td>
<td class="text-right">{{ entity.costoPromedio|number_format(4) }}</td>
<td>{{ entity.subLinea.nombre }}</td>
<td>{{ entity.subLinea.linea.nombre }}</td>
<td>
{% if entity.inventariable == 0 %}
No
{% elseif entity.inventariable == 1 %}
Sí
{% endif %}
</td>
<td>
{% if entity.facturable == 0 %}
No
{% elseif entity.facturable == 1 %}
Sí
{% endif %}
</td>
<td>
{% if entity.activo == 0 %}
No
{% elseif entity.activo == 1 %}
Sí
{% endif %}
</td>
<td class = "actions">
<a href="{{ path('inproducto_show', { 'id': entity.idProducto }) }}"
class = "btn btn-sm btn-info glyphicon glyphicon-search" data-toggle="tooltip" title="Ver"></a>
{% if app.user.nivel > 60 %}
<a href="{{ path('inproducto_edit', { 'id': entity.idProducto }) }}"
class = "btn btn-sm btn-primary glyphicon glyphicon-edit" data-toggle="tooltip" title="Editar"></a>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if app.user.nivel > 30 %}
<div class="col-md-12">
<a href="{{ path('inproducto_new') }}"
class = "btn btn-success glyphicon glyphicon-plus" data-toggle="tooltip" title="Nuevo"></a>
</div>
{% endif %}
</div>
{% endblock %}
Javascript:
<script>
$(document).ready(function() {
$('#ftable').DataTable({
stateSave: true,
language: {
"emptyTable": "No hay datos disponibles en la tabla",
"info": "Mostrando _START_ hasta _END_ de _TOTAL_ registros",
"infoEmpty": "Mostrando 0 hasta 0 de 0 registros",
"lengthMenu": "Mostrar _MENU_ registros",
"search": "Buscar:",
"loadingRecords": "Cargando...",
"processing": "Procesando...",
"paginate": {
"first": "Primero",
"last": "Ultimo",
"next": "Siguiente",
"previous": "Anterior"
},
"infoFiltered": "(filtrados de _MAX_ registros)"
}
});
$('.selectpicker').selectpicker({
size: 8
});
$('.datepicker').datepicker({
format: 'dd-mm-yyyy',
autoclose: true
})
} );
</script>
Loading an HTML table with 3000 records is heavy, and doing that with a full framework, ORM and templating engine is even heavier.
The best approach for this situation is to load the records dynamically on the table, querying only for what you're displaying and doing a real pagination. You can do it in two ways:
Option 1
You can follow the DataTables documentation on how to do it and then implement the JS calls, the controller actions to grab the data and the HTML templates. That's not hard if you know your way around Symfony, but it can be a lot of work.
Option 2
Use DatatablesBundle and let it handle everything for you. It's pretty straightforward and they have a good documentation and even an example repository.
Despite of table with 3000 records is heavy (as mentioned before), 35 seconds is extremely much for the table. Reasonable time should be less than 1-2 second because Twig is pretty fast engine.
Found <td>{{ entity.unidadMedida.nombre }}</td> in your template. Probably you haven't defined EAGER fetch in your entity, so it calls SQL query time when it request unidadMedida field.
Open your Symfony profiler page (in dev mode it's usually /_profiler/) and check how many Doctrine queries you have. Of course if there are thousand of database requests loading time will be inadequate.
Here is sample code (working) that I use with Paginator:
$pagination = $paginator->paginate(
$query, /* query NOT result */
$request->query->getInt('page', 1)/*page number*/,
10/*limit per page*/
);
The last parameter 10 sets the number of items per page. I believe this will be a good solution for you (I mean using paginator).
I implemented KnpPaginatorBundle, it works very good, I recomended it: https://github.com/KnpLabs/KnpPaginatorBundle
I have an issue with TinyMce combined with Twig,
I'am trying to paste html with twig tags into tinyMce. (using raw html)
here is what i want as a result :
<table>
<thead>
<tr>
<th></th>
{% for period in report.periods %}
<th>
{% set per = "last_" ~ period %}
{{ per | trans({}, "admin") }}
</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for category in report.categories %}
<tr>
<td>
<b>{{ category | trans({}, "admin") }}</b>
</td>
{% for period in report.periods %}
<td>
{{ data[category][period] }}
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
This is how it looks like when I paste it into tinyMce and validate my HTML
<p>{% for period in report.periods %} {% endfor %} {% for category in report.categories %} {% for period in report.periods %} {% endfor %} {% endfor %}</p>
<table>
<thead>
<tr>
<th></th><th>{% set per = "last_" ~ period %} {{ per | trans({}, "admin") }} </th>
</tr>
</thead>
<tbody>
<tr>
<td><b>{{ category | trans({}, "admin") }}</b></td>
<td>{{ data[category][period] }}</td>
</tr>
</tbody>
</table>
As you can see, tinyMce moves my twig tags outside the table and break all the logic i wanted to do.
I have tried severals configuration for tinyMce ( cleanup : false ) and also severals versions (3.x, 4.x) directly in the official site.
But it does not work either
Thank you for your help.
You can do some workaround:
<thead>
<tr>
<th></th>
<!--{% for period in report.periods %}-->
<th>
{% set per = "last_" ~ period %}
{{ per | trans({}, "admin") }}
</th>
<!--{% endfor %}-->
</tr>
For TinyMce it is not invalid. Twig render it with some extra empty comments around.
<thead>
<tr>
<th></th>
<!---->
<th>
Result value 1
</th>
<!---->
<th>
Result value 2
</th>
<!---->
</tr>
Use protect option of TinyMCE to disable filtering of TWIG codes:
tinymce.init({
protect: [
/{%(.*)%}/g, // Allow TWIG control codes
/{{(.*)}}/g, // Allow TWIG output codes
/{#(.*)#}/g, // Allow TWIG comment codes
]
})
This looks complex to me, as to put something between </td> and <td> will result as invalid HTML.
TinyMCE is a WYSIWYG HTML editor, so it will try to interpret your HTML to render it as it will result; and this is at this step that your original HTML is broken. Just try, in any browser, to render the following code:
<table border=1>
<tr>
<td>test</td>
hello
<td>test</td>
world
<td>test</td>
</tr>
</table>
You will get something like:
Code out of the table scope has been placed above, this behaviour really looks like the HTML you get while validating your TinyMCE field.
As Twig files are just templates and not final documents, there is no logic to import them on a WYSIWYG editor, as invalid html just can't be rendered. I would recommand you to replace TinyMCE by codemirror used in jinja mode to get a proper Twig editor.
I had exactly the same problem, TinyMCE rearranging Twig tags.
I'm using v4.1 and only solution which is working for Twig tags in table is adding HTML comment around Twig tags so your code would be something like this
<thead>
<tr>
<th></th>
<!-- {% for period in report.periods %} -->
<th>
<!-- {% set per = "last_" ~ period %} -->
<!-- {{ per | trans({}, "admin") }} -->
</th>
<!-- {% endfor %} -->
</tr>
I used <!--TWIG: { my twig tags} :TWIG--> then remove comments with regexp on save.
AFAIK there is no config option which would prevent rearranging Twig tags in table outside of cell <td>