I am trying to create a table using database migrations, here is my code
public function change()
{
$table = $this->table('tags');
$table->addColumn('title', 'string', ['default' => null,'limit' => 255,'null' => false,]);
$table->addColumn('created', 'datetime', ['default' => null,'null' => false,]);
$table->addColumn('modified', 'datetime', ['default' => null,'null' => false,]);
$table->addUniqueKey('title'); // Giving error **Fatal error: Call to undefined method Phinx\Db\Table::addUniqueKey()**
$table->create();
}
I want to set title column unique, but when I try to do it then it gives the error:
Fatal error: Call to undefined method Phinx\Db\Table::addUniqueKey()
Add primary key refer http://book.cakephp.org/3.0/en/orm/schema-system.html
public function change() {
$t = new Table('posts');
$t->addColumn('id', 'integer')
->addColumn('author_id', 'integer')
->addColumn('title', 'string')
->addColumn('slug', 'string');
// Add a primary key.
$t->addConstraint('primary', [
'type' => 'primary',
'columns' => ['id']
]);
// Add a unique key
$t->addConstraint('slug_idx', [
'columns' => ['slug'],
'type' => 'unique',
]);
// Add index
$t->addIndex('slug_title', [
'columns' => ['slug', 'title'],
'type' => 'index'
]);
// Add a foreign key
$t->addConstraint('author_id_idx', [
'columns' => ['author_id'],
'type' => 'foreign',
'references' => ['authors', 'id'],
'update' => 'cascade',
'delete' => 'cascade'
]);
}
This should be the solution
$table->addColumn('title', 'string',
[
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addIndex(['title'], ['unique' => true]); // < this is what you looking for
I am surprised CakePHP documentation doesn't mention it properly. After long searching, I found the solution in this article
Related
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)){
//
}
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;
},
],
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.
I want to add a custom rule to PhpManager RBAC in Yii 2.0.
Here is the custom rule (#app/rbac/OwnerRule.php):
<?php
namespace app\rbac;
use yii\rbac\Rule;
/**
* Checks if userID matches user passed via params
*/
class OwnerRule extends Rule
{
public $name = 'isOwner';
public function execute($user, $item, $params)
{
$access = false;
if(isset($params['id'])){
// My custom logic used to set $access
}
return $access;
}
}
Here is the RBAC hierarchy file (#app/data/rbac.php)
<?php
use yii\rbac\Item;
return [
'manageThing0' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'bizRule' => NULL, 'data' => NULL],
'manageThing1' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'bizRule' => NULL, 'data' => NULL],
'manageThing2' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'bizRule' => NULL, 'data' => NULL],
// AND THE ROLES
'guest' => [
'type' => Item::TYPE_ROLE,
'description' => 'Guest',
'bizRule' => NULL,
'data' => NULL
],
'user' => [
'type' => Item::TYPE_ROLE,
'description' => 'User',
'children' => [
'guest',
'manageThing0', // User can edit thing0
],
'bizRule' => 'return !Yii::$app->user->isGuest;',
'data' => NULL
],
'moderator' => [
'type' => Item::TYPE_ROLE,
'description' => 'Moderator',
'children' => [
'user', // Can manage all that user can
'manageThing1', // and also thing1
],
'bizRule' => NULL,
'data' => NULL
],
'admin' => [
'type' => Item::TYPE_ROLE,
'description' => 'Admin',
'children' => [
'moderator', // can do all the stuff that moderator can
'manageThing2', // and also manage thing2
],
'bizRule' => NULL,
'data' => NULL
],
];
How do I use my custom rule in the hierarchy file?
See these links hope you will find what you are looking for,
http://www.yiiframework.com/doc-2.0/guide-security-authorization.html
http://yii2-user.dmeroff.ru/docs/custom-access-control
RBAC for basic yii2 template
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'
)