Symfony - undefined variable twig - php

I made a list of items to render from db and in other examples it works just fine, but sometimes in trwos error
Variable "ticket" does not exist.
and I can't figure out what am I doing wrong..
/**
* #Route("/ticket-list", name="purchased_tickets_list")
* #param Request $request
* #return \Symfony\Component\HttpFoundation\Response
*/
public function ticketListAction(Request $request)
{
$query = $this->getDoctrine()
->getRepository('AppBundle:Tickets')
->findAll();
$build['ticket'] = $query;
return $this->render('#AdminTemplates/pages/purchased-tickets-list.html.twig', $build);
}
and in my twig
{% for p in ticket %}
<tbody>
<tr>
<td>{{ p.id }}</td>
<td>{{ p.buyersName }}</td>
<td>{{ p.ticketType }}</td>
<td>{{ p.playName }}</td>
<td>{{ p.theaterName }}</td>
<td>{{ p.time }}</td>
<td>{{ p.date|date("m/d/Y") }}</td>
<td class="text-primary"><td>{{ p.price|date('H:i:s') }}</td>
<td>{{ p.price }}</td>
</tr>
</tbody>
{% endfor %}

You never pass ticket -
see below example of sending var:
Controller file:
return $this->render('category/list.html.twig', ['categories' => $categories]);
twig:
{% for value in categories %}
{# rest of code #}
{% endfor %}
update based on comments:
try this:
Controller
$builds = array('foo' => 'one', 'bar' => 'two');
return $this->render('category/list.html.twig', array('ticket' => $builds));
twig file:
{{ dump(ticket) }}
dump is a var_dump in a really pretty human-readable format. If nothing comes through maybe you're in production mode, in that case try running (after changes) in terminal:
php bin/console cache:clear

Related

Symfony - creation of a "table" form

I am under symfony 5, on an application already in production on which I would like to add a screen allowing to modify several lines of the same table at once, in the same "POST" message, with one and the same "send" button.
The different fields must be contained inside a single form tag:
<form name="modif_todo_liste" method="post">
...
</form>
I tried different things including creating a table with different views based on the same template form:
foreach($todos as $v){
$form_tab[]=$this->createForm(ModifTodoListeType::class,$v)->createView();
}
that I render in twig:
{% for form in form_tab %}
{{ form_start(form) }}
<tr>
<td>{{ form_row(form.Denomination) }}</td>
<td>{{ form_row(form.Nbr) }}</td>
<td>{{ form_row(form.CIS) }}</td>
<td>{{ form_row(form.Label) }}</td>
<td>{{ form_row(form.BN_Label) }}</td>
<td>{{ form_row(form.ATC7) }}</td>
<td>{{ form_row(form.Categorie) }}</td>
</tr>
{{ form_end(form) }}
{% endfor %}
visually this corresponds to what I would like, but impossible to validate everything at once because, it is all the lines are not included in the same form:
Does anyone know of an easy way to make this form that will be "flushable" in the controller afterwards?
Otherwise I will do a more classic solution, I pass an array containing my entire table to twig, in the view I build a form by looping over the array. And in the controller I will take care of the update.
Thanks for your help
You can create the whole form containing different fields using Symfony forms.
You can even map the attributes to the entity directly, so the update is taken care of on the handleRequest method called on the form. (the entity is updated, you still need to save it to the database)
Symfony forms docs
If the fields are dependent on some array in the controller, you can also build the form in the controller like here.
Try this instead:
{{ form_start(form) }}
{% for form in form_tab %}
<tr>
<td>{{ form_row(form.Denomination) }}</td>
<td>{{ form_row(form.Nbr) }}</td>
<td>{{ form_row(form.CIS) }}</td>
<td>{{ form_row(form.Label) }}</td>
<td>{{ form_row(form.BN_Label) }}</td>
<td>{{ form_row(form.ATC7) }}</td>
<td>{{ form_row(form.Categorie) }}</td>
</tr>
{% endfor %}
{{ form_end(form) }}

Mailjet Vars blank array throws error

$array = [
"low_price_low_stock_goods" => []
]
In my mailjet template
{% for item in var:low_price_low_stock_goods %}
<tr>
<td>{{ item.good_name }}</td>
<td>{{ item.value }}</td>
<td>{{ item.count }}</td>
</tr>
{% endfor %}
error is now No value for "var:low_price_low_stock_goods"
As I answered you on Github Ricky: it's a known issue on Mailjet's templating language side, sorry for that. To avoid it, just pass a valid object in the API call for the low_price_low_stock_goods value. This will work:
{
item.good_name: "",
item.value: "",
item.count: ""
}

How to count objects in array?

So I've been working with symfony for a while and I'm trying to understand how it works. So, I tried to count how many tasks do I have in my tasks array.
This is my homeController.php class:
public function succesfulLogin(Request $request)
{
$repository = $this->getDoctrine()->getRepository('AppBundle:Task');
$tasks = $repository->findByAuthor($this->getUser()->getUsername());
$points = 0;
foreach($tasks as $task){
$points++;
}
return $this->render(
'userpage.html.twig',array('username' => $username = $this->getUser()->getUsername(), 'tasks' => $tasks, 'points' => $points ));
$user->getTasks();
//as I understant I return '$tasks' array to twig with all my tasks
//so before returning '$tasks' array it should have 21 object in it?(not 13)
//am I wrong?
}
So I pass 'points' to twig and twig prints out number 13, but when I try to print out all tasks in twig, it says that I have 21 task.
There is some twig code:
{% for task in tasks %}//this foreach loop prints out 21 task
<tr>
<td id>{{ task.Id }}</td>
<td>{{ task.Status }}</td>
<td>{{ task.Name }}</td>
<td>{{ task.Description }}</td>
<td>{{ task.Category }}</td>
<td>{{ task.Author }}</td>
<td>{{ task.CreationDate|date("m/d/Y") }}</td>
<td><a id="myLink" href="/edit/{{ task.ID }}" > Edit </a></td>
<td><a id="myLink" href="/delete/{{ task.ID }}" >Delete</a></td>
<?php echo 2+2; ?> </tr>
{% endfor %}
Generally, you should use count() or sizeof() function in PHP for getting count of the objects. So you could just run $points = count($tasks) instead of iterations over $tasks and incrementing.
If you'd like to get array count in twig template, you could use built-in length filter.
{% set tasks_count = tasks|length %}

Symfony2 DATEDIFF function

I need to fill table in TWIG with data from database. Everything is Fine with the exception of this:
I need to have column with DATEDIFF property to get number of days.
TODAY-dateFromDateBase
Question is:
How to get number of days in loop in twig?
here is my twig:
<table>
<thead>
<tr>
<form action="" method="post" {{ form_enctype(searchform) }} class="form-index-permits">
<td>L.p </td>
<td>ID PRZEPUSTKI {{ form_widget(searchform.PermitId) }}</td>
<td>Name{{ form_widget(searchform.Permitname) }}</td>
<td>Surname {{ form_widget(searchform.Permitsurname) }}</td>
<td>Company {{ form_widget(searchform.Company) }}</td>
<td>GW {{ form_widget(searchform.Contractor) }}</td>
<td>Dayleft {{ form_widget(searchform.Dayleft) }}</td>
<td>End date {{ form_widget(searchform.date, { 'attr': {'class': 'datepicker'} }) }}</td>
</form>
</tr>
</thead>
{% for permit in permitcollection %}
<tbody>
<td>{{ loop.index }}</td>
<td>{{ permit.getPermitid()|number_format(0, '.', ' ') }}</td>
<td>{{ permit.getPermitname() }}</td>
<td>{{ permit.getPermitsurname() }}</td>
<td>{{ permit.getPermitsCompany().getName() }}</td>
<td>{{ permit.getPermitsContractor().getName() }}</td>
<td> HERE I WANT TO DISPLAY DAYS LEFT</td>
<td>{{ permit.getExpirationdate()|date('Y-m-d') }}</td>
</tbody>
{% endfor %}
</table>
Is something like this possible?
{{ permit.getExpirationdate()|date('Y-m-d') - "now"|date('Y-m-d') }}
First Solution (recommended) "Use an existing library":
You can use the KnpTimeBundle
In the Twig:
This compare with the current date:
{# Returns something like "3 minutes ago" #}
{{ time_diff(permit.expirationDate) }}
This compare with the another date:
{# Returns something like "3 minutes ago" #}
{{ time_diff(permit.expirationDate, anotherDate) }}
Second Solution "Do it yourself":
Make diff via php function:
$calcFrom = permit.getExpirationdate()
$now = new \DateTime('now');
$now->diff($calcFrom)->format("%a")
And make it available via a Twig extension or directly in an helper method in the entity.
Another possible solution is to write register a custom DQL Function to do the work in the repository
Hope this help

Case statements when updating a table based on clicked button?

I've got a table like below:
<tr>
<td>{{ item.wo_num_and_date }}</td>
<td>{{ item.comp_name_and_number }}</td>
<td>{{ item.finish_sizes }}</td>
<td>{{ item.material }}</td>
<td>{{ item.total_num_pieces }}</td>
<td>{{ item.workorder_num_one }}</td>
<td>{{ item.notes_one }}</td>
<td id='signoff_userone'><input type='button' id='signoff_user_one' data-rowid={{ item.id }} value='Signoff' /> {% if item.signoff_user_one is defined and item.signoff_date_one is defined %}{{ item.signoff_user_one.name|title }} {{ item.signoff_date_one }} {% endif %}</td>
<td>{{ item.workorder_num_two }}</td>
<td>{{ item.notes_two }}</td>
<td id='signoff_usertwo'><input type='button' id='signoff_user_two' data-rowid={{ item.id }} value='Signoff' /> {% if item.signoff_user_two is defined and item.signoff_date_two is defined %}{{ item.signoff_user_two.name|title }} {{ item.signoff_date_two }} {% endif %}</td>
<td>{{ item.workorder_num_three }}</td>
<td>{{ item.notes_three }}</td>
<td><input type='button' id='signoff_user_three' value='Signoff' /> {{ item.signoff_user_three.firstname }} {{ item.signoff_user_three.lastname }}</td>
</tr>
Fiddle: http://jsfiddle.net/qwUV4/1/
Here's my php code I call when a button is clicked, everything works well for the first "Sign Off" box but the other 2 don't work, obviously because of my Update statement below which is only set to update column "signoff_user_one".
<?php
require_once('../includes/config.php');
$user_id = getuserinfo($loggedin_id);
$row_id = (int)mysqli_escape_string($dbc3, $_POST['rowid']);
$sql = "UPDATE checklist_component_stock SET signoff_user_one = $loggedin_id, signoff_date_one = NOW() WHERE id = " . $row_id;
mysqli_query($dbc3, $sql);
$ret = array('rowid' => $row_id, 'user' => $user_id, 'date' => date('Y-m-d H:i:s')); //date('M d, Y')
echo json_encode($ret);
?>
My question is, would I need cases so the script checks whether its signoff_user_one, user_two, or user_three and executes the correct update statement? How would I do something like that? Is there another solution?
Are you using a loop? Because in such a case, it would probably not work very well.It should work well with the buttons and the specific ids which you have captured.You could use an isset function and use the name attribute for the button..

Categories