Yii and database row in dropdown - yii

I have two model: test1 , test2
And an action in test1 :
public function active_widgets_list()
{
$widgets = SiteWidget::model()->find('status=:status', array(':status' => '1'));
return $widgets;
}
And I will show test1.tbl_1 rows as dropdown list in test2's view:
$list=CHtml::listData(SiteWidget::model()->active_widgets_list(), 'id', 'title');
echo $form->dropDownList($model,'widget_id', $list, array('empty' => 'Select Please'));
but down't work. i have just an empty dropdown.

You should be using findAll instead of find, since find returns only a single active record with the specified condition.
$widgets = SiteWidget::model()->findAll('status=:status', array(':status' => '1'));

If you use Gii tools, You don't need any thing for saving. It generate all the codes you need it. It is so easy to make a huge of models, controllers, views and CRUD.
http://www.yiiframework.com/doc/guide/1.1/en/topics.gii

Related

yii2 name field attribute using variable

I'm trying to create in an activeform a series of controls using a loop for not being to declare the various fields of the model in order to have a generic template to which I pass only the name of the table and it creates the edit form.
So that if I pass the table A and it has 3 fields it creates three fields, the b has 5 fields it creates 5 fields etc etc.
$tfields= Array ( [0] => id [1] => brand_id [2] => group_id)
and i create this code
foreach($tfields as $key => $value) {
if (strlen($value)>0){
echo $form->field($model, $value)->textInput();
}
}
but when i run the code i get this error
Calling unknown method: yii\data\ActiveDataProvider::isAttributeRequired()
any ideas?
tks a lot!
the problem was tha i use an ActiveDataProvider as model, using instead and DynamicModel
in the controller
$model2= new \yii\base\DynamicModel([
]);
in the form
foreach(explode(',',$fields) as $item){
if (strlen($item)<>0){ //to avoid empty
echo $form->field($model2, $item)->textInput();
}
}

Collecting a referenced app's values

I am trying to cleanup and optimize my come I am running on podio's API. What I am currently doing is using the filter query to return a collection from one app. I then loop over that collection. On each item I use Podio get_field_value to return the value(s) of a field in a referenced app. This creates a lot of API calls. I would like to retrieve everything in one API call Here is a simple version of my current code:
$collection = PodioItem::filter(WHSE_ID, array(
"filters" => array(
WHSE_EQUP_STATUS => array(2),
),
"sort_by" => WHSE_LOAD_IN,
"sort_desc" => false,
"limit" => 50
)
);
foreach ($collection as $item) {
// Table-A ID
$whId = $item->item_id;
// Referenced App Item(s)
$nucId = $item->fields[0]->values[0]->item_id;
// Get Referenced App Item Field
$app_b_value = PodioItem::get_field_value($nucId, NUC_LOAD_OUT);
echo $app_b_value;
}
Is there a more efficient way of doing this? I am thinking inline with the way you would use JOIN in a mysql query.
Thank you for any help you can provide!
if you are trying to get value from each item from filtered collection, you don't need to make podio calls each time.
Podio filter call will give you item with values. you just have to get value from each item.
like following
foreach ($podioFilterData['items'] as $itemData) {
$itemFields = $itemData['fields'];
foreach ($itemFields as $field) {
$value = $field['values'][0];
}
}

Adding a condition to every query in a model

I have a system where all tables in the MySQL database are populated with external data (synchronized with another system every 5 minutes). All tables have a column DELFLAG which is used to mark disabled entries.
So I have about 15 AR models in Yii that are linked to those tables. Whenever I make a query, I need to add something like $criteria->addCondition('DELFLAG=0'). This gets ugly if there are multiple tables present in the query, as every one of them has the flag. Also, there's a potential for error if I forget one of those conditions.
Here's how I do it now:
public function search($showtype = NULL) {
$criteria=new CDbCriteria;
if (isset($showtype)) {
$criteria->with = array(
'TSSSHOW',
'TSSSHOW.TSSSHOWTYPEITEM',
'TSSSHOW.TSSSHOWTYPEITEM.TSSSHOWTYPE'
);
$criteria->compare('TSSSHOWTYPEITEM.TSSSHOWTYPEID', $showtype);
$criteria->addCondition('TSSSHOW.DELFLAG=0');
$criteria->addCondition('TSSSHOWTYPEITEM.DELFLAG=0');
}
$exp = new CDbExpression("`TSSEVENT_START_DATETIME` > NOW()");
$criteria->addCondition($exp);
$criteria->addCondition('t.DELFLAG=0');
$criteria->together = true;
$criteria->order = 't.TSSEVENT_START_DATETIME ASC';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination' => array(
'pageSize' => 15,
),
));
}
Is there a convenient way to include this condition into every query that includes these tables? Perhaps a special class which my models shall descend from (as opposed to the default CActiveRecord)?
I'd suggest declaring named scope for these models:
public function scopes()
{
return array(
'disabledEntry'=>array(
'condition'=>'DELFLAG=1',
),
);
}
Using the named scope: Model::model()->disabledEntry()->findAll();
You can provide scope when relaring to model in the with() statement as well: ModelA::model()->with('model:disabledEntry')->findAll();
But if you have to set this condition each time, you may set defaultScope:
public function defaultScope()
{
return array(
'condition' => 'DELFLAG=0',
);
}
Thus, this model by default would have this condition.
Update: Since you have the identically named columns in several models, YII can have some column name ambiguity troubles while building sql-query. If it is the case, use alias in scope declaration or use the following statement to set current table alias explicitly while declaring scope 'condition' => $this->getTableAlias(false, false) . '.DELFLAG=0',
You can create Your own class e.g. CustomActiveRecord extends CActiveRecord
then You should override findAll, findByPk methods with your criteria..
Other solution is to run this query 'DELETE FROM table_name WHERE DELFLAG=1' after every import..

How can I display a single record in 2 rows by using Yii CGridView?

I am using CGridView in Yii, how can I display a single record in 2 lines?
Basically I want to show a record details in 1st row of table and on other row I want to display its summary, I tried it with div and css but can't get proper results, is anyone there who can help me in this case?
I am using like this:
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'bidding-grid',
'itemsCssClass' => 'data-default',
'dataProvider'=>$model,
'summaryText' => '',
'columns'=>array(
'people_detail_for_bid.Person' => array(
'type'=>'raw',
'name'=>'people_detail_for_bid.Person',
'value'=>'Yii::app()->Controller->createUserNameLink($data->people_detail_for_bid->PeopleFirstName." ".$data->people_detail_for_bid->PeopleLastName, $data->people_detail_for_bid->PeopleId).
"<br><span class=decriptionText>".$data->people_detail_for_bid->PeopleDesignation."</span>".
"<br><span class=decriptionText>".$data->people_detail_for_bid->PeopleEmail."</span>"',
'htmlOptions'=>array('width'=>200),
),
'timeAgo' => array(
'type'=>'raw',
'name'=>'timeAgo',
'value'=>'"<span class=decriptionText>".Yii::app()->Controller->_ago($data->PBPostedOn)."</sapn>"',
'htmlOptions'=>array('width'=>150),
),
),
));
?>
I think the best and cleanest way to accomplish this is to create a new extension and extend it to CGridView, override the renderTableRow function like this:
/**
* Renders a table body row.
* #param integer $row the row number (zero-based).
*/
public function renderTableRow($row)
{
if($this->rowCssClassExpression!==null)
{
$data=$this->dataProvider->data[$row];
echo '<tr class="'.$this->evaluateExpression($this->rowCssClassExpression,array('row'=>$row,'data'=>$data)).'">';
}
else if(is_array($this->rowCssClass) && ($n=count($this->rowCssClass))>0)
echo '<tr class="'.$this->rowCssClass[$row%$n].'">';
else
echo '<tr>';
$colCtr = 0;
foreach($this->columns as $column){
$column->renderDataCell($row);
$colCtr++;
}
echo "</tr>\n";
echo "<tr><td colspan=\"$colCtr\">This is the summary row. </td></tr>";
}
You can customize what you are rendering in the columns, so if you want to show two different fields of your table in the same row, you have to create a function in your model:
public function customColumn()
{
return $this->PeopleDesignation.'<br/>'.$this->PeopleEmail;
}
And then assign the method to the value of your column:
array(
'type'=>'html',
'value'=>'$data->customColumn()'
),
Cheers, Pablo.
After too much search .. and I tried with different ways now finally got a solution for this .. that solution is basically a kind of 2nd way to do anything not actual way .. but it works to me ..
.....
.....
'timeAgo' => array(
'type'=>'raw',
'name'=>'timeAgo',
'value'=>'"<span class=decriptionText>".Yii::app()->Controller->_ago($data->PBPostedOn)."</sapn></td></tr><tr><td colspan=\"6\"><span class=decriptionText>".$data->PBSummary."</span>"',
'htmlOptions'=>array('width'=>150),
),
.....
.....
added some table tags on last column to close row and added another one.
hope it works for all ..
thanks ..
Sounds like 2 interleaved CGridViews. So you might try that, but I can't imagine it will work out well:
Overlay one CGridView over the other, with enough transparent space in each row for the other to display it's row, and ...
a. one `CGridView` table offset vertically by half a row height, *OR*
b. one table's row's text vertically top-aligned & the other bottom-aligned
But somehow I doubt that's a CGridView capability ;) And keeping the two in sync so they pagenate and scroll together would be darn near impossible. Sounds like you need to enhance CGridView or derive a new widget from CGridView. I wonder if JQuery has something to do this?

multiple checkbox valiadation for any one in YII frame work for this example

Hi can you please tell how can i validate the multiple checkbox any one is checked in yii framework
array('accept', 'required', 'requiredValue' => 1, 'message' => 'You should select alteast one')
As these value are usually sent as arrays, I wrote an array validator for these cases once: https://github.com/schmunk42/p3extensions/blob/master/validators/P3ArrayValidator.php
Usage example:
array('accept',
'ext.validators.P3ArrayValidator',
'min'=>1,
'allowEmpty'=>false,
'message' => 'You should select at least one'
),
sorry for the late reply.
But, I found a solution without installing any extension.
Take a hidden field with the same name [Checkboxes list field].
<?php echo $form->hiddenField($model,'categories');?>
Display a list of categories with name different from our field name (multiple checkboxes).
But, remember the 'class', and play with the class to save the values.
<?php
echo CHtml::checkBoxList(
'group',
//you can pass the array here which you want to be pre checked
explode(',', trim($model->attributes['categories'], ',')),
CHtml::listData(Category::model()->findAll(),'id','name'),
array('separator'=>'', 'template'=>'<tr><td style="width:5%;">{input}</td><td>{label}</td></tr>', 'class' => 'group')
);
?>
This way validation should work also, you get category ids as comma separated e.g. [,1,2,6,]
<script>
$(function(){
$(".group").click(function(){
var str = $('.group:checked').map(function() {
return this.value;
}).get().join();
var groupCats = (str.length > 0) ? ','+str+',' : '';
$('#ModelNAME_field').val(groupCats);
// Get the 'ModelNAME_field' by viewing source of HTML of hidden field.
});
});
</script>