How to fetch cabin name using cabinfk_id in yii? - yii

I have two tables
ie.
1)cabins(id,cabinname,status)
where in cabins table id is a primary key[.][1]
2)tables(id,cabinfk_id,tablename,status)
here cabinfk_id is a reference key of cabins table id.
here in above form when i create new tables where in a single cabin there are many tables so as i enter three tables in mercury-cabin
here i saved it it successfully get saved but in view file of table in a list threre appers table name cabin name and status
My Question is in cabin name column i want cabin name as mercury instead of cabin id shown as 28 28 28 in fig 2
Model-code of tables
----------------------------start------------------------------
namespace app\models;
use Yii;
**
* This is the model class for table "tables".
*
* #property int $id
* #property string $tablename
* #property int $cabinfk_id
* #property int $status 1=active, 0=inactive
*
* #property Orders[] $orders
* #property Cabins $cabinfk
*/
class Tables extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'tables';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['tablename', 'cabinfk_id', 'status'], 'required'],
[['cabinfk_id', 'status'], 'integer'],
[['tablename'], 'string', 'max' => 40],
[['cabinfk_id'], 'exist', 'skipOnError' => true, 'targetClass' => Cabins::className(), 'targetAttribute' => ['cabinfk_id' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'tablename' => Yii::t('app', 'Tablename'),
// 'cabinfk_id' => Yii::t('app', 'Cabinfk ID'),
'cabinfk_id' => Yii::t('app', 'Cabin Name'),
'status' => Yii::t('app', 'Status'),
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getOrders()
{
return $this->hasMany(Orders::className(), ['tablefk_id' => 'id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCabinfk()
{
return $this->hasOne(Cabins::className(), ['id' => 'cabinfk_id']);
}
}
------------------------end-----------------------------

If you have a gridView you can set like this:
[
'attribute' => 'cabinfk_id',
'value' => 'cabinfk.name'
],
If you have details view:
[
'attribute' => 'cabinfk_id',
'value' => $model->cabinfk->name,
],

Related

Object of class Faker\UniqueGenerator could not be converted to string

I am using laravel 9. I am trying to generate some fake users to boost my db using factoreis and seeders.
When i try to seed my db i get this error
Object of class Faker\UniqueGenerator could not be converted to string
at D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:665
661▕ $value,
662▕ match (true) {
663▕ is_int($value) => PDO::PARAM_INT,
664▕ is_resource($value) => PDO::PARAM_LOB,
➜ 665▕ default => PDO::PARAM_STR
666▕ },
667▕ );
668▕ }
669▕ }
1 D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:665
PDOStatement::bindValue(Object(Faker\UniqueGenerator))
2 D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:540
Illuminate\Database\Connection::bindValues(Object(PDOStatement))
this my UserFactory
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'name' => fake()->name(),
'username' => fake()->unique(),
'company' => fake()->sentence(),
'position' => fake()->sentence(),
'bio' => fake()->realText($maxNbChars = 100),
'picture' => fake()->imageUrl(90, 90),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => Hash::make('password'), // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* #return static
*/
public function unverified()
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
After looking arround for a while I found that fake()->unique() does not return a string. So I tried to convert it to string but It also gives me a error saying Unknown format "toString" in Faker\Generator.php:731
[Problem solved]
I just had to edit my UserFactory username to this
'username' => fake()->unique()->text(16),

How to show belongsTomany data in a datatable

DataTables warning: table id=dataTableBuilder - Exception Message:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'phyto_product' (SQL: select count(*) as aggregate from (select '1' as row_count from phyto_product left join phyto_product on phyto_product.id = phytos.phyto_id left join phyto_product on phyto_product.id = products.product_id where phyto_product.deleted_at is null) count_row_table)
I have a belongsTomany relationship between phyto and product as follows. I'm looking for a way to display in the datatable the following
phyto_number, product_name, weight, charge
My query (PhytoProduct is a pivot table)
public function query(PhytoProduct $model)
{
return $model->newQuery()->leftjoin('phyto_product','phyto_product.id', '=','phytos.phyto_id')
->leftjoin('phyto_product','phyto_product.id', '=', 'products.product_id')
->select('phyto_product.*', 'phytos.phyto_number','products.product_name');
}
My datatable
protected function getColumns()
{
return [
[ 'data' => 'phyto_number', 'name' => 'phytos.phyto_number', 'title' => 'Phyto Number' ],
[ 'data' => 'product_name', 'name' => 'products.product_name', 'title' => 'Product Name' ],
[ 'data' => 'weight', 'name' => 'phyto_product.weight', 'title' => 'Weight' ],
[ 'data' => 'charge', 'name' => 'phyto_product.charge', 'title' => 'charge' ],
];
}
Phyto Model
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class Phyto
* #package App\Models
* #version December 27, 2019, 1:08 am UTC
*
* #property string phyto_number
* #property integer destination_id
* #property string indate
*/
class Phyto extends Model
{
use SoftDeletes;
public $table = 'phytos';
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at';
protected $dates = ['deleted_at'];
public $fillable = [
'phyto_number',
'destination_id',
'indate'
];
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'id' => 'integer',
'phyto_number' => 'string',
'destination_id' => 'integer',
'indate' => 'date:d/m/y',
];
/**
* Validation rules
*
* #var array
*/
public static $rules = [
'phyto_number' => 'required',
'indate' => 'required'
];
public function products()
{
return $this->belongsToMany(Product::class)->withPivot(['weight','charge']);
}
public function destinations()
{
return $this->hasMany(Destination::class);
}
}
PhytoProduct Model
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class PhytoProduct
* #package App\Models
* #version December 27, 2019, 2:20 am UTC
*
* #property integer phyto_id
* #property integer product_id
* #property number weight
* #property number charge
*/
class PhytoProduct extends Model
{
use SoftDeletes;
public $table = 'phyto_product';
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at';
protected $dates = ['deleted_at'];
public $fillable = [
'phyto_id',
'product_id',
'weight',
'charge'
];
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'id' => 'integer',
'phyto_id' => 'integer',
'product_id' => 'integer',
'weight' => 'float',
'charge' => 'float'
];
/**
* Validation rules
*
* #var array
*/
public static $rules = [
'phyto_id' => 'required',
'product_id' => 'required'
];
}
Product Model
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class Product
* #package App\Models
* #version December 27, 2019, 1:07 am UTC
*
* #property string product_name
*/
class Product extends Model
{
use SoftDeletes;
public $table = 'products';
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at';
protected $dates = ['deleted_at'];
public $fillable = [
'product_name'
];
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'id' => 'integer',
'product_name' => 'string'
];
/**
* Validation rules
*
* #var array
*/
public static $rules = [
'product_name' => 'required'
];
public function phytos()
{
return $this->belongsToMany(Product::class)->withPivot(['weight','charge']);
}
}
The answer is based on this sql
SELECT phyto_product.weight,
phytos.phyto_number,
products.product_name
FROM phyto_product
LEFT JOIN phytos ON phytos.id = phyto_product.phyto_id
Left join products ON products.id = phyto_product.product_id
and then translated into this
public function query(PhytoProduct $model)
{
return $model->newQuery()->leftjoin('phytos','phytos.id', '=', 'phyto_product.phyto_id')
->leftjoin('products','products.id', '=', 'phyto_product.product_id')
->select('phyto_product.*', 'phytos.*','products.*');
}

How to override ImageFactory in Magento 2.3.3

i have my module which is overriding product in images in product list page (it is loading product images from custom attribute).
In Magento 2.2.x there was file vendor/magento/module-catalog/Block/Product/ImageBuilder.php which you can override and then use your own product image, in my case loaded from custom attribute.
class ImageBuilder extends \Magento\Catalog\Block\Product\ImageBuilder
{
public function create()
{
/** #var \Magento\Catalog\Helper\Image $helper */
$helper = $this->helperFactory->create()
->init($this->product, $this->imageId);
$template = $helper->getFrame()
? 'Magento_Catalog::product/image.phtml'
: 'Magento_Catalog::product/image_with_borders.phtml';
$imagesize = $helper->getResizedImageInfo();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($this->product->getId());
$url = $product->getData('MY_OWN_ATTRIBUTE');
if (trim($url) == '')
{
$url = $helper->getUrl();
}
$data = [
'data' => [
'template' => $template,
'image_url' => $url,
'width' => $helper->getWidth(),
'height' => $helper->getHeight(),
'label' => $helper->getLabel(),
'ratio' => $this->getRatio($helper),
'custom_attributes' => $this->getCustomAttributes(),
'resized_image_width' => !empty($imagesize[0]) ? $imagesize[0] : $helper->getWidth(),
'resized_image_height' => !empty($imagesize[1]) ? $imagesize[1] : $helper->getHeight()
],
];
return $this->imageFactory->create($data);
}
}
In Magento 2.3.3 this code was moved into vendor/magento/module-catalog/Block/Product/ImageFactory.php
Even if i copy whole file and overrride it under my module (without any changes), product list page wont load and i dont see any errors. It just look like this:
This is how look ImageFactory.php under my module:
<?php
namespace MY_COMPANY\MY_MODULE\Block\Product;
use Magento\Catalog\Block\Product\Image as ImageBlock;
use Magento\Catalog\Model\View\Asset\ImageFactory as AssetImageFactory;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Image\ParamsBuilder;
use Magento\Catalog\Model\View\Asset\PlaceholderFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\ConfigInterface;
use Magento\Catalog\Helper\Image as ImageHelper;
class ImageFactory extends \Magento\Catalog\Block\Product\ImageFactory
{
/**
* #var ConfigInterface
*/
private $presentationConfig;
/**
* #var AssetImageFactory
*/
private $viewAssetImageFactory;
/**
* #var ParamsBuilder
*/
private $imageParamsBuilder;
/**
* #var ObjectManagerInterface
*/
private $objectManager;
/**
* #var PlaceholderFactory
*/
private $viewAssetPlaceholderFactory;
/**
* #param ObjectManagerInterface $objectManager
* #param ConfigInterface $presentationConfig
* #param AssetImageFactory $viewAssetImageFactory
* #param PlaceholderFactory $viewAssetPlaceholderFactory
* #param ParamsBuilder $imageParamsBuilder
*/
public function __construct(
ObjectManagerInterface $objectManager,
ConfigInterface $presentationConfig,
AssetImageFactory $viewAssetImageFactory,
PlaceholderFactory $viewAssetPlaceholderFactory,
ParamsBuilder $imageParamsBuilder
) {
$this->objectManager = $objectManager;
$this->presentationConfig = $presentationConfig;
$this->viewAssetPlaceholderFactory = $viewAssetPlaceholderFactory;
$this->viewAssetImageFactory = $viewAssetImageFactory;
$this->imageParamsBuilder = $imageParamsBuilder;
}
public function create(Product $product, string $imageId, array $attributes = null): ImageBlock
{
$viewImageConfig = $this->presentationConfig->getViewConfig()->getMediaAttributes(
'Magento_Catalog',
ImageHelper::MEDIA_TYPE_CONFIG_NODE,
$imageId
);
$imageMiscParams = $this->imageParamsBuilder->build($viewImageConfig);
$originalFilePath = $product->getData($imageMiscParams['image_type']);
if ($originalFilePath === null || $originalFilePath === 'no_selection') {
$imageAsset = $this->viewAssetPlaceholderFactory->create(
[
'type' => $imageMiscParams['image_type']
]
);
} else {
$imageAsset = $this->viewAssetImageFactory->create(
[
'miscParams' => $imageMiscParams,
'filePath' => $originalFilePath,
]
);
}
$data = [
'data' => [
'template' => 'Magento_Catalog::product/image_with_borders.phtml',
'image_url' => $imageAsset->getUrl(),
'width' => $imageMiscParams['image_width'],
'height' => $imageMiscParams['image_height'],
'label' => $this->getLabel($product, $imageMiscParams['image_type']),
'ratio' => $this->getRatio($imageMiscParams['image_width'], $imageMiscParams['image_height']),
'custom_attributes' => $this->getStringCustomAttributes($attributes),
'class' => $this->getClass($attributes),
'product_id' => $product->getId()
],
];
return $this->objectManager->create(ImageBlock::class, $data);
}
}
Of course i have defined override in di.xml.
Question is: how can i override ImageFactory.php in my module ?
thanks
just asking: have You deleted content of generated?
like rm -rf ./generated/*
and cleared cache (especially config)
like:
bin/magento c:c
https://devdocs.magento.com/guides/v2.3/howdoi/php/php_clear-dirs.html

Yii1 - Declaration of model::validate() should be compatible with CModel::validate($attributes = NULL, $clearErrors = true)

I am getting this error when I try to run the index method inside the controller:
Declaration of OneTokenAuth::validate() should be compatible with CModel::validate($attributes = NULL, $clearErrors = true)
My controller:
<?php
/**
* Class is used for
*/
class OneTokenAuthController extends Controller
{
public function init()
{
$this->attachbehavior('restBehavior', new RestBehavior());
parent::init();
}
public function filters()
{
return ['accessControl',];
}
public function accessRules()
{
return [
[
'deny',
'actions' => [
'index',
],
'users' => ['#']
]
];
}
/**
* Entry point for validating JWT token
* If the token is valid, user will be logged in as an admin
* and redirected to the admin dashboard
*
* #param [string] $t
* #return void
*/
function actionIndex($t){
$token = CHtml::encode(strip_tags($t));
$auth = new OneTokenAuth($token);
if(!$auth->verify())
die('Token is not valid');
if(!$auth->validate())
die('Token is not valid');
$this->redirect('admin/jobs/dashboardNewest');
}
}
My model:
<?php
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Token;
use Lcobucci\JWT\ValidationData as JWTValidation;
/**
* This is the model class for table "jwt_access_log".
*
* The followings are the available columns in table 'jwt_access_log':
* #property integer $id
* #property text $token
* #property integer $token_status
* #property timespamp $created_at
*/
class OneTokenAuth extends CActiveRecord
{
const VALID = 100;
const UNVERIFIED = 200;
const NONVALID = 300;
private $_singkey;
private $_token;
private $_signer;
private $_data;
function __construct ($token){
$this->_singkey = '1234xxxx';
$this->_signer = new Sha256();
$this->_token =(new Parser())->parse((string) $token);
$this->_token->getHeaders(); // Retrieves the token header
$this->_token->getClaims(); // Retrieves the token claims
$this->_data = new JWTValidation;
$this->_data->setIssuer('http://example.com');
$this->_data->setAudience($this->_token->getClaim('iss'));
}
public function tableName()
{
return 'jwt_access_log';
}
public function rules()
{
return [
['token_status', 'numerical', 'integerOnly' => true],
['token', 'length', 'max' => 1024],
['created_at', 'safe'],
];
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'token' => 'Token',
'token_status' => 'Token Status',
'created_at' => 'Created At'
);
}
public function verify(){
if($this->_token->verify($this->_signer, $this->_singkey))
return true;
$this->makeLog(self::NONVALID);
return false;
}
public function validate(){
if($this->_token->validate($this->_data)){
$this->adminLogin();
return true;
}
$this->makeLog(self::UNVERIFIED);
return false;
}
public function makeLog($status)
{
$model = new self();
var_dump('<pre>', $model, '</pre>');die;
$model->setAttributes([
'token' => $this->_token,
'token_status' => $status,
]);
$model->save();
}
private function adminLogin()
{
$this->makeLog(self::VALID);
$login = new LoginComponent([
'email' => 'admin#admin.com',
'password' => 'u4ci_7aM%pigRe]Vp9B',
]);
$login->login();
}
}
What is going here?
The method in the derived class must have the same parameters as the parent class, you must specify parameters $attributes and $clearErrors
public function validate($attributes=null,$clearErrors=true){
if($this->_token->validate($this->_data)){
$this->adminLogin();
return true;
}
$this->makeLog(self::UNVERIFIED);
return false;
}

No role detected by BjyAuthorize when login

I am working with ZF2, Doctrine ORM and BjyAuthorize.
The problem is that when I got logged in the method getRoles of the identity returns empty.
class User implements UserInterface, ProviderInterface{
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Application\Entity\Role", inversedBy="user")
* #ORM\JoinTable(name="user_role_linker",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="role_id", referencedColumnName="id")
* }
* )
*/
protected $roles;
public function __construct() {
$this->roles = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addRole(\Application\Entity\Role $role) {
$this->roles[] = $role;
return $this;
}
/**
* Remove role
*
* #param \Application\Entity\Role $role
*/
public function removeRole(\Application\Entity\Role $role) {
$this->roles->removeElement($role);
}
/**
* Get role
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getRoles() {
return $this->roles->getValues();
}
}
In the other hand, if I get the entity in the controller and I use getRoles, I get the values without any problem.
Could you please tell me which one could be the problem?
This is my zfc-user-doctrine-orm-global:
<?php
return array(
'doctrine' => array(
'driver' => array(
// overriding zfc-user-doctrine-orm's config
'zfcuser_entity' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'paths' => 'module\Application\src\Application\Entity',
),
'orm_default' => array(
'drivers' => array(
'Application' => 'zfcuser_entity',
),
),
),
),
'zfcuser' => array(
// telling ZfcUser to use our own class
'user_entity_class' => '\Application\Entity\User',
// telling ZfcUserDoctrineORM to skip the entities it defines
'enable_default_entities' => false,
),
'bjyauthorize' => array(
// Using the authentication identity provider, which basically reads the roles from the auth service's identity
'identity_provider' => 'BjyAuthorize\Provider\Identity\AuthenticationIdentityProvider',
'role_providers' => array(
// using an object repository (entity repository) to load all roles into our ACL
'BjyAuthorize\Provider\Role\ObjectRepositoryProvider' => array(
'object_manager' => 'doctrine.entitymanager.orm_default',
'role_entity_class' => 'Application\Entity\Role',
),
),
),
);
Do you have your roles defined in 'role' table, and userid <-> roleid in user_role_linker table?