Blade, Use html inside variable being passed into partial view is not being rendered - html

I'm using a partial view to display page header, that view accepts two variables one is Icon the other is a title.
pageHeader.blade.php:
<div class="page-header">
<div class="row">
<!-- Page header, center on small screens -->
<h1 class="col-xs-12 col-sm-4 text-center text-left-sm"><i class="fa {{$icon}} page-header-icon"></i> {{$title}}</h1>
</div>
and I'm using it like so:
#include('zdashboard._partials.pageHeader',['icon'=>'fa-pencil','title'=>'<strong>Editing</strong>'.$center->translations()->whereLang('en')->first()->name])
Sometimes I like to make one word strong or italic like the example above but, blade engine won't render the HTML tags I'm typing as part of title variable (the output like the photo down).
So is there any idea how to solve this? Am I doing it!
wrong?
The output

By default in Laravel 5 {{ $title }} construction wil be escaped.
If you don't want the data to be escaped, you may use the following syntax:
{!! $title !!}
Read more about Blade control structures: http://laravel.com/docs/5.0/templates#other-blade-control-structures

view
#if(Session::has('success'))
<div class="alert alert-success">
{!! Session::get('success')!!}
</div>
#endif
Controller
public function store(Request $request)
{
$this->validate($request, [
'product_code' => 'required|unique:products',
'product_name' => 'required',
'description' => 'required',
'price' => 'required',
'brand_id' => 'required',
'category_id' => 'required',
]);
$product = Product::create([
'product_code' => $request->input('product_code'),
'product_name' => $request->input('product_name'),
'description' => $request->input('description'),
'price' => $request->input('price'),
'brand_id' => $request->input('brand_id'),
'category_id' => $request->input('category_id'),
]);
return redirect()->route('products.index')->with('success',
"The product <strong>".$product->product_name."</strong> has successfully been created.");
}

Related

Laravel 7 assigning foreignID using request->route('id)?

I'm trying to submit a form to a store function. The problem is, the foreignKey (degree_id) keeps being set to ?(null) even though I set it to the id in the route.
Form:
{!! Form::open(['url' => 'degrees/{{ $Degree->id }}', 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('title', 'Title')}}
<br>
{{Form::text('title', '', ['class' => 'form-control', 'placeholder' => 'Title'])}}
</div>
#error('title')
<small class="text-danger">{{ $message }}</small>
#enderror
Route:
Route::post('degrees/{degree}', 'ModuleController#store');
Store function:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'desc' => 'required',
'long_desc' => 'required',
'hours' => 'required',
'credits'=> 'required',
]);
$module = new Module;
$module->title = $request->input('title');
$module->desc = $request->input('desc');
$module->long_desc = $request->input('long_desc');
$module->hours = $request->input('hours');
$module->credits = $request->input('credits');
$module->degree_id = $request->route('id');
$module->save();
return redirect('/home/modules');
}
I've since set the degree_id to nullable, so I can create my module and have it display alright, but for future functionality I'd like it to be set to the degree_id. Any idea whats not working here? I do have model-relationships set up, but I can't see how that'd impact it. Maybe something in the route itself?
You can't use Blade Mustache inside a php element, use this instead:
{!! Form::open(['url' => 'degrees/' . $Degree->id , 'method' => 'POST']) !!}
Your route parameter is not named id, you declared it in your route definition as the name degree ('degrees/{degree}').
$request->route('degree');
Change route from
Route::post('degrees/{degree}', 'ModuleController#store');
TO
Route::post('degrees/{id}', 'ModuleController#store');

How to pass parameter from controller to another view (a form) inside a view

This is my actionIndex() in my controller.
public function actionIndex()
{
$featured= new ActiveDataProvider([
'query'=>News::find()
->where(['not', ['featuredOrder' => null]])
->orderBy('featuredOrder'),
]);
$checkList=Featured::find()
->joinWith('news')
->where(['news.featuredOrder'=>null])
->orderBy('featuredOrder')
->all();
return $this->render('index', [
'dataProvider' => $featured,
'checkList'=>$checkList,
]);
I have a listview in my index view which is rendered by this controller. If an item of the listview is clicked, it will display the detailView of each item, along with the update button to update the item's data which will generate a form to update. I need to pass the $checklist to this form. Later I'll use this $checklist to populate a drop-down list. I wonder how to pass the parameter. I could just move this part to the form view, but I think it's not a good practice to have this inside a view.
$checkList=Featured::find()
->joinWith('news')
->where(['news.featuredOrder'=>null])
->orderBy('featuredOrder')
->all();
This is my index :
<?php echo \yii\widgets\ListView::widget([
'dataProvider' => $featured,
'itemView'=>'_post',
'options'=>['class'=>'row'],
'itemOptions'=>['class'=>'col-md-4'],
'summary'=>'',
'viewParams'=>['cekList'=>'cekList'],
'pager' => [
'options'=>['class'=>'pagination justify-content-center'],
'linkContainerOptions'=>['class'=>'page-item'],
'linkOptions'=>['class'=>'page-link'],
_post view
div class = "panel panel-default">
<div class = "panel-body">
<h2 class="truncate text-center"><?=Html::a($model->title, ['view', 'id' => $model->id] ) ?> </h2>
<hr>
</div>
<!-- another block of code, but unrelated, so I won't include it -->
This is the view.php file,being rendered if an item's title in the _post above is clicked.
<div class="row justify-content-between">
<div class="col-xs-6">
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Do you want to delete this post?',
'method' => 'post',
],
]) ?>
If an update button is clicked, it will render a form. I want to pass the param to this form.
My Answer is Based On this Query :
$checkList=Featured::find()
->joinWith('news')
->where(['news.featuredOrder'=>null])
->orderBy('featuredOrder')
->all();
If you want to use only above query for drop down there is a two way to do that :
1. Create A method in controller and use array helper method for drop down list add select statement in query
public function checklistDropdown(){
$items = Featured::find()
->joinWith('news')
->where(['news.featuredOrder'=>null])
->orderBy('featuredOrder')
->all();
$items = ArrayHelper::map($items, 'id', 'name');
}
In your index action call this method pass just like you passed model and dataprovider
2. second option is more feasible i think
Create a component helper for generic drop down list add above method in that component and use that component to call the method in you view , you can define that method as STATIC . It will be reusable.

yii2 ActiveForm numeric textfield

I've created an ActiveForm using yii2 like this:
<?=$form->field($item, 'finalPrice', [
'options' => [
'tag' => 'div',
'class' => '',
],
'template' => '<span class="col-md-2 col-lg-2"><label class="control-label">Final item price</label>{input}{error}</span>'
])->textInput([
// ** i want numeric value **
])->label(false)?>
and it rendered a result of:
<span class="col-md-2 col-lg-2"><label class="control-label">Final item price</label><input type="text" id="item-finalprice" class="form-control" name="Item[finalPrice]"><p class="help-block help-block-error"></p></span>
now i want to make it < input type="number" .. and not text.. (so user could change value using browser up/down buttons). is there any way to do it?
You can use ->textInput(['type' => 'number'] eg :
<?=$form->field($item, 'finalPrice', [
'options' => [
'tag' => 'div',
'class' => '',
],
'template' => '<span class="col-md-2 col-lg-2"><label class="control-label">Final item price</label>{input}{error}</span>'
])->textInput([
'type' => 'number'
])->label(false)?>
Try this . it worked for me
<?= $form->field($model, 'amount')->textInput(['type' => 'number']) ?>
Field like Phone Number/Membership No etc, some time we allow user only to enter numeric input in a text field. In such case applying pattern match rule work great for me.
Simply set a rule in the model class and you are done.
public function rules()
{
return [
...
[['contactno'], 'string', 'max' => 25],
[['contactno'], 'match' ,'pattern'=>'/^[0-9]+$/u', 'message'=> 'Contact No can Contain only numeric characters.'],
...
];
}
<?= $form->field($model, 'code')->textInput(['type'=>'number']) ?>

Getting label with colon for model's field in a form

I need to have Body: (with colon at the end), not Body rendered as label for each field in my form. How can I achieve this the best way?
I tried modifying fieldConfig => template in ActiveForm::begin by adding div class=\"\">{label}:</div> into it:
<?php $form = ActiveForm::begin([
'id' => 'edit-form',
'options' => ['class' => 'form-horizontal'],
'fieldConfig' => [
'template' => "<div class=\"\">{label}:</div>\n<div class=\"\">{input}</div>\n<div class=\"\">{error}</div>",
'labelOptions' => ['class' => 'edit-label'],
]]); ?>
but it is wrong. Colon is rendered as separate DOM element, with incorrect styling and looks ugly.
I tried doing this awfully in CSS:
.edit-label::after {
content: ":";
}
but this is even worse.
I remember, that I made a lot of stupid things in Yii1 to get this. I don't want to repeat these stupid things, when implementing this in Yii2. What is the best way of achieving this?
When using Bootstrap 3 (yii\bootstrap\ActiveField) you can use additional placeholders in the $template and you need to replace {label} with {beginLabel}{labelTitle}:{endLabel}:
<?php $form = ActiveForm::begin([
'id' => 'edit-form',
'options' => [
'class' => 'form-horizontal',
'enctype'=>'multipart/form-data'
],
'fieldConfig' => [
'template' => "<div class=\"\">{beginLabel}{labelTitle}:{endLabel}</div>\n<div class=\"\">{input}</div>\n<div class=\"\">{error}</div>",
'labelOptions' => ['class' => 'edit-label'],
],
]); ?>
I don't know, how to solve this problem, if you're using basic yii\widgets\ActiveField instead.

Yii2: Method Not Allowed (#405) while logout user

I am loging out user through following code. This is my view code behind logout button:
<li>
<a href="<?= Url::to(['site/logout'])?>">
<i class="fa fa-sign-out"></i> Log out
</a>
</li>
My controller code is:
public function actionLogout()
{
Yii::$app->user->logout();
$model = new LoginForm();
$this->layout = 'index';
return $this->render('login', ['model' => $model]);
}
In the logout it shows me:
Method Not Allowed. This url can only handle the following request
methods: POST.
What is it?
Seems like you have VerbFilter attached to logout action in your SiteController:
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
That means this action can requested only with POST method, and you are requesting with GET, that's why exception #405 is thrown.
Either remove this from VerbFilter or add data-method attribute to request with POST:
...
Update: Another reason of this problem can be missing dependency for yii\web\YiiAsset. Make sure it's included in AppAsset:
public $depends = [
'yii\web\YiiAsset',
...
];
YiiAsset provides data-method attribute feature which gives possibility to link act as a form with action post by writing less code. Without asset obviously link will act as regular link and standard GET request will be sent.
You can also use a custom template
'items' => [
[
'label' => 'Logout',
'url' => ['/user/security/logout'],
'template' => '{label}',
],
]
u can change the view code and echo instead of
<li>
<a href="<?= Url::to(['site/logout'])?>">
<i class="fa fa-sign-out"></i> Log out
</a>
</li>
this one:
<?= Html::a('<i class="fa fa-sign-out"></i>',
['/site/logout'],
['class'=>'btn btn-default btn-flat']), //optional* -if you need to add style
['data' => ['method' => 'post',]])
?>
You must only replace 'logout' => ['post'], with 'logout' => ['get']. In this way your error will be solved.
This way works only with Yii Framework version 2.
See more at: http://tutorials.scrisoft.com/solve-this-error-method-not-allowed-this-url-can-only-handle-the-following-request-methods-post/#sthash.fQmwYPJH.dpuf
If you are using Nav::widget to generate menus, the logout item should have linkOptions specified:
[
'label' => '<i class="fa fa-sign-out"></i>Logout',
'url' => ['/logout'],
'linkOptions' => ['data-method' => 'post'],
],
Following works too assuming you might extra class and data-method attribute.
<?=
Html::a(
'Logout (' . Yii::$app->user->identity->username . ')',
['/site/logout'],
['class' => 'ui inverted button', 'data-method' => 'post']
);
?>
this code is working for AdminLTE template.
['label' => 'Sign out (' . Yii::$app->user->identity->username . ')','url' => ['/site/logout'],'template' => '{label}',],