Concatenation in Yii2 activeDropDownList - yii2

Showing names of MilliStones in activeDropDownList of Yii2, but now i wants to concatenate another field with it(Like number of millistone).
e.g ( Milli Stone Name - Number of stones ).
<?= Html::activeDropDownList($model, 'milli_stone_id',ArrayHelper::map(MilliStones::find()->where(['cat_id' => $Rings->milli_cat])->all(), 'id', 'name'),['prompt'=>'Select Milli Stone','class'=>'form-control']) ?>

You should use a select clause in find() this way
<?= Html::activeDropDownList($model, 'milli_stone_id',
ArrayHelper::map(MilliStones::find()->
select('id, concat(name, id) as name ')->
where(['cat_id' => $Rings->milli_cat])->all(), 'id', 'name'),
['prompt'=>'Select Milli Stone','class'=>'form-control']) ?>

<?= Html::activeDropDownList($model, 'milli_stone_id',ArrayHelper::map(MilliStones::find()->where(['IN', 'id', $IdsArray2])->asArray()->all(),
'id',
function($model, $defaultValue) {
return $model['id'].'-'.$model['name'];
}
),['prompt'=>'Select Milli Stone','class'=>'form-control']) ?>

Related

Yii2 grid sorting is not correct with ArrayDataProvider

I'm using array data provider for grid view widget since the data source is an API response. It's working fine, but when I try to sort the 'Name' column, it's sorting incorrectly with the lowercase first letters. Please check the table grid screenshot. The API response which I'm receiving is correct with the current sorting.
1. Table Grid
2. Model
$provider = new ArrayDataProvider([
'allModels' => #$response->data,
'pagination' => false,
'sort' => [
'attributes' => ['id', 'name', 'shortDescription'],
],
]);
3. View
<?= GridView::widget([
' dataProvider' => $dataProvider,
'columns' => [
'id',
'name',
'shortDescription'
],
'options' => ['class' => 'content'],
'tableOptions' => ['class' => 'table table-striped table-hover'],
'summary' => Yii::t('app', 'Showing').' {begin}-{end} of '.$total.' '.Yii::t('app', 'items')
]);
?>
Please guide me to fix this. Thanks!

CakePHP 3 quoting function names defined in 'fields' configuration of my find() call

I am querying a database table conveniently named order and because of that I had to set 'quoteIdentifiers' => true in my app.php configuration. However, when I'm putting function names into the fields configuration of my find() call, CakePHP quotes them too.
$orders->find('all', array(
'fields' => array(
'DATE(Orders.date_added)',
'COUNT(*)',
),
'conditions' => array(
'Orders.order_status_id <>' => 0,
),
'group' => array(
'DATE(Orders.date_added)',
),
));
The query above ends up calling
SELECT <...>, `DATE(Orders.date_added)` FROM `order` <...>
which obviously throws an error.
I googled a lot, tried this:
$orders = $orders->find('all', array(
'conditions' => array(
'Orders.order_status_id <>' => 0,
),
'group' => array(
'DATE(Orders.date_added)',
),
))->select(function($exp) {
return $exp->count('*');
});
and that didn't work either, throwing me some array_combine error.
Is there any way for me to un-quote those function names, while keeping the rest of the query quoted automatically? Here's what I'm trying to accomplish:
SELECT <...>, DATE(Orders.date_added) FROM `order` <...>
Please help.
You should use function expressions, they will not be quoted, except for arguments that are explicitly being defined as identifiers:
$query = $orders->find();
$query
->select([
'date' => $query->func()->DATE([
'Orders.date_added' => 'identifier'
]),
'count' => $query->func()->count('*')
])
->where([
'Orders.order_status_id <>' => 0
])
->group([
$query->func()->DATE([
'Orders.date_added' => 'identifier'
])
]);
I'd generally suggest that you use expressions instead of passing raw SQL snippets wherever possible, it makes generating SQL more flexible, and more cross-schema compatible.
See also
Cookbook > Database Access & ORM > Query Builder > Using SQL Functions

Using from another table for radioList's select options

I want to use another table data for select options of radioList.
for getting better I mean, I want something like bellow code:
$form->field($model_add, 'link_type')->radioList([
'another table ID 1' => 'another table title 1',
'another table ID 2' => 'another table title 2',
]);
Can I use foreach inside it, for options?
If my question is not clear, ask me what you want to know more.
You can use ArrayHelper for this. Assuming $array looks like this:
[
['id' => 1, 'title' => 'aaa'],
['id' => 2, 'title' => 'bbb'],
// ...
]
You can map it to
[
1 => 'aaa',
2 => 'bbb',
// ...
]
like this:
$form->field($model_add, 'link_type')->radioList(
\yii\helpers\ArrayHelper::map($array, 'id', 'title')
);
It also same like Bizley answer,little clear
<?= $form->field($model, 'fieldName')->radioList(
ArrayHelper::map(TableName::find()->all(), 'id', 'name'),
['prompt' => 'Please Select']);?>

Datatables : Make a parallel request in another table using ServerSide

EDIT : I found the solution by replacing the SSP class by a customized SSP class I've found here : https://github.com/emran/ssp
I don't know if it's an understandable title, but here is my problem :
I have a DB-table (called projects) that needs to be inserted in a datatable. I've no problem to make a call using ServerSide and get results in the datatable.
But, for each project (each row), there is a project creator (column creator_id in the projects DB-table). What I need to do is to make a request to the creators DB-table in order to get the firstname/lastname of the creator, each time I get a row from the projects DB-table. Is that make sense?
Here is the code I use :
$table = 'projects';
$primaryKey = 'project_id';
$columns = array(
array(
'db' => 'project_id',
'dt' => 'DT_RowId',
'formatter' => function( $d, $row ) {
return $d;
}
),
array( 'db' => 'creator_id',
'dt' => 'creator',
'formatter' => function( $d, $row ) {
// Here I need to make a call to the creators DB-table and return the $creator_name value
return $creator_name;
}
)
);
// SQL server connection information
$sql_details = array(
'user' => '',
'pass' => '',
'db' => '',
'host' => ''
);
require(BASE_DIR.'/lib/dataTables/ssp.class.php');
$result = SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns);
You can use formatter property to make a separate SQL query but it will affect performance greatly by increasing script response time.
Instead you can use the following trick when using ssp.class.php with sub-queries instead of table name to use GROUP BY, JOIN, etc.
<?php
$table = <<<EOT
(
SELECT projects.project_id, creators.creator_id, creators.creator_name
FROM projects
LEFT JOIN creators ON projects.creator_id=creators.creator_id
) t
EOT;
$primaryKey = 'project_id';
$columns = array(
array(
'db' => 'project_id',
'dt' => 'DT_RowId'
),
array(
'db' => 'creator_id',
'dt' => 'creator'
),
array(
'db' => 'creator_name',
'dt' => 'creator_name'
)
);
// SQL server connection information
$sql_details = array(
'user' => '',
'pass' => '',
'db' => '',
'host' => ''
);
require(BASE_DIR.'/lib/dataTables/ssp.class.php');
$result = SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns);
echo json_encode($result);
To use that trick, you also need to edit ssp.class.php and replace all instances of FROM `$table` with FROM $table to remove backticks.
Alternatively, there is github.com/emran/ssp repository for library that extends ssp.class.php allowing GROUP BY, JOIN, aliases.
LINKS
See jQuery DataTables: Using WHERE, JOIN and GROUP BY with ssp.class.php for more information.

Make Select Options Static to Dynamic

Select's Option Values are static & i want it dynamic
Right now is static. as per below line
<?echo $this->Form->input('intaddressid',
array(
'options' =>
array('add1static,add1static' => 'add1static,add1static',
'addres2static,add2stattic'=>'addres2static,add2stattic'),
'label'=>false,
'empty' => '(Select hotel and time)',
'class' => 'form-control border_none'
)
);
?>
My static field output
https://www.dropbox.com/s/6133d4e9aorpo33/Selection_047.png?dl=0
And if i set for each then my dynamic
https://www.dropbox.com/s/v3hfhfaubkfr62m/Selection_048.png?dl=0
But i want it only in 1 field all value so help on it
I used for each times as time and my table value generated but now i want this value in above my static code. value => add1,add2 = add1,add2
$times['Time']['varaddress1']
$times['Time']['varaddress2']
my updated code is ->
$arr1=array();
$arr2=array();
$arr1 = $this->Time->find('list', array(
'fields' => array('varaddress1'),'order'=> array('Time.varaddress1')
));
$arr2 = $this->Time->find('list', array(
'fields' => array('varaddress2'),'order'=> array('Time.varaddress2')
));
$finalArr=array_merge ($arr1,$arr2);
$this->set('time',$finalArr);
and in ctp i used
'options' => $time
In ctp
<?php
echo $this->Form->input('intaddressid', array(
'options' => $courseCategoriesNames,
'empty' => '(choose one)',
'label' => false
));
?>
UPDATED solution
In controller:
NEW
$arr1=array();
$arr2=array();
$arr1= $this->Course->CourseCategory->find('list',
array('fields'=> array('Time.varaddress1'),
'order'=> array('Time.varaddress1') )
);
$arr2= $this->Course->CourseCategory->find('list',
array('fields'=> array('Time.varaddress1'),
'order'=> array('Time.varaddress2') )
);
$finalArr=array_merge ($arr1,$arr2);
$this->set('courseCategoriesNames',$finalArr);
FINAL ans
//INSIDE model Your Time->
public $virtualFields = array('name_price' => 'concat(Time.varaddress1, "-", Time.varaddress2)');
////INSIDE model
$products=$this->Product->find('list',array('fields'=> $this->Time->virtualFields['name_price'] )));
$this->set('products',compact($products));