I have the :
class MyClass extends \yii\db\ActiveRecord
public static $myrequested = ['Value1', 'Value2', 'Value3'];
How access value propertie os the myrequested on the gridview ?
[
'attribute' => 'requested_mounth',
'enableSorting' => true,
'value' => ?????
'filter' => Resourcerequest::$myrequested ,
],
if left blank it only returns the position of the array, and I need the value.
(the filter option work fine).
EDIT 1
Example of the array:
myrequested [
0 => 'value1',
1 => 'value2',
2 => 'value3',
]
Add method getRequestedMounth() at class Resourcerequest
public function getRequestedMounthValue()
{
if ($this->requested_mounth === null) {
return null;
}
return self::$myrequested[$this->requested_mounth];
}
Then
[
'attribute' => 'requested_mounth',
'enableSorting' => true,
'value' => function($data) {
return $data->getRequestedMounthValue(); // OR use magic property $data->requestedMounthValue;
},
'filter' => Resourcerequest::$myrequested ,
],
In one of my projects I have used the code below:
['attribute' => 'final_cost',
'format' => 'raw',
'value' => function ($data) use ($staticArray)
{
return $staticArray[$data->id];
},
],
Related
in my view I'm trying to add 'value' function, which shows the field if the id = 0, otherwise it doesn't show it. I'm trying to do it like so:
echo $form->field($model, 'test', [
'options' => [
'class' => $twoColumns . ' required',
'value' => function ($model) {
return $model->testvar == 0 ? 'Test' : null;
}
]
])
I've added function into 'value', but somehow it doesn't work. Could someone explain me why?
I'm getting htmlspecialchars error
Closure here is not supported and there is no reason to use it anyway.
You only need something like:
$model->interest = null;
if ($model->is_interest_variable == 0) {
$model->interest = 'Test';
}
echo $form->field($model, 'interest', [
'addon' => [
'append' => [
'content' => '%',
],
],
'options' => [
'class' => $twoColumns . ' required',
]
])->textInput([
'placeholder' => '0.0000',
'class' => 'form-control amount-4'
]);
I'm Using Kartik DateTimePicker Extension
<?= $form->field($model, 'Created')->widget(DateTimePicker::classname(),[
'model' => $model,
'attribute' => 'Created',
'name' => 'Created',
'options' => ['placeholder' => 'Select Created'],
'pluginOptions' => [
'format' => 'dd-mm-yyyy hh:ii:ss',
'todayHighlight' => true
]
])
?>
User fill the Create Date the format is
d-m-Y H:i:s (like 24-09-2015 11:21:10)
But when record save to database then Create Date Format change to
Y-m-d H:i:s (like 2015-09-24 11:21:10)
How can I change the date format on save/update of record
Need to just add this code before save/update model in controller.
like,
// ICU format
$model->Created = Yii::$app->formatter->asDate($_POST['modelName']['Created'], 'yyyy-MM-dd HH:mm:ss'); // 2014-10-06 15:22:34
OR
// PHP date()-format
$model->Created = Yii::$app->formatter->asDate($_POST['modelName']['Created'], 'php:Y-m-d H:i:s'); // 2014-10-06 15:22:34
For more information refer this link
Finally I found the answer using AttributeBehavior.
In my model class I've write the behaviors code:
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
// update 1 attribute 'created' OR multiple attribute ['created','updated']
ActiveRecord::EVENT_BEFORE_INSERT => ['created','updated'],
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated',
],
'value' => function ($event) {
return date('Y-m-d H:i:s', strtotime($this->Created));
},
],
];
}
My Model Class
namespace frontend\models;
use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\AttributeBehavior;
/**
* This is the model class for table "product".
*
* #property integer $id
* #property integer $product_id
* #property string $product_name
* #property string $created
* #property string $updated
*/
class Product extends ActiveRecord
{
public $csv_file;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'product';
}
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created','updated'], // update 1 attribute 'created' OR multiple attribute ['created','updated']
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated', // update 1 attribute 'created' OR multiple attribute ['created','updated']
],
'value' => function ($event) {
return date('Y-m-d H:i:s', strtotime($this->LastUpdated));
},
],
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id', 'product_id', 'product_name', created, updated], 'required'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'product_id' => 'Product ID',
'product_name' => 'Product Name',
'created' => 'Created',
'updated' => 'Updated',
];
}
}
If input format is d/m/Y then you need to replace the "/" by "-"
like: input date(created): 10/09/2015
date('Y-m-d H:i:s', strtotime(str_replace("/","-",$this->created)));
use in active form
'clientOptions' => ['alias' => 'dd-mm-yyyy'],
use in active form
echo MaskedInput::widget([
'name' => 'input-31',
'clientOptions' => ['alias' => 'date']]);
use class
Class yii\widgets\MaskedInput
Example
<?= $form->field($model, 'date_of_birth')->widget(\yii\widgets\MaskedInput::className(), [
'name' => 'input-31',
'clientOptions' => ['alias' => 'dd-mm-yyyy'], ]) ?>
I have simple code,
in behavior:
public function behaviors() {
return [
[ 'class' => \yii\behaviors\TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
],
// if you're using datetime instead of UNIX timestamp:
'value' => new Expression('NOW()'),
]
];
}
for rules:
public function behaviors() {
return [
[ 'class' => \yii\behaviors\TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
],
// if you're using datetime instead of UNIX timestamp:
'value' => new Expression('NOW()'),
]
];
}
public function behaviors() {
return [
[
'class' => BlameableBehavior::className(),
],
[
'class' => TimestampBehavior::className(),
'value' => date('Y-m-d H:i:s')
],
];
}
use kartik\widgets\Select2;
echo Select2::widget([
'model' => $myModel,
'name' => 'company[]',
'options' => [
'placeholder' => 'Select a company ...',
'multiple' => true,
],
'value' => 6, //doesn't work
'initValueText' => '6', //doesn't work
'pluginOptions' => [
'allowClear' => true,
'ajax' => [
'url' => Url::to(['/company/default/get-company-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {return {results:data.results}; }'),
],
'initSelection' => new JsExpression('function(element, callback) {
$(element).val(6); //doen't work
callback({"text" : "Vendor B", "id" : 6}); // it does only set text, not id
}'),
],
]);
... many many select2 form below too, that named 'company[]'
After form submit, if user come back to this page, I want to set what user selected as default.
How can I set default value for Select2 widget?
When you update the model, it will automatically have the last selected value.
$myModel = new \app\models\myModel;
$myModel->attributes = \Yii::$app->request->post('myModel');
I related two models following the official documentation of CakePHP 3 and can not return the values of one of them in view (Template).
The Code:
Work - Entity
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Work extends Entity
{
protected $_accessible = [
'project' => true,
'client' => true,
'filter' => true,
'tech_1' => true,
'tech_2' => true,
'tech_3' => true,
'tech_4' => true,
'job' => true,
'status' => true,
'link' => true,
];
}
WorksImage - Entity
namespace App\Model\Entity;
use Cake\ORM\Entity;
class WorksImage extends Entity
{
protected $_accessible = [
'photo' => true,
'photo_dir' => true,
'work_id' => true,
'work' => true,
];
}
PagesController - Controller:
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
class PagesController extends AppController
{
public function portfolio()
{
$this->loadModel('Works');
$this->loadModel('WorksImages');
$works = $this->Works->find('all',['contain' => ['WorksImages'],'limit' => 10, 'order' => ['Works.created' => 'DESC']]);
$this->set(compact('works'));
}
}
WorksTable - Table:
namespace App\Model\Table;
use App\Model\Entity\Work;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class WorksTable extends Table
{
public function initialize(array $config)
{
$this->table('works');
$this->displayField('project');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasOne('WorksImages', [
'foreignKey' => 'work_id'
]);
}
WorksImagesTable - Table
namespace App\Model\Table;
use App\Model\Entity\WorksImage;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class WorksImagesTable extends Table
{
public function initialize(array $config)
{
$this->table('works_images');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Works', [
'foreignKey' => 'work_id',
'joinType' => 'INNER'
]);
}
Portfolio - View (Template)
<div class="container">
<div class="span12">
<h1>Portfólio</h1>
<div>
<?php foreach ($works as $work): ?>
<div>
<p><?= 'Conteúdo da tabela Works = ' . $work->project ?></p>
<p><?= 'Conteúdo da tabela WorksImages = ' . $work->work_id ?></p>
</div>
<?php endforeach ?>
</div>
</div>
</div>
I can not return any value from the WorksImagesTable model. During Debugging, I realize that the tables are related, in addition, cake returns no error in the view.
I can not understand what is wrong.
I thank in advance any help.
Thanks.
In the foreach loop (debug($work->works_image)) returned something like this:
object(App\Model\Entity\WorksImage) {
'new' => false,
'accessible' => [
'photo' => true,
'photo_dir' => true,
'work_id' => true,
'work' => true
],
'properties' => [
'id' => (int) 1,
'photo' => 'arteviva.jpg',
'photo_dir' => 'a4cd522c-b7b9-437a-99fc-0eb15827944f',
'work_id' => (int) 1,
'created' => object(Cake\I18n\Time) {
'time' => '2015-05-08T20:25:07+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'modified' => null
],
'dirty' => [],
'original' => [],
'virtual' => [],
'errors' => [],
'repository' => 'WorksImages'
}
I have a lot of models using created_time. And I want all of the GridViews to show the models sorted by created_time DESC.
Right now I write something like this
$dataProvider = new \yii\data\ActiveDataProvider([
'query' => MyModel::find(),
'sort' => [
'defaultOrder' => [
'created_time' => SORT_DESC
]
],
]);
Instead of writing all of sort configuration I tried ways below but nothing works.
Using container
\Yii::$container->set(\yii\data\ActiveDataProvider::class,
[
'sort' => [
'defaultOrder' => [
'created_time' => SORT_DESC
]
]
]);
Overriding the sort in extended class.
class ActiveDataProvider extends \yii\data\ActiveDataProvider {
public $sort = [
'defaultOrder' => [
'created_time' => SORT_DESC
]
];
}
Overriding before init() in the extended class works, but it won't work if the instantiation tries to override again.
class ActiveDataProvider extends \yii\data\ActiveDataProvider {
public function init() {
$this->sort = [
'defaultOrder' => [
'created_time' => SORT_DESC
]
];
parent::init();
}
}
//but this won't work if I want to use the ascending
$dataProvider = new \app\components\data\ActiveDataProvider([
'query' => MyModel::find(),
'sort' => [
'defaultOrder' => [
'created_time' => SORT_ASC
]
],
]);
To do this for a single GridView, you can add 'defaultOrder' => ['created_time' => SORT_DESC] to the array that is accepted by setSort():
$dataProvider->setSort([
'attributes' => [
'id',
...
],
'defaultOrder' => ['created_time' => SORT_DESC]
]);
You should do this for yii\data\Sort and not for yii\data\ActiveDataProvider. See the documentation to $sort property.
1) With container:
use Yii;
...
Yii::$container->set(\yii\data\Sort::className(),
'defaultOrder' => [
'created_time' => SORT_DESC,
],
]);
2) Overriding class:
class Sort extends yii\data\Sort
{
public $defaultOrder' = [
'created_time' => SORT_DESC,
];
}