php combine variables into array for twig - php

so I have some php variables, some are form an array. I can print them like this
echo $arr->title;
echo $arr->date;
echo $xml;
echo $cover;
I am using twig. I think I need to combine specific php variables into one array(say book) so I can render my twig template with
echo $template->render(['book' => $book]);
then in my twig template be able to use
{{ title }}
{{ date }}
{{ xml }}
{{ cover }}
any tips on how to achieve this would be greatly appreciated .

Just create the array for your needs:
$viewData = [
'book' => [
'title' => $arr->title,
'date' => $arr->date,
'xml' => $xml,
'cover' => $cover,
]
];
echo $template->render($viewData);
Template
{{ book.title }}
{{ book.date }}
{{ book.xml }}
{{ book.cover }}

If you want to be able to use the data in your twig template like this:
{{ title }}
{{ date }}
{{ xml }}
{{ cover }}
then you need to pass on the data to the view like that:
echo $template->render([
'title' => $arr->title,
'date' => $arr->date,
'xml' => $xml,
'cover' => $cover,
]);

Related

Retrieve old value from Laravel Form::select

I have the following form field in a Laravel project in my create view (create.blade.php):
{{ Form::label('format', 'Type', ['class'=>'label']) }}
{{ Form::select('format', array('is_html' => "HTML", 'is_video' => 'Video'), null, ['class' => 'form-control format']) }}
I retrieve this inside the format column in my database so i can use this data in my project.
Now, inside the edit (edit.blade.php) view I want to have the already selected data to reflect. So when the user has selected "video", the select option will already be set to Video.
While I was typing this question, i figured it out. Already typed the entire question so might as well post it to help someone out.
The third argument needs to correspond with the data I retrieve from the database. So, for example, if i wanted the Video to be selected, it would look like this:
{{ Form::label('format', 'Type', ['class'=>'label']) }}
{{ Form::select('format', array('is_html' => "HTML", 'is_video' => 'Video'), 'is_video', ['class' => 'form-control format']) }}
I replaced the is_video with the variable that contains the data from my database and it's working as expected.
{{ Form::label('format', 'Type', ['class'=>'label']) }}
{{ Form::select('format', array('is_html' => "HTML", 'is_video' => 'Video'), $var->format, ['class' => 'form-control format']) }}

Using subsections of an array in Twig as if they were the main

If I have an array passed to twig like this
$values = [
'title'=>'Title of Page',
'subsection_a'=>[
'title'=>'Title of Subsection'
],
];
What I'd want to do is for a specific section in my template, use 'subsection_a' as the base so when I do {{ title }} it says "Title of Subsection" rather than "Title of Page"
I'm very unfamiliar with Twig, and I'm testing it as a replacement for a template engine I threw together for a project.
If your dividing the main proportion of your templates in subtemplate you can do it with the keyword with:
controller.php
echo $twig->render('main.twig, [
'title' => 'parent',
'foo' => 'bar',
'bar' => 'foo',
'child' => [
'title' => 'Child',
'foo' => 'Foobar',
]
]);
main.twig
<h1>{{ title }}</h1>
<p>{{ foo }}</p>
{% include "child.twig" with child %}
child.twig
<h2>{{ title }}</h2>
<p>{{ foo }}</p>
twigfiddle
There is no Twig-way of achieving this.
If it's just for ease of use, you could set a short variable, such as
{% set sub = subsection_a %}
This would allow you to write {{ sub.title }}.
You could create a new array with twig, merge the specific subsection, but in your case, it would make managing the code more difficult, you could have duplicate and it might not be worth the trouble.

laravel - null value in foreach

i would like to know how to solve this problem. Im making a query with a "whereIn" clause (In this case, its named "Price") in which there is a "<=" operator. But im getting an error which indicates that one variable is null. Im using laravel 5.4.
code used so far:
controller:
function catalog(Request $abc) {
$categoryesc = $abc->categoryesc;
$manufaesc = $abc->manufaesc;
$priceesc = $abc->priceesc;
$modelesc = $abc->modelesc;
if (empty($modelesc)) {
$robots = DB::table('robots')->whereIn('Category_id', [$categoryesc])->whereIn('Manufacturer_id', [$manufaesc])->whereIn('Price', '<=', $priceesc)->get();
}elseif (Auth::check()){
$robots = DB::table('robots')->where('Model', $modelesc)->first();
$colours = DB::table('colours')->pluck('Colour', 'id');
}
else {
return redirect('login');
}
return view('catalog', compact('robots', 'categories', 'colours'));
}
blade file:
#if (empty($_GET['modelesc']))
<h1>Catalog</h1>
{{ Form::open(array('method' => 'GET')) }}
{{ Form::select('categoryesc', ['3,2,1' => 'Any Category', '1' => 'Light', '2' => 'Medium', '3' => 'Heavy'], '3,2,1') }}
{{ Form::select('manufaesc', ['2,1' => 'Any Make', '1' => 'Xenon', '2' => 'Tauron'], '2,1') }}
{{ Form::select('priceesc', ['1000000' => 'Any Price', '100' => '100', '200' => '200'], '1000000') }}
{{ Form::submit('Search') }}
{{ Form::close() }}
<div>Available models</div>
<b>On this page ({{ $robots->count() }} robots)</b>
<div id="area1">
#foreach($robots as $robot)
{{ Form::open(array('method' => 'GET')) }}
{{ Form::hidden('modelesc', $robot->Model) }}
{{ Form::submit($robot->Model) }}
{{ Form::close() }}
#endforeach
</div>
#else
<h1>Orders</h1>
<button> < </button>
{{ Form::open(['method' => 'POST']) }}
{{ Form::hidden('users_id', Auth::user()->id) }}
Model: {{ Form::text('Model', $robots->Model) }}<br><br>
{{ Form::hidden('Category_id', $robots->Category_id) }}
{{ Form::hidden('Fabrication_date', date('Y-m-d')) }}
Choose colour: {{ Form::select('Colour_id', $colours) }}<br><br>
{{ Form::hidden('Order_status_id', '1') }}
{{ Form::submit('Order') }}
{{ Form::close() }}
#endif
In the builder.php i previously added the "<=" operator to the function "invalidOperatorAndValue" at page 615 (in order for it to work). This is the error message:
ErrorException in Builder.php line 766:
Invalid argument supplied for foreach()
in Builder.php line 766
at HandleExceptions->handleError(2, 'Invalid argument supplied for
foreach()',
'C:\\Users\\Joao_Carvalho\\Laravel\\MegaRobot\\
vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php',
766, array('column' => 'Price', 'values' => '<=', 'boolean' => null, 'not'
=> false, 'type' => 'In')) in Builder.php line 766
at Builder->whereIn('Price', '<=', null) in CentralController.php line 26
Your whereIn for the condition on Price should be a where instead. whereIn is not the appropriate method for when you want to do a comparison with <=:
DB::table('robots')
->whereIn('Category_id', [$categoryesc])
->whereIn('Manufacturer_id', [$manufaesc])
->where('Price', '<=', $priceesc)
->get();
whereIn on the other hand should be used for testing whether a value is in an array, which is what you do in the two other cases.
WhereIn expects array as a second parameter as it is structured to check if field value is within the array.
whereIn('Price', '<=', $priceesc) will not work as second parameter is string and internally its expecting array and doing foreach on it.
You need to replace it with :
where('Price', '<=', $priceesc)
First, there is the whereIn issue addressed by the other answers.
However, in addition to that, the actual issue you're running into is that $robots is being set to two different things depending on the result of your if statements.
Inside if (empty($modelesc)), $robots is being set to a Collection of stdClass objects. When you foreach this result, you will loop through the Collection.
However, inside the elseif (Auth::check()), $robots is being set to an individual stdClass instance (you have used the first() method). When you foreach this result, you'll be looping through the properties on that one instance, which is not what you intended. One of the properties on this instance is null, which is what you are seeing.
A quick solution would be to wrap this result in a new collection:
$robots = collect([DB::table('robots')->where('Model', $modelesc)->first()]);

How to create a volt URL with parameters

I want to create a URL using volt (Phalcon).
I have tried:
{{ url("order/view/", ["id" :order.id]) }}
However that produces a URL like:
http://localhost/gateway-new/order/view/?id=7
Whereas I would like the url to look like:
http://localhost/gateway-new/order/view/id/7
Any idea how to do this correctly?
if you have a route defined like
$router->add('order/view/id/:int', array(
'controller' => 'order',
'action' => 'view',
'id' => 1))->setName('order-view');
you could use
{{ url(['for': 'order-view', 'id': order.id]) }}
{{ url("order/view/id/" ~ order.id) }}

Symfony2 TimeType Field separate hour's and minute's input fields

I want to get two input fields for hours and minutes with the TimeType field.
I also want to set for the input field of time and hour an unique label, placeholder and / or input values. I also want to render each inpult field individually in TWIG, like
{{ form_row(form.TimeExtern[####HOUR FIELD####]) }}
{{ form_row(form.TimeExtern[####MINUTES FIELD####]) }}
My current code:
$builder->add('TimeExtern', 'time', array(
'input' => 'timestamp',
'widget' => 'single_text',
'required' => true,
'label' => 'Externe Zeit',
'attr' => array(
'help_text' => 'Zeitformat: Stunden:Minuten',
'input_group' => array(
'append' => '.icon-time',
)
),
));
This gives me ONE input field for hour and minutes together.
I've already read the docs but couldn't find a solution.
Any ideas?
The form_div_layout.html.twig renders the time widget using
{{ form_widget(form.hour, vars) }}
{% if with_minutes %}:{{ form_widget(form.minute, vars) }}{% endif %}
{% if with_seconds %}:{{ form_widget(form.second, vars) }}{% endif %}
So as far as I can see you would be able to use
{{ form_widget(form.TimeExtern.hour) }}
{{ form_widget(form.TimeExtern.minute)) }}
And then just add your details (label, placeholder, etc) in the attributes hash like
{{ form_widget(form.TimeExtern.hour, {'label': '', 'attr': {'placeholder': '' }}) }}
{{ form_widget(form.TimeExtern.minute, {'label': '', 'attr': {'placeholder': '' }}) }}

Categories