Laravel different styles - php

Hello i have one problem i have Article model its haves 5 types and one of the types must have different style in html
model
public static function scopeAllNews($query)
{
return Article::whereIn('type', ['news', 'interview', 'analytic', 'quote'])->statusOn()->orderBy('created_at', 'DESC');
}
controller
public function news()
{
$newsFirstLine = Article::allNews()->get()->take(8);
$newsSecondLine = Article::allNews()->FilterContent($newsFirstLine->pluck('id'))->get();
$populars = Article::popular();
$articles = Article::all();
return view('pages/news/news-list', compact('newsFirstLine', 'newsSecondLine', 'populars', 'articles'));
}
blade
<div class="container w-100 d-block d-xs-none">
<div class="d-flex w-100">
<span class="fas fa-yellow-bullet text-yellow pr-10px font-size-20"></span>
<div class="font-size-20 font-size-xs-16 font-bold-caps text-blue-100">#tr('web.news')</div>
</div>
<div class="row">
#foreach($newsFirstLine as $news_item)
#include("cards/interviews", [
'image' => $news_item->image,
'slug' => $news_item->getUrl(),
'title' => $news_item->tr('title'),
'created' => $news_item->created_at->format('d.F.Y'),
'createdHi' => $news_item->created_at->format('H:i'),
])
#endforeach
#if($articles->type == 'quote')
#foreach($newsFirstLine as $quote)
#include("cards/quote", [
'slug' => $quote->getUrl(),
'title' => $quote->tr('title'),
'avatar' => $quote->respondent->image,
'publicPerson' => $quote->respondent->tr('name'),
'created' => $quote->created_at->format('d.m.Y'),
'createdHi' => $quote->created_at->format('H:i'),
])
#endforeach
#endif
</div>
</div>
#include("home.popularNews")
<div class="container w-100">
<div class="row">
#foreach($newsSecondLine as $news_item)
#include("cards/interviews", [
'image' => $news_item->image,
'slug' => $news_item->getUrl(),
'title' => $news_item->tr('title'),
'created' => $news_item->created_at->format('d.m.Y'),
'createdHi' => $news_item->created_at->format('H:i'),
])
#endforeach
#if($articles->type == 'quote')
#foreach($newsFirstLine as $quote)
#include("cards/quote", [
'slug' => $quote->getUrl(),
'title' => $quote->tr('title'),
'avatar' => $quote->respondent->image,
'publicPerson' => $quote->respondent->tr('name'),
'created' => $quote->created_at->format('d.m.Y'),
'createdHi' => $quote->created_at->format('H:i'),
])
#endforeach
#endif
</div>
</div>
but it's don't working if type will be quote it must include cards/quote and if its not quote type it must include cards/interviews
what's i'm doing wrong? (

Related

How to retrieve value from the migrations and display them

I used this for my migrations.
<?php
use Anomaly\Streams\Platform\Database\Migration\Migration;
class SnipcartModuleProductsCreateProductsFields extends Migration
{
/**
* The addon fields.
*
* #var array
*/
protected $fields = [
'name' => 'anomaly.field_type.text',
'description' => 'anomaly.field_type.text',
'sku' => [
'type' => 'anomaly.field_type.slug',
'config' => [
'slugify' => 'name',
'type' => '-'
],
],
'price' => [
"type" => "anomaly.field_type.decimal",
"config" => [
"min" => 0
]
],
'image' => 'anomaly.field_type.file',
'tags' => [
'type' => 'anomaly.field_type.tags',
'config' => [
'free_input' => true
]
]
];
}
Routing it from here
web.php
Route::get('/products', function () {
return view('products','ProductsController#getProducts');
});
Now How would I retrieve those values from here
ProductControllers.php
//name,description and price all the values should be pass to the products.blade.php
public function getProducts(){
$products = [];
return view('products', ['products' => $products]);
}
Then display it here
products.blade.php
#if (products)
<div class="row">
#foreach ($products as $product)
<div class="col-sm-4">
<div class="card" style="margin-bottom: 2rem;">
<div class="card-body">
<h4 class="card-title">{{ $product->name }}</h4>
<img />
<p class="card-text">{{ $product->description }}</p>
Buy for {{ $product->price }}
</div>
</div>
</div>
#endforeach
</div>
#endif

Yii2 Dynamic Data is not loading on all DepDrop in dynamic field

I'm trying to create a dynamic form for one of my projects. I used wbraganca's Dynamic From to achieve this. In my dynamic form I have a DepDrop to show subcategories list from a parent category.
My _form.php
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<div class="row">
<div class="col-md-6">
<?= $form->field($model, 'rq_job_no')->textInput() ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'rq_req_date')->widget(\yii\jui\DatePicker::class, [
//'language' => 'ru',
'dateFormat' => 'php:Y-m-d',
'clientOptions' => [
'changeMonth' => true,
'changeYear' => true,
'showButtonPanel' => true,
'yearRange' => '1990:2030',
'minDate' => date('Y-m-d'),
],
'options' => ['class' => 'form-control', 'readOnly' => true, 'placeholder' => 'Enter the Item Required Date'],
]) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'rq_priority_type')->dropDownList(['urgent' => 'Urgent', 'normal' => 'Normal'], ['prompt' => '--Select Priority Type--']) ?>
</div>
<div class="col-md-6">
</div>
<div class="col-md-6">
<?= $form->field($model, 'rq_approval_type')->dropDownList([1 => ' Approved Vendor Needed', 2 => 'Approved Submitted Needed', 3 => 'Warranty Certificate to be Collected', 4 => 'Long Lead Material',], ['prompt' => '--Select Type of Approval--']) ?>
<?php echo $form->field($model, 'rq_cat_type')->widget(Select2::class, [
'data' => $catData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-md-12">
<?= $form->field($model, 'rq_remarks')->textarea(['rows' => 6]) ?>
</div>
</div>
<!-- code for dynamic form -->
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="glyphicon glyphicon-envelope"></i> Request Items</h4>
</div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress[0],
'formId' => 'dynamic-form',
'formFields' => [
'item_name',
'item_qty',
'item_unit',
],
]); ?>
<div class="container-items">
<!-- widgetContainer -->
<?php foreach ($modelsAddress as $i => $modelAddress) : ?>
<div class="item panel panel-default">
<!-- widgetBody -->
<div class="panel-heading">
<h4 class="panel-title pull-left">Items</h4>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="fa fa-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="fa fa-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (!$modelAddress->isNewRecord) {
echo Html::activeHiddenInput($modelAddress, "[{$i}]rt_id");
}
?>
<?php //$form->field($modelAddress, "[{$i}]rt_item")->textInput(['maxlength' => true]) ?>
<?= $form->field($modelAddress, "[{$i}]rt_item")->widget(DepDrop::class, [
'options' => ['id' => 'reqitems-'.$i.'-rt_item'],
'pluginOptions' => [
'depends' => ['requests-rq_cat_type'],
'placeholder' => '--Select Location--',
'url' => Url::to(['/requests/subcat'])
]
]); ?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelAddress, "[{$i}]rt_qty")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelAddress, "[{$i}]rt_unit")->textInput(['maxlength' => true]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
My Controller action to load the subcategory
public function actionSubcat()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = self::getSubCatList($cat_id);
return ['output' => $out, 'selected' => ''];
}
}
return ['output' => 'No Category Available', 'selected' => ''];
}
public function getSubCatList($cat_id)
{
$output = [];
$category = Item::find()->where(['item_category' => $cat_id])->orderBy('item_title')->all();
if (empty($category)) {
$output[] = ['id' => '0', 'name' => 'No Category Available'];
} else {
foreach ($category as $cat) {
$output[] = ['id' => $cat->item_id, 'name' => $cat->item_title];
}
}
return $output;
}
My problem is that DepDrop is only loading the subcategory for the first loop of the dynamic form and leaves the rest loop blank. Attached screenshot for your reference.
Can anyone help by pointing what I am missing or how can I achieve my requirement.

File Upload field using ActiveForm in Yii2 framework does not work

I want to add a File Upload field in an ActiveForm in Yii2 framework, but it's not working, the file is not uploaded nor the name of the file is stored in the database column 'company_cover'.
If someone could help me find my mistake.
Thanks in advance.
The VIEW
<div class="block-body collapse" id="company-block">
<?php $form = ActiveForm::begin([
'id' => 'form-change-company',
'method' => 'post',
'action' => ['account/update-company'],
'enableAjaxValidation' => false,
'options' => ['enctype' => 'multipart/form-data'],
]);
?>
<div class="row">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-12">
<?= $form->field($modelAbout, 'group_id', [
'template' => '{input} {error}',
])->dropDownList([2 => t('app','Enable'), 1 => t('app','Disable')])->label(false);
?>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<?= $form->field($modelCompany, 'store_name', [
'template' => '{input} {error}',
])->textInput([ 'placeholder' => t('app','Store Name'), 'class' => ''])->label(false); ?>
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<?= $form->field($modelCompany, 'company_name', [
'template' => '{input} {error}',
])->textInput([ 'placeholder' => t('app','Company Name'), 'class' => ''])->label(false); ?>
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<?= $form->field($modelCompany, 'company_mail', [
'template' => '{input} {error}',
])->textInput([ 'placeholder' => t('app','Company E-Mail'), 'class' => ''])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<?= $form->field($modelCompany, 'company_no', [
'template' => '{input} {error}',
])->textInput([ 'placeholder' => t('app','Company No'), 'class' => ''])->label(false); ?>
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<?= $form->field($modelCompany, 'vat', [
'template' => '{input} {error}',
])->textInput([ 'placeholder' => t('app','VAT'), 'class' => ''])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
</div>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<?= $form->field($modelCompany, 'company_lat', [
'template' => '{input} {error}',
])->textInput([ 'placeholder' => t('app','Company Latitude'), 'class' => ''])->label(false); ?>
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<?= $form->field($modelCompany, 'company_lng', [
'template' => '{input} {error}',
])->textInput([ 'placeholder' => t('app','Company Longitude'), 'class' => ''])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<?= $form->field($modelCompany, 'file')->fileInput([ 'placeholder' => t('app','Company Cover'), 'class' => '']) ?>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<button type="submit" id="submit-company-info" class="btn-as" value="Submit"><?=t('app','Submit');?></button>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
The MODEL
class CustomerStore extends \app\models\auto\CustomerStore
{
// when inactive model
const STATUS_INACTIVE = 'inactive';
// when active model
const STATUS_ACTIVE = 'active';
// when deactivated
const STATUS_DEACTIVATED = 'deactivated';
public $file;
public function rules()
{
return [
[['store_name', 'company_name', 'company_mail', 'company_lat', 'company_lng', 'company_no', 'vat'], 'trim'],
[['store_name', 'company_name'], 'required'],
[['file'], 'file'],
[['store_name', 'company_name'], 'string', 'max' => 30],
[['company_no', 'vat'], 'string', 'max' => 20],
[['status'], 'safe']
];
}
/**
* #inheritdoc
*/
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors[] = [
'class' => SluggableBehavior::className(),
'value' => [$this, 'getSlug'] //https://github.com/yiisoft/yii2/issues/7773
];
return $behaviors;
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'store_id' => t('app', 'Store ID'),
'customer_id' => t('app', 'Customer'),
'store_name' => t('app', 'Store Name'),
'company_name' => t('app', 'Company Name'),
'company_mail' => t('app', 'Company E-Mail'),
'company_no' => t('app', 'Company No'),
'vat' => t('app', 'VAT'),
'status' => t('app', 'Status'),
'company_lat' => t('app', 'Company Latitude'),
'company_lng' => t('app', 'Company Longitude'),
'company_cover' => t('app', 'Company Cover'),
'created_at' => t('app', 'Created At'),
'updated_at' => t('app', 'Updated At'),
]);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCustomer()
{
return $this->hasOne(Customer::className(), ['customer_id' => 'customer_id']);
}
/**
* #return bool
*/
public function deactivate()
{
$this->status = self::STATUS_INACTIVE;
$this->save(false);
return true;
}
/**
* #return bool
*/
public function activate()
{
if($this->status == self::STATUS_DEACTIVATED || $this->status == self::STATUS_INACTIVE) {
$this->status = self::STATUS_ACTIVE;
$this->save(false);
}
return true;
}
/**
* #param $slug
* #return array|null|\yii\db\ActiveRecord
*/
public function findBySlug($slug)
{
return $this->find()->where(array(
'slug' => $slug,
))->one();
}
/**
* #param $event
* #return string
* //https://github.com/yiisoft/yii2/issues/7773
*/
public function getSlug($event)
{
if(!empty($event->sender->slug)) {
return $event->sender->slug;
}
return Inflector::slug($event->sender->store_name);
}
}
The CONTROLLER (the controller is quite long so i just paste the part for the file upload field)
public function actionUpload()
{
$modelCompany = new CustomerStore();
if (Yii::$app->request->isPost) {
$modelCompany->file = UploadedFile::getInstance($modelCompany, 'file');
if ($modelCompany->validate()) {
$modelCompany->file->saveAs('/' . $modelCompany->file->baseName . '.' . $modelCompany->file->extension);
}
}
return $this->render('upload', ['model' => $modelCompany]);
}
I think you must to load post data to the model. You can try do like this
if ($modelCompany->load(Yii::$app->request->post())) {
$modelCompany->file = UploadedFile::getInstance($modelCompany, 'file');
if ($modelCompany->validate()) {
$modelCompany->file->saveAs('/' . $modelCompany->file->baseName . '.' . $modelCompany->file->extension);
}
}

Active Record in Yii2, Joining multiple table, find the rating of a thread, and retrieve the rating in ListView

I am confused with how to retrieve data that has been averaged after joining multiple tables.
Problem:
I have 3 tables i want to join, User, Thread, and Rate.
I need all data from the tables and for rate table, i need to do average operation to get the rating value
My code is:
MyController looks like this:
public function actionHome(){
$dataProvider = new ActiveDataProvider([
'query' => Thread::retrieveAll(),
'pagination' => [
'pageSize' =>5,
],
]);
return $this->render('home', ['listDataProvider' => $dataProvider]);
}
My active record class (model class) looks like this:
public static function retrieveAll(){
return Self::find()->joinWith('user')
->joinWith('rate')
->select(['AVG(rate.rating) as rating, thread.*, user.*'])
->groupBy('rate.thread_id');
}
public function getUser(){
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getRate(){
return $this->hasMany(Rate::className(), ['thread_id' =>'thread_id']);
}
Retrieve all is used in the data provider query
My home class looks like this:
<div class="col-md-6">
<?= ListView::widget([
'dataProvider' => $listDataProvider,
'options' => [
'tag' => 'div',
'class' => 'list-wrapper',
'id' => 'list-wrapper',
],
'layout' => "{summary}\n{items}\n{pager}",
'itemView' => function ($model, $key, $index, $widget) {
return $this->render('_list_thread',['model' => $model]);
},
'pager' => [
'firstPageLabel' => 'first',
'lastPageLabel' => 'last',
'nextPageLabel' => 'next',
'prevPageLabel' => 'previous',
'maxButtonCount' => 3,
],
]) ?>
</div>
my item for the listview looks like this:
<article>
<div class="box col-md-12">
<div class="row">
<?= Html::a($model->title, Url::to('thread/index.php?id='. $model->thread_id))?>
</div>
<div class="row">
<p> <?= $model->content ?> </p>
</div>
<div class="row">
<div class="col-md-5">
<?= StarRating::widget([
'name' => 'rating_2',
'value' => 2.5,
'readonly' => true,
'pluginOptions' => [
'showCaption' => false,
'min' => 0,
'max' => 5,
'step' => 1,
'size' => 'xs',
]])?>
</div class="col-md-7" align="center center-vertical">
<p align="right" style="font-size:8px">Created by <?= $model->user->first_name?> <?=$model->user->last_name?> at <?= $model->date_created ?></p>
</div>
</div>
<br><br><br>
<br><br><br><br><br><br><br><br><br>
</article>
I can retrieve $model->user->first_name and lst_name but i cannot retrieve $model->rate->rating
Any suggestion for this?
$this::select('AVG(rate.rating) as rating',*)->innerJoin('rate','your codition on you have to take a join')->innerJoin('thread','your codition on you have to take a join')->all()->groupBy('rate.thread_id');

CGridView styling specific column, inserting <div> inside <td> elements

I’m trying to apply custom styling to specific columns generated by CGridView. I need to insert inside the elements, but I can’t figure out how to do it.
Here is the view file:
<div id="shortcodes" class="page">
<div class="container">
<!-- Title Page -->
<div class="row">
<div class="span12">
<div class="title-page">
<h2 class="title">Available Products</h2>
</div>
</div>
</div>
<!-- End Title Page -->
<!-- Start Product Section -->
<div class="row">
<?php
$this->widget('bootstrap.widgets.TbGridView', array(
'id' => 'products-grid',
'dataProvider' => $dataProvider,
'ajaxUpdate' => TRUE,
'pager' => array(
'header' => '',
'cssFile' => false,
'maxButtonCount' => 25,
'selectedPageCssClass' => 'active',
'hiddenPageCssClass' => 'disabled',
'firstPageCssClass' => 'previous',
'lastPageCssClass' => 'next',
'firstPageLabel' => '<<',
'lastPageLabel' => '>>',
'prevPageLabel' => '<',
'nextPageLabel' => '>',
),
'columns' => array(
'id',
'name',
'category',
'brand',
'weight_unit',
'price_unit',
'flavors',
array(
'name' => 'providers',
'htmlOptions' => array('class' => 'label label-info'),
),
),
));
?>
</div>
<!-- End Product Section -->
</div>
</div>
So I want to style the column named “providers”. Using htmlOptions does add the class to the td column, but the alignment of the column is getting out of place. That’s why I wanted to wrap it inside a <div>, to apply the proper alignments and styling.
Right now it appears like this:
<tr class="even">
<td>414</td>
<td>Owl Book</td>
<td>Night Owl Trance</td>
<td>Binaural Beats</td>
<td> 400 Grams</td>
<td>$569.66</td>
<td>Ether</td>
<td class="label label-info">Shrooms.com</td>
</tr>
What I was looking to do is this:
<tr class="even">
<td>414</td>
<td>Owl Book</td>
<td>Night Owl Trance</td>
<td>Binaural Beats</td>
<td> 400 Grams</td>
<td>$569.66</td>
<td>Ether</td>
<td><div class="label label-info">Shrooms.com</div></td>
</tr>
So, how would I do this? Is there an option for it? As far as I know, htmlOptions will only add attributes to the element.
Not tested, but I think you can use something like this.
'flavors',
array(
'name' => 'providers',
'value' => "<div class=label label-info>$data->providers</div>"
),
Ok, i first tried redGREENblue's answer, but i gives a Undefined variable: data
'value' => ''.$data->providers.'',.
Then after some advice in the Yii forums i found the solution. Basically what i did was return the value from within a function closure, and it worked,
The working code ::
<div id="shortcodes" class="page">
<div class="container">
<!-- Title Page -->
<div class="row">
<div class="span12">
<div class="title-page">
<h2 class="title">Available Products</h2>
</div>
</div>
</div>
<!-- End Title Page -->
<!-- Start Product Section -->
<div class="row">
<?php
$this->widget('bootstrap.widgets.TbGridView', array(
'id' => 'products-grid',
'dataProvider' => $dataProvider,
'filter' => $dataProvider->model,
'ajaxUpdate' => TRUE,
'pager' => array(
'header' => '',
'cssFile' => false,
'maxButtonCount' => 25,
'selectedPageCssClass' => 'active',
'hiddenPageCssClass' => 'disabled',
'firstPageCssClass' => 'previous',
'lastPageCssClass' => 'next',
'firstPageLabel' => '<<',
'lastPageLabel' => '>>',
'prevPageLabel' => '<',
'nextPageLabel' => '>',
),
'columns' => array(
'id',
'name',
'category',
'brand',
'weight_unit',
'price_unit',
'flavors',
array(
'name' => 'providers',
'value' => function($data) { //*the closure that works*
return '<div class="label label-info">'.$data->providers.'</div>';
},
'type' => 'raw',
),
),
));
?>
</div>
<!-- End Product Section -->
</div>

Categories