This approach lets you directly link the templates to the category types defined by constants and avoid confusion or mismatch by string type keys.
User
i was thinking it be nice to have both options of int or string type for getAllowedTemplatesByType
Assistant
Absolutely! It is quite common and user-friendly to accept both integer constants (from ContentCategory) and string types (like 'post' or 'product') in your method that retrieves allowed templates. You can achieve this by normalizing the input internally.
Here’s a clean approach:
Maintain your mapping keys as integer constants (recommended, since your categories define constants).
Add a lookup map from string type to the integer constant.
In your getAllowedTemplatesByType() method, accept int|string as input, detect the type, and convert strings to the integer constant if needed.
Example implementation
php
use app\models\ContentCategory;
class Content extends ActiveRecord
{
public static $templates = ['item', 'artwork', 'article', 'exhibition', 'artist', 'catalog'];
// Keyed by ContentCategory int constants
protected static array $allowedTemplatesByType = [
ContentCategory::TYPE_POST => ['article', 'exhibition', 'artist', 'catalog'],
ContentCategory::TYPE_PRODUCT => ['item', 'artwork', 'exhibition', 'catalog'],
// ContentCategory::TYPE_CATALOG => [],
];
// Map string keys to ContentCategory constants
protected static array $typeMap = [
'post' => ContentCategory::TYPE_POST,
'product' => ContentCategory::TYPE_PRODUCT,
// 'catalog' => ContentCategory::TYPE_CATALOG,
];
/**
* Get allowed templates by type, accepts int constants or string keys
*
* @param int|string $type
* @return array
*/
public static function getAllowedTemplatesByType(int|string $type): array
{
if (is_string($type)) {
$type = strtolower($type); // normalize
if (isset(self::$typeMap[$type])) {
$type = self::$typeMap[$type];
} else {
// Unknown string type, return empty or error as you prefer
return [];
}
}
return self::$allowedTemplatesByType[$type] ?? [];
}
}
User
code
class ContentSearch extends Content
{
public static function getTypeList(): array
{
return [
ContentCategory::TYPE_POST => \Yii::t('app', 'Post'),
ContentCategory::TYPE_PRODUCT => \Yii::t('app', 'Product'),
//Content::TYPE_CATALOG => 'Catalog',
];
}
public static function getTemplateList(): array
{
return array_combine(Content::$templates, array_map('ucfirst', Content::$templates));
}
// ... keep existing code ...
public function rules(): array
{
return [
[['id', 'category_id', 'status', 'year', 'price', 'quantity',
'created_by', 'updated_by', 'created_at', 'updated_at'], 'integer'],
[['type', 'template', 'category_title', 'title', 'slug', 'body', 'meta_description',
'meta_keywords', 'artist', 'dimensions', 'medium'], 'safe'],
];
}
public function scenarios(): array
{
// By default, bypass parent's scenarios to allow all attributes for searching
return ActiveRecord::scenarios();
}
public function search(array $params): ActiveDataProvider
{
$query = Content::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ['pageSize' => 25],
'sort' => [
'defaultOrder' => [
'created_at' => SORT_DESC
]
],
]);
$this->load($params);
if (!$this->validate())
{
// Optionally return no records on validation failure
$query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'category_id' => $this->category_id,
'status' => $this->status,
'year' => $this->year,
'quantity' => $this->quantity,
'price' => $this->price,
'created_by' => $this->created_by,
'updated_by' => $this->updated_by,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'title', $this->title])
->andFilterWhere(['type' => $this->type])
->andFilterWhere(['template' => $this->template]);
return $dataProvider;
}
}
TypeError
ucfirst(): Argument #1 ($string) must be of type string, int given
TypeError
ucfirst(): Argument #1 ($string) must be of type string, int given
occurs because $model->type contains an integer (e.g. ContentCategory::TYPE_POST = 1), but ucfirst() expects a string, e.g. 'post'.
Why this happens
In your ContentSearch::getTypeList(), the keys are integers (ContentCategory::TYPE_POST = 1).
Your filter dropdown uses this array, so when you display the value, $model->type is integer.
But ucfirst() requires a string, so calling ucfirst(1) triggers the error.
How to fix
You need to convert those integer type values back to readable strings before applying ucfirst or better, use the mapping you already defined (getTypeList()) to get the string label.
Recommended changes:
Change the 'value' callback for the 'type' attribute:
Instead of:
php
'value' => function ($model)
{
return ucfirst($model->type);
},
do:
php
'value' => function ($model)
{
$types = ContentSearch::getTypeList();
// $model->type can be int or string key, normalize by int
$typeKey = is_numeric($model->type) ? (int)$model->type : $model->type;
return $types[$typeKey] ?? $model->type;
},
This way you show the proper human label (like 'Post' or 'Product') instead of an integer.
For 'template', you should not need ucfirst because your getTemplateList() already mutates template keys using ucfirst:
php
public static function getTemplateList(): array
{
return array_combine(Content::$templates, array_map('ucfirst', Content::$templates));
}
User
its the typelist giving issues
Assistant
Yes, the issue comes from how your getTypeList() is structured:
The values are translated strings like 'Post', 'Product'.
Then in your grid column's 'filter' you gave the whole array:
php
'filter' => ContentSearch::getTypeList(),
This is fine because the dropdown uses the keys for option values (integer 1, 2) and values for the displayed labels.
The problem arises when you do:
php
'value' => function ($model) {
return ucfirst($model->type);
},
Because $model->type is most likely integer 1 or 2, passing this directly to ucfirst() causes the error.
How to resolve: Display the label from the type list based on the model's type key
Instead of calling ucfirst($model->type), you want to fetch and display the translated label from your type list.
So you can do:
php
'value' => function ($model) {
$typeList = ContentSearch::getTypeList();
// $model->type might be int (1,2), look it up
return $typeList[$model->type] ?? $model->type;
}
No need for ucfirst() here because the translation already returns a proper string with first letter uppercase.
Optional improvement for extra safety: cast or normalize
If $model->type might sometimes be a string or integer, you can normalize:
Your $model->type is integer like 1, not string like 'post'.
Using ucfirst() directly causes error because ucfirst(1) is invalid.
Fetch the label from getTypeList() using $model->type as key and return that instead.
This lets your grid display the label without errors.
User
/**
* Render a related user (e.g. createdBy or updatedBy) with fallback
* If no name, fallback to email. If neither, mark as not set.
* Usage:
*
* [
* 'attribute' => 'created_by',
* 'format' => 'raw',
* 'value' => fn(model)=>ViewHelper::renderRelatedUser(model, 'createdBy'),
* ],[
* 'attribute' => 'updated_by',
* 'format' => 'raw',
* 'value' => fn(model)=>ViewHelper::renderRelatmodel, 'updatedBy'),
* ],
*/
public static function renderRelatedUser(model,stringrelation): string
{
user=ArrayHelper::getValue(model, $relation);
Yes, you can and should type-hint $model as an object if you expect it to be an object, especially a Yii ActiveRecord or a model instance. This both improves code clarity and enables static analysis.
Since $model is typically an instance of your model class (e.g. Content or its descendant), you can type hint it as object if you don't want to specify the exact class, or use a base class/interface if you want to be more restrictive.
Example with generic object type
php
public static function renderRelatedUser(object $model, string $relation): string
{
$user = ArrayHelper::getValue($model, $relation);
// ...
}
More specific type hint
If you know your models all extend yii\db\ActiveRecord, you could hint it like this:
php
use yii\db\ActiveRecord;
public static function renderRelatedUser(ActiveRecord $model, string $relation): string
{
$user = ArrayHelper::getValue($model, $relation);
// ...
}
Or if you have a common base model class, use that.
Notes
If for some reason $model could be an array or other types (unlikely in this context), keeping it untyped or mixed may be necessary.
PHP 7.2+ supports object type hint natively.
Static analysis tools (PHPStan, Psalm) will benefit from the type hint.
It helps IDE to provide autocomplete for $model.
Summary
Add type hint like this:
php
public static function renderRelatedUser(object $model, string $relation): string
or (better) more specific if you know the base class of your models.
If you want, an even stricter version that expects $user to have firstname, lastname, email properties would require declaring an interface or class for user, but that's usually unnecessary for this helper.
User
TypeError
app\helpers\ViewHelper::renderCurrency(): Argument #1 ($amount) must be of type string|int, null given,
called in views/content/artwork.php on line 163
public static function getIntl(int|string $amount): string
{
try
{
self::validateNumeric($amount, 'getIntl');
}
catch (YiiBaseInvalidConfigException $e)
{
return $e->getMessage();
}
$formatter = \Yii::$app->formatter;
$money = new Money($amount, new Currency($formatter->currencyCode));
$currencies = new ISOCurrencies();
$numberFormatter = new \NumberFormatter($formatter->locale, \NumberFormatter::CURRENCY);
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, $currencies);
return (string) $moneyFormatter->format($money);
}
Assistant
The error message:
code
TypeError
app\helpers\ViewHelper::renderCurrency(): Argument #1 ($amount) must be of type string|int, null given
indicates that $model->price is null in some cases. Your method renderCurrency() is type-hinted to accept only int|string, so passing null triggers this error before your code that checks $amount === null.
Why this happens
Even though your code inside the method gracefully handles null:
But allowing null in the type hint is cleaner and better.
Summary
Change this:
php
public static function renderCurrency(int|string $amount): string
to:
php
public static function renderCurrency(int|string|null $amount): string
to accept null and avoid the PHP TypeError.
User
would I be better of using this to check the value?
public static function isSetAndNull(value): bool
{
if (isset(value) && empty($value))
{
return true;
}
code
return false;
}
Assistant
Your current method:
php
public static function isSetAndNull($value): bool
{
if (isset($value) && empty($value))
{
return true;
}
return false;
}
What this does
isset($value) is true if $value is notnull.
empty($value) is true if $value is one of: 0, '0', null, false, '', [].
So the expression:
php
if (isset($value) && empty($value))
is true when:
$value is not null (isset true), and
$value is empty (like 0, '0', false, or empty string).
In other words, this returns trueonly for values like 0, '0', false, '' but not for null.
Is this what you want?
The method name isSetAndNull is confusing because you're checking if the value is not null (isset) and empty.
Usually, you'd want to check if value is not set or null or empty — for example to detect "missing" or "empty" values.
Recommended version to check "empty or null or unset"
If you want to check if a value is null, empty, or not set, you could do simply:
php
public static function isNullOrEmpty($value): bool
{
return empty($value);
}
Because empty() returns true for null, '', 0, '0', false, [], etc.
Or if you want to check specifically for null or empty string only, do:
php
public static function isNullOrEmptyString($value): bool
{
return $value === null || $value === '';
}
For your currency case
You want to detect when the value is null or empty string (meaning "not set"). So this is enough:
php
if ($amount === null || $amount === '') {
// treat as not set
}
No need to use isset() or empty() here.
In summary
Your current method name and logic do not check if value is null.
Also isset() returns false only if the value is null or not defined.
empty() is much broader (0 and false count as empty).
For currency, explicitly check null and '' to treat as "not set".
Final suggestion for your helper
Just use:
php
if ($amount === null || $amount === '') {
// handle not set case
}
Avoid overcomplicating with isset or custom functions unless you have a very specific need.
User
can i get created_by updated_by filters for cartQuery
Assistant
Sure! To add filters for created_by and updated_by in your cartQuery (assuming you are building an ActiveQuery or ActiveDataProvider for a Cart model or similar), here’s a general approach:
1. Make sure your Cart model has created_by and updated_by attributes
Typically, if these fields are saved in the table or are accessible via relations in your Cart model.
If they use behaviors like TimestampBehavior and BlameableBehavior, these attributes exist.
2. Add filtering in your search or query logic
For example, if you have a CartSearch model or in your controller where you build the data provider, add these filters:
php
$query = Cart::find();
if (!empty($this->created_by)) {
$query->andFilterWhere(['created_by' => $this->created_by]);
}
if (!empty($this->updated_by)) {
$query->andFilterWhere(['updated_by' => $this->updated_by]);
}
If your created_by and updated_by are integer IDs referring to users, you can create dropdown filter lists similar to what you did in ContentSearch.
3. Provide filter dropdown lists in the GridView or wherever you display the filter
For example:
php
// In CartSearch model or helper
public static function getUserList(): array
{
// Assuming User is your user model and you want id => username
return \app\models\User::find()
->select(['username', 'id'])
->indexBy('id') // Use user id as key
->column();
}
4. Make sure relations are defined in your Cart model:
php
public function getCreatedBy()
{
return $this->hasOne(User::class, ['id' => 'created_by']);
}
public function getUpdatedBy()
{
return $this->hasOne(User::class, ['id' => 'updated_by']);
}
Summary:
Add filtering conditions in your query (andFilterWhere on created_by, updated_by)
Provide filter dropdown lists for users
Display createdBy and updatedBy usernames in GridView via relations
If you want me to provide a precise code snippet tailored exactly to your cartQuery/search context, please share your Cart model and search method code.
User
could these:
public function getCreatedBy()
{
return $this->hasOne(User::class, ['id' => 'created_by']);
}
public function getUpdatedBy()
{
return $this->hasOne(User::class, ['id' => 'updated_by']);
}
be in the cartQuery file instead of the Cart activeRecord?
Assistant
No, the getCreatedBy() and getUpdatedBy()relation methods should be defined in the Cart ActiveRecord model, not in the CartQuery class.
Why?
Relations define how an ActiveRecord is related to other ActiveRecord models.
They belong in the ActiveRecord class (e.g. Cart.php) because this describes the data structure and relations of that entity.
The CartQuery class (or CartQuery object) is meant only for building and customizing queries (add conditions, scopes, etc.).
Relations are not query scopes or filters; they are part of the model's object graph representation, so they must live inside the AR class.
What is CartQuery for?
Typically, a query class extends ActiveQuery and is used for methods like:
php
public function active()
{
return $this->andWhere(['status' => 1]);
}
public function recent($limit = 5)
{
return $this->orderBy(['created_at' => SORT_DESC])->limit($limit);
}
You can call these scope-like methods on:
php
Cart::find()->active()->recent()->all();
But you cannot define relations (hasOne, hasMany) inside the query class because they are not query constraints, but rather part of the model itself.
Summary
Put relations like getCreatedBy() in Cart model class (which extends ActiveRecord).
Use CartQuery for complex query logic / scopes only.
This keeps a clear separation of responsibilities per Yii2 conventions.
Example structure:
php
// Cart.php (ActiveRecord model)
class Cart extends \yii\db\ActiveRecord
{
// ...other methods...
public function getCreatedBy()
{
return $this->hasOne(User::class, ['id' => 'created_by']);
}
public function getUpdatedBy()
{
return $this->hasOne(User::class, ['id' => 'updated_by']);
}
}
// CartQuery.php (ActiveQuery)
class CartQuery extends \yii\db\ActiveQuery
{
public function active()
{
return $this->andWhere(['status' => 1]);
}
// Other custom query methods...
}
If you want, I can help you move these methods properly based on your project structure.
You can simplify that query by creating a reusable method in your CartQuery class (or directly in the Cart ActiveRecord) — whichever fits your architecture. This method will encapsulate the commonly used condition for finding a Cart item by created_by and product_id.
Option 1: Add a custom query scope in CartQuery
If you have a custom query class CartQuery, add this method:
php
// CartQuery.php
public function byUserAndProduct(int $userId, int $productId): self
{
return $this->andWhere([
'created_by' => $userId,
'product_id' => $productId,
]);
}
If not already done, you should override find() in the Cart model so it returns your CartQuery:
php
// Cart.php
public static function find(): CartQuery
{
return new CartQuery(get_called_class());
}
This allows you to use your custom query methods fluently.
If you want, I can help you build more custom query methods or chain filters!
User
code
Assistant
Looks like your last message was empty — if you want to continue or have a new question, just let me know!
User
code
/**
* Filter by User ID
* @param int|string $userId
* @return static
* Usage:
*
* Model::find()->userId('1')->one();
*/
public function userId(int|string $userId): self
{
$id = (int) $userId;
return $this->andWhere(['created_by' => $id]);
}
/**
* Filter by Product ID
* @param int|string $productId
* @return static
* Usage:
*
* Model::find()->productId('1')->one();
*/
public function productId(int|string $productId): self
{
$id = (int) $productId;
return $this->andWhere(['product_id' => $id]);
}
/**
* Filter by User and Product
* @return
*/
public function byUserAndProduct(int $userId, int $productId): self
{
return $this->andWhere([
'created_by' => $userId,
'product_id' => $productId,
]);
}
so are they self or static
Assistant
Great question!
self vs static in return type for query builder methods
In your query class methods:
php
public function userId(int|string $userId): self
{
// ...
}
public function productId(int|string $productId): self
{
// ...
}
public function byUserAndProduct(int $userId, int $productId): self
{
// ...
}
Both self and static can be used as return type references, but they behave differently with inheritance:
Differences:
self means the class where the method is declared.
static (late static binding) means the actual class that called the method (even in subclasses).
Which one to use for ActiveQuery subclasses?
Since query classes are often inherited or extended, it’s a best practice to use static as the return type for chainable query methods, so that subclasses preserve the correct return type.
For example:
php
public function userId(int|string $userId): static
{
// ...
}
This ensures that when you call:
php
MyCustomCartQuery::find()->userId(1);
the return type remains MyCustomCartQuery, not the base class where the method was declared.
Summary:
Use static as return type for query builder methods to support fluent interfaces and inheritance.
Using self can restrict chaining in subclasses as it always refers to the defining class.
Therefore, your methods should be:
php
public function userId(int|string $userId): static
{
$id = (int) $userId;
return $this->andWhere(['created_by' => $id]);
}
public function productId(int|string $productId): static
{
$id = (int) $productId;
return $this->andWhere(['product_id' => $id]);
}
public function byUserAndProduct(int $userId, int $productId): static
{
return $this->andWhere([
'created_by' => $userId,
'product_id' => $productId,
]);
}
Let me know if you'd like a deeper explanation or examples!
This design gives you the flexibility of using either integer constants internally (recommended) or more human-readable strings externally, and it gracefully handles unknown inputs by returning an empty array (customize as needed).
Each template key already has a capitalized label, so just do:
php
'value' => function ($model)
{
// fallback if template key is unexpected
return ucfirst($model->template ?? '');
},