Yii2 Unknown model map key - php

I'm extending the registrationForm model for yii2-usuario, and overriding the rules() function.
my model looks like this
namespace app\models\user\Form;
use Da\User\Form\RegistrationForm as BaseForm;
class RegistrationForm extends BaseForm
{
public $captcha;
public $firstname;
public $lastname;
public $password_repeat;
public function rules()
{
/** #var User $user */
$user = $this->getClassMap()->get(User::class);
return [
// username rules
'usernameLength' => ['username', 'string', 'min' => 3, 'max' => 255],
'usernameTrim' => ['username', 'filter', 'filter' => 'trim'],
'usernamePattern' => ['username', 'match', 'pattern' => '/^[-a-zA-Z0-9_\.#]+$/'],
//'usernameRequired' => ['username', 'required'],
'usernameUnique' => [
'username',
'unique',
'targetClass' => $user,
'message' => Yii::t('usuario', 'This username has already been taken'),
],
...
...
}
}
but i'm getting this error
Unknown model map key: app\models\user\Form\User on this line $user = $this->getClassMap()->get(User::class);
Not sure how to fix this. The user.php model is in the correct directory app\models\user\Form\User.php
UPDATE:
in my main.php
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'enableEmailConfirmation' => true,
'classMap' => [
'RecoveryForm' => 'app\models\user\Form\RecoveryForm',
'RegistrationForm' => 'app\models\user\Form\RegistrationForm',
'ResendForm' => 'app\models\user\Form\ResendForm',
'User' => app\models\user\Model\User::class
],
'viewPath' => '#app/views/user',
'controllerMap' => [
'registration' => [
'class' => app\controllers\user\RegistrationController::class, //\Da\User\Controller\RegistrationController::class,
'on ' . \Da\User\Event\FormEvent::EVENT_AFTER_REGISTER => function (\Da\User\Event\FormEvent $event) {
\Yii::$app->session->setFlash('info', Yii::t('usuario', 'A message has been sent to your email address. It contains a confirmation link that you must click to complete registration.'));
\Yii::$app->controller->redirect(['/user/security/login']);
},
'on ' . \Da\User\Event\FormEvent::EVENT_AFTER_RESEND => function (\Da\User\Event\FormEvent $event) {
\Yii::$app->session->setFlash('info', Yii::t('usuario', 'A message has been sent to your email address. It contains a confirmation link that you must click to complete registration.'));
\Yii::$app->controller->redirect(['/user/security/login']);
},
],
],

Related

Is there a way to get input values on messages function at laravel's request file?

At my registration form, i have a bool input as newCompany with values
0=register to existed company with company code
1=create new company
Using required_if validation at different fields. And if it fails throws a validation message like "The Company Code field is required when Company is 0."
I wanna set that 0 value as Existing for 0 and New for 1. So i'm inserted them to my language file and changed :value attribute for default error message at lang/en/validation.php file.
'required_if' => 'The :attribute field is required when :other is :value.'
Here's my app/Requests/AuthRegisterRequest.php file:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password;
use Illuminate\Validation\Rules\File;
use Illuminate\Http\Request;
class AuthRegisterRequest extends FormRequest {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize() {
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules(Request $request) {
return [
'name' => 'required|max:50|alpha',
'surname' => 'required|max:50|alpha',
'email' => 'required|email|unique:users,email',
'password' => [
'required',
Password::min(8)->numbers()->letters()->uncompromised(5)
],
'c_password' => 'required|same:password',
'newCompany' => 'required|boolean',
'companyCode' => 'nullable|required_if:newCompany,0|max:20|exists:user_companies,code',
'companyName' => 'nullable|required_if:newCompany,1|max:255',
'companyPhone' => 'nullable|required_if:newCompany,1|max:50|unique:user_companies,phone',
'activityTaxDocument' => [
'nullable',
'required_if:newCompany,1',
File::types(['jpg, jpeg, gif, png, doc, docx, pdf'])->max(5*1024) //5 MB
],
'privacyPolicies' => 'required|boolean'
];
}
public function attributes() {
return __('fieldname.AuthRegister');
}
public function messages() {
return [
'companyCode.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['0']
]),
'companyName.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['1']
]),
'companyPhone.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['1']
]),
'activityTaxDocument.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['1']
])
];
}
}
And lang/en/fieldname.php file
<?php
return [
'AuthRegister' => [
'name' => 'Name',
'surname' => 'Surname',
'email' => 'Email',
'password' => 'Password',
'c_password' => 'Confirm Password',
'newCompany' => 'Company',
'companyCode' => 'Company Code',
'companyName' => 'Company Name',
'companyPhone' => 'Company Phone',
'activityTaxDocument' => 'Activity/Tax Document',
'privacyPolicies' => 'Privacy Policy & Terms',
'newCompanyValues' => [
'1' => 'New',
'0' => 'Existing'
]
]
];
It's working but i wanna combine message for required_if validation to shorten the code according to newCompany field. But couldn't get input values at messages function.
Tried:
public function messages(Request $request) {
return [
'required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')[$request->newCompany]
])
];
}
But it throws 500 with error below
{
"message": "Declaration of App\\Http\\Requests\\AuthRegisterRequest::messages(Illuminate\\Http\\Request $request) must be compatible with Illuminate\\Foundation\\Http\\FormRequest::messages()",
"exception": "Symfony\\Component\\ErrorHandler\\Error\\FatalError",
"file": "/var/www/html/app/Http/Requests/AuthRegisterRequest.php",
"line": 67,
"trace": []
}
I have a lot of forms like this. Some of them have much much more fields changing according a bool field. Is there a way to get input values at messages function or capture it from somewhere else?
if not, is it worth to defining a new rule, or should i just define it for each field separately?
Thanks.
I think you can use sometimes method without message() method
public function rules(Request $request) {
return [
'name' => 'required|max:50|alpha',
'surname' => 'required|max:50|alpha',
'email' => 'required|email|unique:users,email',
'password' => [
'required',
Password::min(8)->numbers()->letters()->uncompromised(5)
],
'c_password' => 'required|same:password',
'newCompany' => 'required|boolean',
'companyCode' => 'nullable|sometimes|required_if:newCompany,0|max:20|exists:user_companies,code',
'companyName' => 'nullable|sometimes|required_if:newCompany,1|max:255',
'companyPhone' => 'nullable|sometimes|required_if:newCompany,1|max:50|unique:user_companies,phone',
'activityTaxDocument' => [
'nullable',
'sometimes',
'required_if:newCompany,1',
File::types(['jpg, jpeg, gif, png, doc, docx, pdf'])->max(5*1024) //5 MB
],
'privacyPolicies' => 'required|boolean'
];
}

'guard' => false in newEntity() options not working in Cakephp4

There's certainly something that I do wrong, but I can't use correctly the guard option of newEntity() method.
// Entity
class Bloc extends AbstractBloc
{
protected $_accessible = [
'*' => false // All fields are protected against mass assignment
];
}
'guard' => false doesn't allow to save my entity in this example :
// Controller
public function test()
{
$entity = $this->Blocs->newEntity([
'titre' => 'TEST ASSIGNEMENT',
'rubrique_id' => 282,
'description' => 'Content'
], ['guard' => false]); // guard is false but nothing changes
if ($this->Blocs->save($entity)) {
return $this->redirect([...]);
}
else {
die('save is false');
}
}
What am I doing wrong ?
There is no such option for Table::newEntity(), the guard option belongs to Entity::set(). The option for newEntity() is called accessibleFields.
$entity = $this->Blocs->newEntity(
[
'titre' => 'TEST ASSIGNEMENT',
'rubrique_id' => 282,
'description' => 'Content',
],
[
'accessibleFields' => [
// '*' => true
'titre' => true,
'rubrique_id' => true,
'description' => true,
],
]
);
https://book.cakephp.org/4/en/orm/saving-data.html#changing-accessible-fields

unique field validations in model based on foriegn key yii2

I have a table called menusoffered where I am storing menuname based on restaurantid which is a foreign key.
In my menusoffered model I have declared that menuname has a unique validator, but this is checking the uniqueness from the entire table.
I want it to check uniqueness based on restaurantid,
Can any one help me how to make this menuname unique for particular restaurantid?
Below is my given menu model,
class Menusoffered extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'menusoffered';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['phase_id', 'required', 'message' => 'Please select Phase'],
['menuname', 'required'],
['price', 'required'],
[['price'],'integer' , 'message' =>'Price should be in digits'],
[['image_url'], 'file'],
[['description', 'status'], 'string'],
[['createdts','restaurantid'], 'safe'],
['master_menu_sepcality_id', 'required', 'message' => 'Please select Speciality'],
['master_menu_type_id', 'required', 'message' => 'Please select Type'],
['menuname', 'unique', 'with'=>'restaurantid'],
[['restaurantid'], 'exist', 'skipOnError' => true, 'targetClass' => Restaurant::className(), 'targetAttribute' => ['restaurantid' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'master_menu_sepcality_id' => 'Master Menu Sepcality ID',
'master_menu_type_id' => 'Master Menu Type ID',
'item' => 'Item',
'price' => 'Price',
'restaurantid' => 'Restaurantid',
'phase_id' => 'Phase ID',
'description' => 'Description',
'image_url' => 'Image Url',
'status' => 'Status',
'createdts' => 'Createdts',
];
} }
Try this: Yii2 Unique Validator:
// a1 and a2 need to be unique together, only a1 will receive error message
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]

Yii2 PHP Excel Error getAttributeLabel() on null

I have to implementing export excel using moonland PHP excel extension. When I implemented it, it throws the error:
"Call to a member function getAttributeLabel() on null".
Code
$dataProvider = new \app\models\Details;
\moonland\phpexcel\Excel::widget([
'models' => $dataProvider,
'mode' => 'export', //default value as 'export'
'columns' => ['id','name','address'], //without header working, because the header will be get label from attribute label.
//'header' => ['id' => 'Header Column 1','name' => 'Header Column 2', 'address' => 'Header Column 3'],
]);
My model
class Details extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'details';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id'], 'required'],
[['id'], 'integer'],
[['name', 'address'], 'string', 'max' => 50],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
/* return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
'address' => Yii::t('app', 'Address'),
];*/
return [
'id' => 'ID',
'name' => 'Name',
'address' =>'Address',
];
}
}
Table
May i know what is the problem in that, thanks in advance for your idea

Yii2 app\model\Db6TrxImportData not found

I am new with Yii2 and i am having this error.
PHP Fatal Error – yii\base\ErrorException
Class 'app\models\Db6TrxImportData' not found
I have searched somewhere that you need to add
use app\models\Db6TrxImportData;
i have already added this to my controller but still get the same error. I am noob in yii2.. please help. This is my code.
<?php
namespace app\modules\dtv\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\components\helpers\User;
use app\components\helpers\Data;
use app\models\Db6TrxImportData;
class ManageController extends \yii\web\Controller
{
// Properties
public $layout = '/registerLayout';
public $breadcrumbItems;
public $breadcrumbHomeItems;
public $route_nav = 'dtv/manage/list';
public $viewPath = 'app/modules/dtv/views';
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['list', 'delete'],
'rules' => [
[
'allow' => true,
'actions' => ['list', 'delete'],
'roles' => ['#'],
'matchCallback' => function ($rule, $action) {
$identity = User::initUser();
$feature = Yii::$app->params['Modules']['News Video Management'];
return User::hasAccess($identity, $feature);
},
],
],
'denyCallback' => function ($rule, $action) {
if (Yii::$app->user->isGuest) {
$this->goHome();
} else {
$this->redirect(['/dashboard']);
}
}
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function init()
{
if (Yii::$app->user->isGuest) {
$label = Yii::t('app', 'Login');
$url = '/login';
} else {
$label = Yii::t('app', 'Dashboard');
$url = '/dashboard';
}
$this->breadcrumbHomeItems = [
'label' => $label,
'url' => $url,
'template' => '<li>{link}</li> ',
];
}
public function actionList()
{
// Initialize Layout
$this->breadcrumbItems = [
Yii::t('app', 'Xml acquisition article list')
];
$identity = User::initUser();
$ownerId = User::getOwnerId($identity);
$dtvMovieModel = new Db6TrxImportData();
$params = [ 'owner' => $ownerId,
'status' => 'active',
'application' => 'menumaker'
];
$dtvMovie = $dtvMovieModel->getRecords($params);
return $this->render('list', [
'dtvMovie' => $dtvMovie
]);
}
}
?>
This is my Model
<?php
namespace app\models;
use Yii;
use yii\db\Query;
use app\components\helpers\User;
use app\components\helpers\Data;
class Db6TrxImportData extends \yii\db\ActiveRecord
{
public static function tableName()
{
return '_dtvdb.trx_import_data';
}
public static function getDb()
{
return Yii::$app->get('dtvdb');
}
public function rules()
{
return [
[['article_id', 'ctrl_flg', 'image_flg', 'video_flg', 'del_flg', 'news_cat', 'news_cat_cd', 'copyright', 'copyright_cd', 'title', 'article_text', 'zapping_text'], 'required'],
[['cx_create_date', 'cx_update_date', 'publish_date_from', 'publish_date_to', 'import_date', 'create_time', 'up_time'], 'safe'],
[['status'], 'string'],
[['article_id'], 'string', 'max' => 12],
[['ctrl_flg', 'image_flg', 'video_flg', 'del_flg'], 'string', 'max' => 1],
[['news_cat', 'news_sub_cat', 'disptach_type', 'copyright', 'lang'], 'string', 'max' => 100],
[['news_cat_cd', 'dispatch_cd', 'copyright_cd', 'lang_cd', 'article_status', 'zapping_status'], 'string', 'max' => 2],
[['news_sub_cat_cd'], 'string', 'max' => 4],
[['title', 'zapping_text'], 'string', 'max' => 300],
[['article_text'], 'string', 'max' => 1000],
[['comment'], 'string', 'max' => 500]
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'article_id' => 'Article ID',
'cx_create_date' => 'Cx Create Date',
'cx_update_date' => 'Cx Update Date',
'ctrl_flg' => 'Ctrl Flg',
'image_flg' => 'Image Flg',
'video_flg' => 'Video Flg',
'del_flg' => 'Del Flg',
'news_cat' => 'News Cat',
'news_cat_cd' => 'News Cat Cd',
'news_sub_cat' => 'News Sub Cat',
'news_sub_cat_cd' => 'News Sub Cat Cd',
'dispatch_cd' => 'Dispatch Cd',
'disptach_type' => 'Disptach Type',
'copyright' => 'Copyright',
'copyright_cd' => 'Copyright Cd',
'lang_cd' => 'Lang Cd',
'lang' => 'Lang',
'publish_date_from' => 'Publish Date From',
'publish_date_to' => 'Publish Date To',
'title' => 'Title',
'article_text' => 'Article Text',
'comment' => 'Comment',
'zapping_text' => 'Zapping Text',
'import_date' => 'Import Date',
'article_status' => 'Article Status',
'zapping_status' => 'Zapping Status',
'status' => 'Status',
'create_time' => 'Create Time',
'up_time' => 'Up Time',
];
}
public static function findByAttribute($arr)
{
foreach ($arr as $arrKey => $arrValue) {
$record = self::find()->where($arrKey.'=:'.$arrKey,[':'.$arrKey => $arrValue])->one();
}
return $record;
}
}

Categories