Yii inherit attributeLabels - yii

With Yii php framework, I use inheritance.
In my AbstractModel, I have this method:
public function attributeLabels()
{
return array(
'0'=>Yii::t('default','No'),
'1'=>Yii::t('default','Yes'),
);
}
In my object who extends AbstractModel, I have this method:
public function attributeLabels()
{
return array(
'username' => Yii::t('user', 'email'),
);
}
In a view file, I use:
<?php echo CHtml::activeLabel($model, $model->property);?>
But I never show 'No' or 'Yes' from asbtractModel. If I put all in my model it works. But I want to use inheritance.
How can I concat parent attributeLabels with current model attributeLabels?

Simply merge the return value of the parent method in MyObject (model class):
public function attributeLabels() {
return array_merge(
parent::attributeLabels(),
array(
'username' => Yii::t('user', 'email'),
)
);
}
You may also use CMap::mergeArray().

Related

Can't get id from a foreign key

can i know where is my fault
Error
insert into `images` (`product_id`, `image`, `updated_at`, `created_at`) values (?, 1656838354.png, 2022-07-03 08:52:34, 2022-07-03 08:52:34)
My Models
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
'image' , 'product_id'
];
public function product()
{
return $this->belongsTo('App\Product' , 'product_id');
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'title',
'description',
'image',
'detail',
'price',
'quantity'
];
public function image()
{
return $this->hasMany('App\Image');
}
}
My Controller
public function store(Request $request)
{
$request->validate([
'image'=>'required|mimes:jpg,png,jpeg|max:4096',
]);
$newImgName = time() . '.' . $request->image->extension();
$request->image->move(public_path('multiple_images'), $newImgName);
$image = Image::create([
'product_id' => $request->id,
'image' => $newImgName,
]);
return redirect()->route('products.index')
->with('msg','Record has been inserted successfully');

notification system in Laravel 8

I am working on a laravel app where i have a user(organizer) who post an event ,and other users can comment on this event .
I am trying to make notifications system in laravel 8 between the organizer and the users when commenting on these event !
but i get this error (Call to a member function notify() on null).
This is my class :
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NewCommentPosted extends Notification
{
use Queueable;
protected $user;
protected $event;
public function __construct($user, $event)
{
$this->user = $user;
$this->event = $event;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'user' => $this->user->name,
'eventTitle' => $this->event->title,
'eventId' => $this->event->id
];
}
This is storefunction() in my controller :
namespace App\Http\Controllers;
use App\Models\Event;
use App\Models\Comment;
use App\Notifications\NewCommentPosted;
use Illuminate\Http\Request;
class CommentController extends Controller
{
public function store(Event $event)
{
request()->validate([
'content' => 'required|min:5'
]);
$comment = new Comment();
$comment->content = request('content');
$comment->user_id = auth()->user()->id;
$event->comments()->save($comment);
$event->user->notify(new NewCommentPosted(auth()->user(), $event));
return redirect()->route('events.show', [$event->id, $event->title]);
}
Any help please !!?

How to show content for the users using CGridView?

I have a page with the list of categories on my site and I want to show them using Cgridview as right now they displayed with CListView. I'm using Yii 1.1. I see that CGridView used only if you want to manage content but is it possible to use it if you want to show it, on the index pages?
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'title',
'status',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
You can used this code for your cgridview
Categories Model
File Path : protected/model/categories.php
Categories.php
<?php
/**
* This is the model class for table "categories".
*
* The followings are the available columns in table 'categories':
* #property integer $id
* #property string $title
* #property string $status
*/
class Categories extends CActiveRecord
{
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'area';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, status', 'required'),
array('status', 'numerical', 'integerOnly'=>true),
array('title', 'length', 'max'=>255),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, title, status', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'title' => 'Title',
'status' => 'Status'
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* #return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('title',$this->title,true);
$criteria->compare('status',$this->status);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* #param string $className active record class name.
* #return Area the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
Categories Controller
File Path : protected/model/CategoriesController.php
CategoriesController.php
<?php
class CategoriesController extends Controller
{
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
* #access Public
*/
public function accessRules()
{
return array(
array('allow',
'actions' => array('index'),
'users' => array('*'),
),
array('deny',
'users' => array('*'),
),
);
}
public function actionIndex()
{
$model = new Categories();
$model->unsetAttributes();
if(isset($_REQUEST['Categories']))
$model->attributes = $_REQUEST['Categories'];
$this->render('index',array('model'=>$model));
}
}
Categories View File
File Path : protected/view/index.php
index.php
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'title',
'status',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
you can add your design in index.php file.
refere this link for design

Yii2 REST create with fields()

Let's say that I had the following API set up:
Controller:
<?php
namespace app\modules\v1\controllers;
use yii;
class ResourceController extends \yii\rest\ActiveController
{
public $modelClass = 'app\modules\v1\models\Resource';
}
Model:
use yii;
class Resource extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'ResourceTable';
}
public function fields()
{
return [
'id' => 'ResourceID',
'title' => 'ResourceTitle',
];
}
}
where my table only has the two columns, ResourceID and Title.
When I try a GET request on the API, it works fine and returns the list of resources (or single resource in the case of resource/{id}) with the aliased field names. But when I try to POST to create a resource, I want to use the aliased field names (e.g. title instead of ResourceTitle). The problem is that the default CreateAction supplied by Yii does $model->load(), which looks for the field names in the table. If I use the aliased names then it returns an error. If I use the table field names, it works fine.
So my question is, is there a way to expose resource attributes to the end user where the field names (using the fields() function) are the same for reading and creating? If possible, I'd like to avoid writing my own CreateAction.
It's necessary to add rules for new virtual properties, if you want to $model-load() save parameters to them
class OrganizationBranch extends BaseOrganization{
public function rules()
{
return array_replace_recursive(parent::rules(),
[
[['organizationId', 'cityId'], 'safe'],
]);
}
public function fields() {
return ['id',
'cityId' => 'city_id',
'organizationId' => 'organization_id',
'address',
'phoneNumbers' => 'phone_numbers',
'schedule',
'latitude',
'longitude',
];
}
public function extraFields() {
return ['branchType', 'city'];
}
public function getOrganizationId() {
return $this->organization_id;
}
public function setOrganizationId($val) {
$this->organization_id = $val;
}
public function getCityId() {
return $this->city_id;
}
public function setCityId($val) {
$this->city_id = $val;
}
}
You can create getters/setters for alias.
public function getTitle(){ return $this->ResourceTitle; }
public function setTitle($val){ $this->ResourceTitle = $val ; }

cakephp override construct in child controller

I'm wondering if it is possible to inherit/override constructors in child controllers in cakephp.
In my AppController.php
I have it like this:
public function __construct( $request = null, $response = null ) {
parent::__construct( $request, $response );
$this->email = new CakeEmail();
$this->_constants = array();
$this->_constants['some_var'] = $this->Model->find( 'list', array(
'fields' => array( 'Model.name', 'Model.id' )
) );
}
and in my child controller SomeController.php, it inherits the parent constructor
public function __construct( $request = null, $response = null ) {
parent::__construct( $request, $response );
}
and when I tried to access $this->email and $this->_constants['some_var'] they both are null. But as soon as I put the code directly in SomeController.php instead of inheriting, it worked.
Did I do something wrong or this is simply not approachable for cake?
Also I tried the same with function beforeFilter(), same thing happened.
But it makes sense that each controller to have its own beforeFilter().
I wouldn't even try overriding the _construct' function of the appController. That's what thebeforeFilter,beforeRender` methods are for. It looks like you are just trying to pass vars to each controller from the appController. You can do that like so...
class AppController extends Controller {
var $_constants = array();
public function beforeFilter(){
$this->_constants[] = array('this', 'that', 'the other');
}
}
and in your model's controller you can access the variable like so...
class UsersController extends AppController {
public function add(){
pr($this->_constants);
}
}
It's a different story if you are trying to send the variables to the view (slightly). Just use the set method
class AppController extends Controller {
public function beforeFilter(){
$this->set('_constants', array('this', 'that', 'the other'));
}
}
and in any view you can just call the _constants variable with pr($_constants);. Because it is in the appController it should be available on every view.