Correct approach for rendering optional param in blade - laravel-5

I noticed that below construction is not correct for Blade
<div class="constant #if($some_condition)optional#endif">
cause this is converted to in PHP which is invalide
<div class="constant <?php if($some_condition): ?>optional<?php endif; ?>">
To make this statement work I need to put close tag on different line but it looks very bad, especially if there are many others attribute.
<div class="constant #if($some_condition)optional
#endif" data-id="1" tabindex="2" data-etc="...">
What is the right way of rendering such kind of conditions in Blade?

Try the short version of if statement.
$some_condition ? 'optional' : ''
Using the code above, if the condition is true it will return the the string 'optional', if the condition is not true it will return an empty string I mean this ''. Note, an empty string as attribute do nothing inside Html element.
In your case it should look like this:
<div class="constant {{ $some_condition ? 'optional' : '' }}">

Related

Passing conditional disabled attribute to blade component with ternary operator

Is there a way to conditionally pass a disabled attribute to a blade component? For example this question and answer mention how to use the ternary operator to pass in the value of the attribute but the attribute name will be there regardless.
I am specifically trying to use the ternary operator in the blade component tag to add (or not add) the disabled attribute
template code:
<x-button {{!$aircraftType->canIslandBuild($island) ? 'disabled' : ''}}>
Build
</x-button>
button component code:
<button {{ $attributes->merge(['class' => 'inline-flex']) }}>
{{ $slot }}
</button>
The error involves adding {{!$aircraftType->canIslandBuild($island) ? 'disabled' : ''}} to the x-button tag.
The error that I'm getting is: syntax error, unexpected token "endif", expecting end of file
Also if I change this {{!$aircraftType->canIslandBuild($island) ? 'disabled' : ''}} to {{''}} the same error happens so I'm curious if you can render strings from php code inside of the component tag header like you can anywhere else in a blade template. I know there are other ways to pass in data and conditionally add the disabled attribute by modifying the button component code but I would like to know if there is an easy solution here.
Went with matiaslauriti's comment and decided to replace
{{!$aircraftType->canIslandBuild($island) ? 'disabled' : ''}}
with
:disabled="!$aircraftType->canIslandBuild($island)"
without changing anything else. It seems disabled="disabled" is included in the $attributes variable only when the value is true. This means that the button renders a disabled="disabled" only when !$aircraftType->canIslandBuild($island) is true and when it is false, no disabled is rendered on the final html for the button.

Cannot inject request paraemter into blade view file

I have the following URL:
https://example.com/?email=test#test.com
then I have the following blade template
<input value="{{Request::query('email') or old('email')}}">
But it's not displaying the email I passed in the get parameter into the input. Instead, it's displaying the value 1
Tried searching haven't found a solution that works.
That's because you have {{Request::query('email') or old('email')}} which is conditional. It will always return true or false.
Try any of these:
{{Request::query('email') || old('email')}}
or
{{Request::query('email') ? Request::query('email') : old('email')}}
You can try this:
<input value="{{ request()->email }}">

Add class with old data in a form

I try to add class on a label if an the input has old datas.
I try this on my label:
<?php empty(old(email)) ? '' : 'active' ;?>
But it doesn't work. I also try with "isset" but I have an error exception.
Can you help me ? Thank you
The old method takes the input name as a string. You can also use blade syntax to make things easier.
<label class="label{{ old('email') ? ' active' : '' }}" >Test</label>
The old function accepts string as its first parameter. You're likely getting the error because constant email does not exists. Instead, call it with string old('email')
<?php empty(old('email')) ? '' : 'active' ;?>

How to style successful input fields in Thymeleaf

I would like to use Bootstrap's has-success and has-failure classes with Thymeleaf.
So far I have
<div th:class="${#fields.hasErrors('field')}? 'form-group has-error' : 'form-group'"></div>
This displays the failure style correctly, when the form is posted and the field is invalid.
However if I change the second part of the ternary to 'form-group has-success', then on the initial form GET request, then, of course, it styles it as a success, even though the form hasn't been posted yet.
My question: is there a way in Thymeleaf to handle the following
Displays a form without any styling on GET.
On POST apply has-error or has-success classes.
I think you'll need to add attributes to your Model in the back-end for this.
In you GET request, change nothing. In your POST request, add an attribute: ["hasErrors", true] if the form data you send via the post is incorrect, false otherwise.
Now in your html you can add the following:
<th:block th:if="${hasErrors != null}">
<div th:class="${hasErrors ? 'form-group has-error' : 'form-group has success'"></div>
</th:block>
<th:block th:unless="${hasErrors != null}">
<div class="form-group"></div>
</th:block>
You check if the hasErrors model attribute isn't null, if it is, it means you're in the GET method and you should display a simple form-group. If the hasErrors is not null, you can create the ternary expression based on the boolean value hasErrors. The th:block is non-html. You can replace it with a div, but then you neen an extra div just to check a boolean.
I'm not going into GET/POST problem but I think that this can help you:
New th:errorclass for adding CSS class to form fields in error
Until now, whenever we wanted to apply a specific CSS class to an input field in a form when there were errors for that field, we needed to use the th:class or th:classappend attributes.
In Thymeleaf 2.1, in order to simplify this structure, a new th:errorclass attribute processor has been introduced. This processor will read the name of the field from the name or th:field attribute in the same tag, and apply the specified class if such field has errors.
Note the 'error' literal is in fact a token, so no single quotes are really needed.
The result is much more concise. Note also that th:errorclass works like th:classappend, not th:class. So the specified class will in fact be appended to any existing ones.
http://www.thymeleaf.org/whatsnew21.html#errcl
I found that Thymeleaf as a hasAnyErrors function.
<div class="form-group row"
th:attrappend="class=${#fields.hasAnyErrors()
? #fields.hasErrors('field') ? ' has-error' : ' has-success'
: '' }">
This now works.
When the user GETs the form, hasAnyErrors is false, so the empty string is appended and the input and label receive the default style.
When the user POSTs the form, if there are any errors then the first part of the ternary is evaluated. This adds the has-error or has-success styles.
This was inspired by Roel Strolenberg's answer below.

MVC Question: How do I know when I'm putting too much logic into my view?

Consider the following from CodeIgniter. If I am doing this wrong, then please tell me:
<html>
<head>
<title><?=$title ?></title>
</head>
<body>
<h1><?=$heading; ?></h1>
<?php foreach ($query->result() as $row):?>
<p>
<?=$row->LastName . ', ' . $row->FirstName . ' ' . $row->MiddleName?>
</br>
<?=$row->myField?>
<?php if ($row->myField == ''):?>
no data found
<?php endif;?>
some text
<?=$row->anotherField ?>
</br>
<?php if ($row->purchasedate !='') {echo 'Purchase Date ' . mdate('%m' . '/' . '%d' . '/' . '%Y', strtotime($row-> purchasedate));}?>
</p>
<p>
<label for="ProductNumber">Product</label>
<input type="text" name="Product_number" id="ProductNumber" value =
<?=$row->ProductNumber?>
/>
</br>
<?php if ($row->Purchased == '-1'): ?>
<h3>Bought</h3>
<?php endif;?></br>
<?php if ($row->Sold == '-1'): ?>
<h3>Sold</h3>
<?php endif;?></br>
</p>
<?php endforeach;?>
</body>
</html>
I know some of it will not make sense. I am experimenting and also changed some of the names of fields.
My question is: Is this too much intermixing of code into my view? It seems this occurs with most templating but that there is some vague line that just feels wrong when you cross it and you say, "That's too much logic in my view." I don't know that line. Is this example crossing it? A foreach, if thens, echo, strtotime, the ?php tags, etc.
Is it just crossing the "line" when I put db access logic and start emitting all my html tags from print or response.write statements all on one big page behind the scenes on the server?
There's better checks you can do instead of shoving that logic in the view. For example you're doing things like if($row->Purchased == '-1') when in fact it would be better to have if($row->isPurchase), that way determining the validity and control flow is placed further onto the state of your model. If you followed this logic throughout your code example you'll see it actually turns into something much simpler.
MVC Question: How do I know when I’m putting too much logic into my view?
IMHO
If your logic is doing anything other than making presentational decisions.
In the example all your if statements are doing something graphical.
So I think there is nothing wrong with that code.
Using all those php tags can make a view look like a mess. But thats just php.
Thats why I use smarty, it makes it a bit more readable.
Yeah I know php is a template language but its just my opinion.

Resources