Laravel blade "old input or default variable"? - php

I want to show the old input in input value. If there isn't old input, than show other variable:
value="{{ old('salary_' . $employee->id) or 'Default' }}"
But when there is no old input, it gives me 1 instead of the default value!
I think the problem has something to do with the concatenation, but I don't know how to fix it!?

or is a comparison operator in PHP, so your code is evaluating to true, or 1. What you want is a ternary if statement.
As mentioned, or can be used in blade as shorthand for a ternary if statement.
But you can (and should) just pass the default value as the second argument to the function, like so:
value="{{ old('salary_' . $employee->id, 'Default') }}"

You can use the code (for PHP 7):
{{ old('field_name') ?? $model->field_name ?? 'default' }}
For checkbox checked attribute use the code (if default value is false):
{{ (old() ? old('field_name', false) : $model->field_name ?? false) ? 'checked' : '' }}
Construction {{ $something or 'default'}} works only for variables

You can use:
old($key, $defaultValue)
See more:
https://github.com/laravel/framework/blob/87df108bb487714d205002aba7e7317533976a8d/src/Illuminate/Foundation/helpers.php#L541-L553

As described in the Laravel doc: "If you are displaying old input within a Blade template, it is more convenient to use the old helper:".
So if you need add/edit data form (when you need to use edit form for add and edit in edit mode you need to use loaded data from model (database)) to show values from the model (through controller) you can use following:
name="some_value" value="{{ $some_value or old('some_value', $the_value) }}"
where is "some_value_from_model" variable name in view array.
In this case it should be at first $some_value will be used to set in the "value" and, if no, it will try to use old (value from request from name "some_value") and if not old then '' should be used.
Thanks WoodyDRN for comment.

Try this:
value="{{ old('salary_' . $employee->id) ?? 'Default' }}"
Explanation:
If an old value is there, it will be set, otherwise, 'Default' will be set as value.

Try this:
<textarea name="alamat" id="" class="form-control" placeholder="Alamat">{{ old('alamat').#$biodata->alamat }}</textarea>

Related

Show variable on blade template

I tried to show a variable this way on a blade template on laravel
<input type="text" name="win-phone" class="modal-input" value="{{ $info['fields']['phone'] }}">
and it doesn't work , but this way
<input type="text" name="win-phone" class="modal-input" value="{!! $info['fields']['phone'] !!}">
It worked, why? the first way its no the correct wat?
By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:
Hello, {!! $name !!}.
In summary, if used in this way disabled HTML is allowed.
Source : https://laravel.com/docs/7.x/blade
There are two way to print your php variable in blade template.
1. Statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attack
{{ $your_variable }}
2. If you do not want your data to be escaped, you may use the following syntax
{!! $your_variable !!}

Why is my variable displaying incorrect value in Laravel 5.4 Blade file?

I have a variable $country_code that is displaying the correct value in one part of my form but not in a different part. Why is this happening?
This is my code:
{{ Form::open(['action' => ['PinVerificationController#valid'],'id'=>'pin_code_form']) }}
//$country_code shows 1
We sent a text message to {{$country_code}} {{$phone_number}}. You should receive it within a few seconds.<br><br>
{{ Form::label('Pin Code', null, ['class' => 'control-label']) }}
{{ Form::hidden('country_code', $country_code) }}//<------shows 1-US instead of 1
{{ Form::hidden('phone_number', $phone_number) }}
{{ Form::hidden('type', $pin_notification_type) }}
{{ Form::text('pin_code', null,['placeholder' => 'Pin Code'])}}<br><br>
Enter a 4 digit pin you received by phone.
<br>
<br>
{{ Form::submit('Verify',['name'=>'validate'])}}
{{ Form::close() }}
So if I set $country_code to "1" in my controller it'll display We sent a text message to 1 5555555. You should receive it within a few seconds.
But if I do an inspect element on my hidden form it displays 1-US. I've tried php artisan view:clear and php artisan clear-compiled but the problem still persists.
I've also tried hardcoding a value {{ Form::hidden('country_code', 'asdf') }} and i'm not seeing the change. I tried adding a test {{ Form::hidden('country_code1', 'asdf') }} and see the update.
I also renamed country_code to country_code111 for my hidden field and it displayed the correct value of 1. I thought it was a caching issue but like I mentioned I've tried php artisan cache:clear and the problem is still there.
Since you are using Laravel 5.4, I assume you are using Form from the LaravelCollective, since they were removed from baseline Laravel in 5.x.
LaravelCollective Forms will override the value you provide to the input if it exists in the request data, or in old posted data (the old() function). I suspect this is the case for you.
You can see this behavior implementation here.
To solve this problem, you have a few options:
change the name of the request parameter feeding into the page (if you have control over it)
rename your field name to something that doesn't conflict
Don't use Form:: to generate the form and just use classic html/Blade to create the hidden input automatically
Personally, I would recommend #3 because then you have full control over your code.
<input type="hidden" name="country_code" value="{{ $country_code }}"/>

Laravel checkbox state after failed validation

There are many many questions here on SO about how to properly persist checkbox fields in Laravel after form submission (
example,
example,
example
), this question is not about that.
Please note I am also well aware of Laravel's old() method, and that it accepts a default value. My question is about a particular case where old() does not seem to work for a checkbox.
I'm working on an edit form, updating data already in the DB. The form will initially be populated with the values from the DB.
The standard approach to re-populating form inputs after failed validation is to use old(). For most input types, something like the following works:
<input type='text' name='unicorns' value='{{ old('unicorns', $model->unicorns) }}'>
On initial page load (before the form is submitted) this works fine. As nothing has been submitted yet, old('unicorns') is null, so the default of $model->unicorns will be used, and the text field's value reflects the current DB state.
After submitting a new value, which fails validation, old('unicorns') will be the new value, even if the new value was an empty string, and again the text field's value reflects the submitted state, as we want.
However this breaks down for checkboxes, when the unchecked checkbox does not appear in the request at all. Consider:
<input type='checkbox' name='unicorns' value='1' #if old('unicorns', $model->unicorns) checked #endif>
On initial page load this works fine, just like for text fields. But after failed validation, for the 2 cases where the checkbox is changed from its initial state:
Case 1: DB state 0 (unchecked), submitted state checked. old('unicorns') will be 1, so the test evaluates true, the checkbox is checked - OK!
Case 2: DB state 1 (checked), submitted state unchecked. Since old('unicorns') is null, old() falls back to the default value $model->unicorns (1), so the test evaluates true, and the checkbox is checked - but we just unchecked it! FAIL!
(There is no problem in the other 2 cases, where the checkbox is not changed from the state in the DB).
How to solve this?
I initially thought the best way around this would be to test if there has been a validation error - if so, use the old() value, with no default fallback; if not, use old() with default fallback. One way to test for failed validation is to check $errors. This seems to work, but it only works within a view AFAICT, as (from the Laravel docs):
Note: The $errors variable is bound to the view ...
I'd like to create a global helper for this, and $errors won't work there. Anyway, this approach feels ... clunky and too complicated.
Am I missing something? Is there a neat Laravel way of solving this? It seems odd that old() simply does not work for this particular case.
This is not a new problem, how do others handle this?
This is the solution I referred to in my question. It works well, and 6 months later, it does not seem as clunky as when I posted the question. I'd be happy to hear how others are doing this though.
I have an Html helper, created as described in this question, and aliased in config/app.php as described in the first part of this answer to that question. I added a static method to it:
namespace App\Helpers;
use Illuminate\Support\ViewErrorBag;
class Html {
/**
* Shortcut for populating checkbox state on forms.
*
* If there are failed validation errors, we should use the old() state
* of the checkbox, ignoring the current DB state of the field; otherwise
* just use the DB value.
*
* #param string $name The input field name
* #param string $value The current DB value
* #return string 'checked' or null;
*/
public static function checked($name, $value) {
$errors = session('errors');
if (isset($errors) && $errors instanceof ViewErrorBag && $errors->any()) {
return old($name) ? 'checked' : '';
}
return ($value) ? 'checked' : '';
}
}
Now in my views I can use it like so:
<input type='checkbox' name='unicorns' value='1' {{ \Html::checked('unicorns', $model->unicorns) }}>
This correctly handles all combinations of DB and submitted state, on initial load and after failed validation.
I came across the same problem and found this old post. Thought to share my solution:
<input type="checkbox" name="unicorns" class="form-check-input" id="verified" {{ !old()?$model->unicorns:old('unicorns')?' checked':'' }}>
{{ !old()?$model->unicorns:old('unicorns')?' checked':'' }}
Nested ternaries: The first ternary provides the condition for the second:
When there is no old() array, there is no post, thus the DB value $model->unicorns will be used as the condition like so:
{{ $model->unicorns?' checked':'' }} will correctly evaluate on a value of either 0 or 1
If however old() array is present, we can use the existence of the old('unicorns') variable as the condition like so:
{{ old('unicorns')?' checked':'' }} will correctly evaluate on a value of on or no value.
It's a bit of type juggle and you have the nested ternary, but it works well.
I had a similar situation and my solution was to add a hidden field just before the checkbox field. So, in your case it would be something like:
<input type='hidden' name='unicorns' value='0'>
<input type='checkbox' name='unicorns' value='1' {!! old('unicorns', $model->unicorns) ? ' checked' : '' !!}>
That way, when the checkbox is not ticked, a value of 0 for that field will still be present in the post request. When it is ticked then the value of the checkbox will overwrite the value in the hidden field, so the order is important. You shouldn't need to use your custom class with this approach.
Does that work for you?
From Don't Panic 's answer, you could do it like this in blade:
<input type="checkbox" class="form-check-input" value='true'
#if ($errors->any())
{{ old('is_private') ? 'checked' : '' }}
#else
{{ isset($post) && $post->is_private ? 'checked' : '' }}
#endif
>
Hope it helps.
I do this
<input id="main" class="form-check-inline"
type="checkbox" name="position" {{old('position',$position->status)?'checked':''}}>
I actually do a simple ternary operator when persisting checkbox states:
<input name='remember' type='checkbox' value='1' {{ old('remember') ? 'checked' : '' }}>
Edit:
<input name='remember' type='checkbox' value='yes' {{ old('remember') == 'yes' ? 'checked' : '' }}>

Laravel: variable + parameter in view

I want to ask if it is possible to do something like this in View in Laravel 5.2:
<p> This is window: {{$element_ + 'window'}} </p>
<p> This is wall: {{$element_ + 'wall'}} </p>
The values for this variables are from $element_window, $element_wall.
There are couple of options.
First - is to use #php block in .blade file for dynamic output:
#php
${'window'} = ${$element_.'window'}
#endphp
Second is to write custom blade extension to output anything you need.
Third is to define custom method in your Model (if you use one).
However I should mention, that such variable assignment inside template (first option) is not recommended. It's hardly readable and could cause Exceptions if such dynamically created variables do not exist at some point. Not saying that this is not presentation logic.
If you want to dynamically name a variable.. you can do the following.
<p> This is window: {{ ${'element_'.'window'} }} </p>
<p> This is wall: {{ ${'element_'.'wall'} }} </p>
That should work.
But if just want to concatenate a string to the variable... you can use "." :-)

Laravel Blade Request method

Recently I started learning Laravel by following the Laravel From Scratch cast(https://laracasts.com/series/laravel-5-from-scratch).
Right now I'm trying to add additional functionality to the registration form(starting with error feedback) and I already ran into a problem.
Is there a (native) way to check wether the form has been submitted or not?
I tried to use:
{{ Request::method() }}
But even after pressing Register on the default scaffold generated by running the command php artisan make:auth it returns GET while the action of the form is POST and it triggers a route with a POST Request type.
The reason for all of this is that I want to add a CSS class to a element based on the following requirements.
if form is submitted
if $errors->has('name') //is there an error for name(example)
add 'has-error' class
else
add 'has-success' class
endif
endif
Does anybody know a solution for it?
I think you want to achieve this:
if( old('name') ){ // name has been submitted
if( $errors->first('name') ){ // there is at least an error on it
// add error class
}else{ // has been submitted without errors
// add valid class
}
}
That in a input field is something like this:
<input name="name" class="validate{{ old('name') ? ( $errors->first('name') ? ' invalid' : ' valid') : '' }}" type="text" value="{{ old('name') }}">
Rick,
You can validate you should have a look at the validate function in Laravel. You can validate the input you sent in and when there are errors send them back into your view.
For examples look at the url: https://laravel.com/docs/5.1/validation
Hope this helps.

Categories