Being a beginner with Symfony and Doctrine I have some difficulties to achieve what I would like.
Indeed I have 2 tables in my database : 'Prints' and 'Files'. I have 2 entities and 2 repositories.
These two tables are similar, we find almost the same variables in the entities.
I made the following code. Of course it works but I don't find it very "professional":
//we are in a new controller
/**
* #Route("/Admin/", name="Admin")
*/
public function AdminAction(){
$doctrine=$this->getDoctrine();
$repositoryPrints =$doctrine->getRepository('AppBundle:Prints');
$repositoryFiles =$doctrine->getRepository('AppBundle:Files');
$repositoryUser =$doctrine->getRepository('AppBundle:User');
$showPrints = $repositoryPrints->findAll();
$showFiles = $repositoryFiles->findAll();
$owners = $repositoryUser->findAll();
return $this->render('#App/Admin.html.twig', [
'showPrints'=> $showPrints,
'showFiles'=> $showFiles,
'owners'=> $owners
]);
}
This code makes me do a lot of repetitive code like this in my html/twig files :
//The Admin.html.twig file
{% extends 'base.html.twig' %}
{% block body %}
<table class="tableClass">
<thead>
<tr>
<th class="head">Tilte</th>
<th class="head">Owner</th>
<th class="head">Size</th>
<th class="head">Printing Duration</th>
<th class="head">Due Date</th>
<th class="headStatus">Status</th>
{% set break = false %}
{% for element in showPrints %}
{% if element.done == 1 and break == false %}
<th class="head">
Date of print
</th>
{% set break = true %}
{% endif %}
{% endfor %}
{% for element in showFiles %}
{% if element.done == 1 and break == false %}
<th class="head">
Date of print
</th>
{% set break = true %}
{% endif %}
{% endfor %}
</tr>
</thead>
A quick and easy solution would be to do this:
$showAll = $repositoryPrints->findAll() + $repositoryFiles->findAll();
instead of this :
$showPrints = $repositoryPrints->findAll();
$showFiles = $repositoryFiles->findAll();
In my controller.
Does anyone have any idea how to do this so easily?
Thank you for your attention and your potential answers.
findAll() function will return array. I think you can merge it using array_merge function.
$prints = $repositoryPrints->findAll();
$files = $repositoryFiles->findAll();
$showAll = array_merge($prints, $files);
Related
I am working on a webapplication but ive ran into a hiccup, I have gathered data from my database and displayed the records into a datatable, my problem is that I can not just have one table the client wants me to divide the table into multiple based on what interger is in a column(omloopNummer).
The best ive gotten so far is with the following code it wil split the table up into lets say 4 tables if the interger in the database wil go 1,2,3,4 but it wil only show 1 record in each table while it should be more.
If there is any other simple solution to this instead of using twig I would be happy to try it.
<div id="index" class="table-responsive">
{% set i = 1 %}
{% for duel in duels %}
{% if duel.omloopNummer == i %}
{% set i = i + 1 %}
<table id="" class="table display-" style="width: 90%; margin-top: 30px">
<thead>
<tr>
<th>Omloop</th>
<th>Team 1</th>
<th>vs</th>
<th>Team 2</th>
<th>Acties</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ duel.omloopNummer }}</td>
<td>{{ duel.team1 }}</td>
<td>vs</td>
<td>{{ duel.team2 }}</td>
<td>{{ include('duel/_delete_form.html.twig') }}</td>
</tr>
</tbody>
</table>
{% endif %}
{% endfor %}
You could use PHP to group Duels by omloopNummer in the controller before passing to twig.
$duels = $duelRepository->findAll();
$sorted = [];
foreach($duels as $duel){
$sorted[$duel->getOmloopNummer()][] = $duel;
}
return $this->render('template.html.twig', [
'duel_groups' => $sorted,
]);
Then in twig, loop through the sorted array building a table for each non-empty group and inside each tbody loop through the group.
{% for group in duel_groups %}
...
{% if group is not empty %}
<table>
...
<tbody>
{% for duel in group %}
<tr>...</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
...
{% endfor %}
I am trying to implement a search for user by email function into page admin's dashboard. Currently, I have hardcoded a value into $email variable just to test whether the search works. It does find the right user, but does not display anything in the twig.
Executing {{ dump() }} outputs: array:2 [▼ 0 => User {#4745 ▼ -id: 5 -
username: "test_user" -plainPassword: null -password:
"$2y$13$rGYteIrzifg9Dty.O5knOOCHQnzOtF.nZux8h1jc4sNbap5V7Xn0." -email:
"tester#test.com" } "app" => AppVariable {#2617 ▶} ]
the function I use in AdminController.php:
/**
* #Route("/admin/result", name="user_search")
* Method({"POST"})
*/
public function user_search(Request $request)
{
$email = 'tester#test.com';
$result = $this->getDoctrine()
->getRepository(User::class)
->findOneBy(['email' => $email]);
if ($result) {
return $this->render('admin/result.html.twig', $result);
}else{
return $this->render('admin/result.html.twig', [
'error' => 'No user found with this email '.$email]);
}}
result.html.twig:
{% extends 'base.html.twig' %}
{% block body %}
{% if error %}
<span class="error">{{ error }}</span>
{% endif %}
{% if result %}
<table>
<tr>
<th>Username</th><th>Email</th>
</tr>
{% for item in result %}
<tr>
<td>{{ item.getUsername }}</td><td>{{ item.getEmail }}
</td>
</tr>
{% endfor %}
</table>
{% endif %}
{{ dump() }}
{% endblock %}
In twig you assume that the result is an array. For this, uses findBy instead of findOneBy. findBy returns an array of objects with the desired search. The findOneBy return only an object with the desired search or null if results are not found.
Example:
// look for a single User by email
$result = $this->getDoctrine()
->getRepository(User::class)
->findOneBy(['email' => $email]);
// look for multiple User objects matching the email
$result = $this->getDoctrine()
->getRepository(User::class)
->findBy(['email' => $email]);
This was finally solved by these steps:
There was a typo in the hardcoded $email variable.
Changed return $this->render('admin/result.html.twig', 'result'->$result); instead of return $this->render('admin/result.html.twig', $result);
Changed <td>{{ item.username }}</td><td>{{ item.email }}</td> instead of <td>{{ result.getUsername }}</td><td>{{ result.getEmail }}</td>
Check $user with instance
if ($result instanceof User)
.......................................................................
I suggest you use defined in twig
{% if result is defined %}
{% extends 'base.html.twig' %}
{% block body %}
{% if error is defined %}
<span class="error">{{ error }}</span>
{% else %}
<table>
<tr>
<th>Username</th><th>Email</th>
</tr>
{% for item in result %}
<tr>
<td>{{ result.getUsername }}</td><td>{{ result.getEmail }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
{% endblock %}
So i'd like to get the values from my sql query into my twig.
Easy, but now i have this INNER JOIN query and i just can't get the values...
Here's the code :
public function getList() {
$game= array();
$req = "SELECT * FROM JEU INNER JOIN CATEGORIE ON CATEGORIE.IDCATEGORIE = JEU.IDCATEGORIE";
$stmt = $this->_db->prepare($req);
$stmt->execute();
while ($donnees = $stmt->fetch())
{
$game[] = new Game($donnees);
}
return $game;
}
The index.php
if (isset($_GET["action"]) && $_GET["action"]=="liste")
{ $game= $gameManager->getList();
echo $twig->render('game_list.html.twig',array('game'=>$game));
}
And the view
{% extends "index.html.twig" %}
{% block section %}
<table class="table table-hover table-condensed"><thead>
<tr><th>Name</th><th>Logo</th><th>Cat</th><th>Time</th><th>Players</th></tr>
</thead><tbody>
{% for game in game%}
<tr><td>{{game.name}}</td><td>{{game.logo}}</td><td>{{game.cat}}</td><td>{{game.time}}</td><td>{{game.player}}</td><td>
</tr>
{% endfor %}
</tbody></table>
{% endblock %}
Dump NULL everytime...
Thanks for you help
You're using the game variable twice:
{% for game in game%}
I would name the array 'games', since it can contain >1 game.
So in index.php:
if (isset($_GET["action"]) && $_GET["action"]=="liste")
{
$games= $gameManager->getList();
echo $twig->render('game_list.html.twig',array('games'=>$games));
}
and in the twig:
{% for game in games%}
<tr>
<td>{{game.name}}</td><td>{{game.logo}}</td><td>{{game.cat}}</td><td>{{game.time}}</td><td>{{game.player}}</td>
</tr>
{% endfor %}
[You were also opening more <td> tags than you closed in the twig, so I fixed that too]
I am working on a project using symfony framework. I just want to make a simple search function wherein it can search all the entities that contain with what the user inputted. When I tried to run my code, its not working it keeps on redirecting to my no found result even if their is a related files to be found with.
Here is my controller:
public function searchAction(Request $request){
$request = $this->getRequest();
$data = $request->request->get('search');
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT a,b,c
FROM SampleBundle:transactionDetail a
JOIN a.transaction b
JOIN b.documentRelated c
WHERE a.pNumber LIKE :data
AND b.senderId LIKE :data
AND b.receiverId LIKE :data
AND b.transactDate LIKE :data
AND a.amountPaid LIKE :data')
->setParameter('data',$data);
$res = $query->getResult();
if($res == null){
return $this->render('SampleBundle:Sample:noresult.html.twig');
}
return $this->render('SampleBundle:Sample:search.html.twig', array('res' => $res));
}
and for my search.html.twig
{% extends '::layout.html.twig' %}
{% block pageTitle %} Related Files Found{% endblock %}
{% block body %}
div class="table-responsive margins" >
<table class="table table-condensed table-striped table-bordered table-hover no-margin">
<thead>
<tr style="height: 40px; ">
<th>Transaction Date</th>
<th>Sender ID</th>
<th>Receiver ID</th>
<th>P Number</th>
<th>Amount Paid</th>
</tr>
</thead>
<tbody>
<tr>
{% for res in res %}
{% for other in res.transaction %}
<td >{{res.transaction.transactDate|date('YMd')}} {{res.ediTransaction.transactionDate|date('H:i')}}</td>
<td>{{res.transaction.senderId}}</td>
<td >{{res.transaction.receiverId}}</td>
{% if other.pNumber != null %}
<td style="word-break: break-all">{{other.pNumber}}</td>
{% else %}
<td>N/A</td>
{% endif %}
{% if other.amountPaid != null %}
<td style="word-break: break-all">{{other.amountPaid}}</td>
{% else %}
<td>N/A</td>
{% endif %}
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
{% block javascripts %}
{% javascripts
'bundles/sampledoc/js/jQuery.js'
'bundles/sampledoc/js/bootstrap.js'
%}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
{% endblock %}
my form for searching:
<form action="{{path('sample_search')}}" method="POST">
<div class="form-group input-group">
<input type="text" name="search" class="form-control" placeholder="Search" style="width: 200px; float: right;" >
<span class="input-group-btn"><button class="btn btn-default" type="submit" style="margin-right: 20px;"><i class="fa fa-search"></i></button></span>
</div>
</form>
Can somebody help me with this one? thanks in advance.
Data can't equal all your criteria. If you AND everything in your query data has to match all fields, so you will probably return no results.
Try something like:
WHERE a.pNumber LIKE :data
OR b.senderId LIKE :data
OR b.receiverId LIKE :data
OR b.transactDate LIKE :data
OR a.amountPaid LIKE :data')
->setParameter('data', "%$data%");
And look at the generated SQL with
$query->getSQL()
This way you can actually test your query directly on the DB.
Assuming $data is an associative array holding all the goodies, I do not think you can just hand it to setParameter() the way you are doing. You need to break it down more specifically, for each of those "LIKE" clauses.
Completely untested but I suspect you are looking for something like:
`
WHERE a.pNumber LIKE :pNumber
AND b.senderId LIKE :senderId
AND b.receiverId LIKE :recieveId
AND b.transactDate LIKE :transactDate
AND a.amountPaid LIKE :amountPaid')
->setParameters(array(
'pNumber' => $data['pNumber'],
'receiverId' => $data['receiverId'],
'transactDate' => $data['transactDate'],
'amountPaid' => $data['amountPaid'],
));
`
First of all, sorry by advance for my english which is not perfect.
I have a problem for days by reporting 3 doctrine entity in a Twig Table template.
It's a table for manage stocks at work. I have different materials which have each different sizes. Each couple (1 material + 1 size) got a number as amound to order.
So I first created 3 entity :
Stock (represent materials) ManyToMany Dimension (represent sizes)
Besoin (needs) got a ManyToOne relation with both Stock and Dimension.
Then, I created few Stocks, Dimensions and needs with my forms to get a test database.
The goal is now to create a double entry table with the dimensions list, Stocks list and in each cell the needed number.
It's in this step that I have bugs.
For now I can give you my code and hope someone can help me by giving me a tips.
Controller :
public function commandeAction()
{
$em = $this->getDoctrine()->getManager();
$materiauxlist = $em->getRepository('TGComptaBundle:Stock')->findAll();
$dimensionslist = $em->getRepository('TGComptaBundle:Dimension')->findAll();
$tab1 = array_merge($materiauxlist, $dimensionslist);
$besoins = array();
foreach ($materiauxlist as $stock) {
foreach ($dimensionslist as $dimension) {
$besoin = $em->getRepository('TGComptaBundle:Besoin')->findBesoins($stock, $dimension);
}
}
return $this->render('TGProdBundle:Projet:stocks.html.twig', array(
'materiauxlist' => $materiauxlist,
'dimensionslist' => $dimensionslist,
'besoin' => $besoin));
}
View :
{% block tgprod_body %}
<div class="well">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>#</th>
{% for dimension in dimensionslist %}
<th>{{ dimension.name }}</th>
{% endfor %}
</tr>
</thead>
{% for stock in materiauxlist %}
<tr>
<td>{{ stock.name }}</td>
{% for dimension in dimensionslist %}
{% if besoin %}
<td>{{ besoin.nombre }}</td>
{% else %}
<td>X</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
Repository :
public function findBesoins($stock, $dimension)
{
$qb = $this->createQueryBuilder('b');
$qb
->where('b.stock = :stock')
->andwhere('b.dimension = :dimension')
->setParameter('stock', $stock)
->setParameter('dimension', $dimension);
$qb
->getQuery()
->getResult();
}
My actual problem is : I have X in all cells
Before I asked your help I tried :
foreach ($materiauxlist as $stock) {
foreach ($dimensionslist as $dimension) {
$besoin = $em->getRepository('TGComptaBundle:Besoin')->findBesoins($stock, $dimension);
$besoins[] = $besoin;
}
}
and :
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>#</th>
{% for dimension in dimensionslist %}
<th>{{ dimension.name }}</th>
{% endfor %}
</tr>
</thead>
{% for stock in materiauxlist %}
<tr>
<td>{{ stock.name }}</td>
{% for dimension in dimensionslist %}
{% for besoin in besoins %}
{% if besoin %}
<td>{{ besoin.nombre }}</td>
{% else %}
<td>X</td>
{% endif %}
{% endfor %}
{% endfor %}
</tr>
{% endfor %}
</table>
But it was wrong result (I had like 10000 X on each row)
I thinked it's the "{% for besoin in besoins %}" which is wrong, it should be something like "{% for besoin.dimension.stock in besoins %}" but I can't write this in twig.
and I tried something like this to :
$table = array('stock' => $stock, 'dimension' => $dimension, 'besoin' => $besoin);
$besoins[] = $table;
when I do a { dump() } in Twig I have array with number of stock x number of dimension and all with a null besoin so it seems strange ... and finally I didn't find how to render this array in my table so I let this solution away :/