how to render columns in laravel datatable? - php

i'm got stuck for 2 days, i got confused how to render column usind yajra/laravel-datatable
i'm using postgre as database, and yajra/laravel-datatables as package.
i have query builder like this
$data = DB::select("SELECT * FROM get_list_count_amount_transaction('chat', 'done', '2019-03-01', '2021-12-31' )")[0];
which generates a value of object : (i use var_dump() to see the value)
{ ["list_data"]=> string(2171)
"[{"id":"44649ccd-9195-4964-b48c-ed2098077dc5","kd_join":1,"status":"done","booking_date":"2021-04-18","transaction_type":"chat","price":4000.00,"date_create":"2021-04-18T19:56:57"},
{"id":"e500d2c1-99ae-4436-8ecc-8073f4f05bba","kd_join":1,"status":"done","booking_date":"2021-03-20","transaction_type":"chat","price":10000.00,"date_create":"2021-03-19T21:41:41"}
]"
["count_transaction"]=> int(12)
["total_amount_transaction"]=> string(9) "160500.00"
}
i'm confused, how to render list_data into a table using datatble
this is my html builder function :
public function html()
{
return $this->builder()
->columns($this->getColumns())
->minifiedAjax()
->addAction(['width' => '200px'])
->addColumnBefore([
'defaultContent' => '',
'data' => 'DT_Row_Index',
'name' => 'DT_Row_Index',
'title' => 'No',
'render' => function () {
return 'function(data,type,fullData,meta){return meta.settings._iDisplayStart+meta.row+1;}';
},
'orderable' => false,
'searchable' => false,
'exportable' => false,
'printable' => true,
'footer' => '',
]);
}
protected function getColumns()
{
return [
['data' => 'transaction_type', 'name' => 'transaction_type', 'title' => 'Tipe Transaksi', 'orderable' => false],
['data' => 'status', 'name' => 'status', 'title' => 'Status', 'orderable' => false],
['data' => 'booking_date', 'name' => 'booking_date', 'title' => 'Tanggal Booking', 'orderable' => false],
['data' => 'price', 'name' => 'price', 'title' => 'Jumlah', 'orderable' => false],
];
}
}

Just grab the list_data, use json_decode and laravel collection to make your needed structure. Try to use map, filter, mapWithKeys or whatever suitable.
For Instance:
collect(json_decode($listData))->mapWithKeys(function($item)){
//
}

Related

How to properly fix - Cannot use empty array elements in arrays

I have the code below but it showing an error "Cannot use empty array elements in arrays".
It seems that the issue is in this line }), collect(json_decode($post['comments'], true))->map(function ($comment) {
Code:
'data' => [
'comments' =>
collect(json_decode($configs['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
}), collect(json_decode($posts['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
}),
]
If we simplify your code it seems like this;
'data' => [
'comments' =>
collect(),
collect()
]
It is not a valid syntax. You can try like this;
$comments = collect(json_decode($configs['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
});
$postComments = collect(json_decode($posts['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
});
'data' => [
'comments' => $comments->merge($postComments)->toArray()
];

Unable to get name against the id in yii2 gridview

I have a index view in which I have a field name sub-division. The field displays the id. But I want to display it's name instead of ID.
What I have done?
I have placed a function in my Model
public function getSubdivision()
{
return $this->hasOne(SurveyHescoSubdivision::className(), ['id' => 'sub_division']);
}
In my search model I have done filtering like
$query->andFilterWhere([
'id' => $this->id,
'meter_id' => $this->meter_id,
'created_by' => $this->created_by,
'updated_by' => $this->updated_by,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'store_id' => $this->store_id,
'sub_division'=> $this->sub_division,
'status'=>'Inventory Stored',
]);
And in my index view
[
'label' => 'Sub-Division',
'value' => function ($d) {
return $d->subdivision->name;
},
// 'filter' => Html::activeDropDownList($searchModel, 'sub_division', \common\models\SurveyHescoSubdivision::toArrayList(), ['prompt' => "Sub-Div", 'class' => 'form-control']),
],
The table has the name column against the id.
When I goto my index page I am getting the below exception
Trying to get property of non-object
I have done this thing in other views but I don't know why this is showing
Any help would be highly appreciated.
Your subdivision id is empty, Use :
[
'label' => 'Sub-Division',
'value' => 'subdivision.name',
],
OR
[
'label' => 'Sub-Division',
'value' => function ($d) {
return !empty($d->sub_division) ? $d->subdivision->name : null;
},
],

Change Fieldset Fields' required parameter dynamically

I have a moneyFieldset with 2 fields, amount and currency.
class MoneyFieldset ...
{
public function __construct($name = null, $options = array())
{
parent::__construct($name, $options);
$this->setHydrator(...);
$this->add(array(
'name' => 'currency',
'type' => 'select',
'options' => array(
'value_options' => \Core\Service\Money::getAvailableCurrencies(true),
),
'attributes' => array(
'value' => \Core\Service\Money::DEFAULT_CURRENCY,
),
));
$this->add(array(
'name' => 'amount',
'type' => 'text',
));
}
}
public function getInputFilterSpecification()
{
$default = [
'amount' => [
'required' => false,
'allow_empty' => true,
'filters' => [
['name' => AmountFilter::class]
],
'validators' => [
]
],
'currency' => [
'required' => false,
'allow_empty' => true,
'filters' => [
['name' => StringToUpper::class]
],
'validators' => [
]
]
];
return \Zend\Stdlib\ArrayUtils::merge($default, $this->filterSpec, true);
}
I'm using moneyFieldset in my other fieldsets like this:
// Price Field
$this->add(array(
'name' => 'price',
'type' => 'form.fieldset.moneyFieldset',
'attributes' => array(
'required' => true,
'invalidText' => 'Please type an amount'
),
'options' => array(
...
),
));
When I set filter like this:
function getInputFilterSpecification()
{
'price' => [
'required' => true,
'allow_empty' => false,
],
}
It's not working because price has 2 fields, so how can I say price[amount] and price[curreny] is required?
You can provide the input specifications for the nested fieldset (within the context of the form) using the following array structure.
public function getInputFilterSpecification()
{
return [
// ...
'price' => [
'type' => 'Zend\InputFilter\InputFilter',
'amount' => [
'required' => true,
],
'currency' => [
'required' => true,
]
],
//...
];
}
If you are dynamically modifying the values of the input filter it might be worth considering creating the validator using a service factory class and then attaching it to a form using the object API rather than arrays.
As I said in #AlexP's comment, a field, or a group of field declared as Required like this :
function getInputFilterSpecification()
{
'price' => [
'required' => true,
'allow_empty' => false,
],
}
Not means that it will be print an html like this :
<input type="text" required="required"/>
It just check when you'll do $form->isValid() if your fields are empty and required or other checks.
To achieve that, you just have to set in attributes that you want to require those fields. As you already did. Attributes can add, same as class attribute, html code to an input.
P.S : AlexP's answer is the best answer I just give more info about it.

Yii2 ListView custom data-attribute based on currend DP model

I need to set custom data-attribute to the ListView elements. As example I try to get current DataProvider model id. But I still view error "htmlspecialchars() expects parameter 1 to be string, object given". Please check my code and halp me - how I should get this ID?
<?= ListView::widget([
'dataProvider' => $photoProvider,
'id' => 'photo-list',
'itemView' => '_photoListItem',
'viewParams' => [
'fullView' => true,
],
'options' => [
'tag' => 'ul',
'class' => 'list-view'
],
'itemOptions' => [
'tag' => 'li',
'class' => 'item',
'data' =>[
'test' => function ($model, $key, $index, $widget) {
return Html::encode($model->id);
}
]
],
'pager' => [
'class' => ScrollPager::className(),
'container' => '#photo-list',
'item' => '.item',
'triggerText' => '<div class="btn more">Load More</div>',
'noneLeftText' => '',
'triggerOffset' => 2,
'negativeMargin' => 200
],
'layout' => "{items}\n{pager}",
]);
?>
This is not possible in the ListView, according to the doc:
'data' => [
'test' => function ($model, $key, $index, $widget) {
return Html::encode($model->id);
}
]
You cannot use a function here. Only static values are allowed.
Alternatively, you can provide those attributes in tags of your _photoListItem view file.

YiiBooster. TbEditableColumn. Property "attribute" should be defined

I have a problem with TbEditedableColumn in YiiBooster 4.0.1
View:
$this->widget(
'application.extensions.booster.widgets.TbGridView',
array(
'type' => 'striped bordered',
'dataProvider' => new CActiveDataProvider('Stats'),
'columns' => array(
'pid',
array(
'class' => 'application.extensions.booster.widgets.TbEditableColumn',
'name' => 'login',
'sortable' => false,
'editable' => array(
//'model' => $model,
//'attribute' => 'login',
'url' => $this->createUrl('stats/editableSaver'),
'placement' => 'right',
'inputclass' => 'span3'
)
)
),
)
);
Controller:
public function actionEditableSaver()
{
Yii::import('application.extensions.booster.components.TbEditableSaver');
$es = new TbEditableSaver('Stats');
$es->update();
}
When I try to save the edited fields, I got this exception: Property "attribute" should be defined.
$es->attributes is empty.
How to fix that? Thanks.
From the source code, TbEditableSaver::update() obtains the attribute from a post or get parameter name:
$this->attribute = yii::app()->request->getParam('name');
$this->value = yii::app()->request->getParam('value');
//checking params
if (empty($this->attribute)) {
throw new CException(Yii::t('TbEditableSaver.editable', 'Property "attribute" should be defined.'));
}
In order for this parameter to be sent in the update request it needs to be defined in the editable array. To fix this:
'class' => 'application.extensions.booster.widgets.TbEditableColumn',
'name' => 'login',
'sortable' => false,
'editable' => array(
'name' => 'login',
'url' => $this->createUrl('stats/editableSaver'),
'placement' => 'right',
'inputclass' => 'span3'
)

Categories