Yii2 dynamically add behavior by class name or instance?

I am using behaviors and add them dynamically which is working fine. To add a a behavior, one can use $component->attachBehavior('myBehavior1', new MyBehavior); or $component->attachBehavior('myBehavior2', MyBehavior::className()); I cannot figure out when to use which method or is there no difference? Can someone explain this to me?

Yii2 Route all requests, not matching other routes, to single action

I used catchAll route to my config 'catchAll' => ['site/page'] and it works fine. But all request are going to this action, even that one that have a separate controller/action. How can I map the routing to match the controller/action at first, and if corresponding controller/action doesn't not exists, then fallback to catch all route?

Yii2 Object of class yii\jui\Dialog could not be converted to string

I am trying to use the Dialog widget provided by Yii2 default installation,but the application throws the following error: exception 'yii\base\ErrorException' with message 'Object of class yii\jui\Dialog could not be converted to string' Code: Dialog::begin([ 'id'=>'my-dialog', 'clientOptions' => [ 'modal' => true, ], ]); echo 'Dialog contents here...'; Dialog::end(); If anyone of you have faced this issue , please help me out on this. Thank You!

Accept String Parameter in Yii2 Action

In my config file I've set the url rule like this : <controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action> And what happens is:- controller/action/123 (work) controller/action/hello (not work) But it accepts only digit as the parameter. What I want is that both digit and string should be accepted. Please help!!!!

Yii2: Path issue while redirecting with pretty url from login

i have enabled pretty url in url manager & tried login with. When logs in successfully to my dashboard, i am getting problem w.r.t CSS & JS loading for that page as the path makes problem i have analyzed the problem in network problem the screen shots are below. First screen shot is the image when i am trying login without enabling pretty UR...works fine How to fix this issue. Second:This is the login page when i enabled pretty url & opened login view Third: This is the thir

Yii2 Yii 2: can not use @web in config/web.php file aliases section

I am using basic-template. here is my code in config/web.php: return [ 'aliases' => [ '@uploadUrl' => '@web/uploads/', ], ]; I want to use the alias like this: <?= Html::img( Yii::getAlias('@uploadUrl/'.$model->image)); ?> But, program erred: Invalid path alias: @web/uploads/ thanks for help!

Create thumbnail from uploaded image in Yii2

How can I create a thumb image from uploaded image? I tried this in my controller: <?php namespace backend\controllers; use Yii; use app\models\Employee; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\AccessControl; use yii\filters\VerbFilter; use yii\web\UploadedFile; use yii\imagine\Image; public function actionCreate() { $model = new Employee(); $model->added_date_time = date('Y-m-d H:i:s'); if ($model->load(Yii::$app->request->post()

Create thumb in Yii2

I have used this link to insatll yii2-imagine: ThumbCreate When it successfully run, then in /vendor/yiisoft/yii2/Imagine/ folder there is one folder vendor and then in that folder there are 2 more folders with name imagine and composer . In imagine folder there is one more folder with same name and then in that folder there are so many folders and file. i am attaching image for that. Now, how can i use thumbnail function to make thumbs of images. composer.json file { "name": "yiisoft/yii

Yii2 How to get max and min date in Yii 2

In my databae filed type 'import_date varchar(100)' value 'max => 01-01-2016' 'min => 31-12-2015' I have code to get max and min date $dateMin = Report::find()->min('import_date');// ouput 01-01-2016' => false $dateMax = Report::find()->max('import_date');// ouput 31-12-2015' => false Please help me Thank all

Yii2 trim everything on save

Yii2 framework. The idea to create common behavior for common model: before Validate trims all fields in model. if it's array trim all values in array. I'm wondered why in Yii2 core doesn't exist such possibility. Or I'm wrong. Am I? What problems could I face if I trim all fields?

Time is wrong when get datetime in yii2

I have a problem when I get datetime in my yii2 project. When I get datetime, the date is true but the time is wrong. I execute my code and the result is : 2016-05-02 12:30:28 whereas the time in my laptop is : 19:30. What's the problem? I use time in Indonesia. This is my code: $time = new \DateTime('now', new \DateTimeZone('UTC')); $model->tanggal_sampai = $time->format('Y-m-d H:i:s');

Yii2 Custom validation on scenario not working

I am creating a function for validation data on given scenario but its not working. Model code : public function rules() { return [ // ['session_key','deal_id','required'], ['data', 'validateCart'], [['session_key','deal_id'], 'safe'], // [['cartfood','session_key'], 'required','on'=>'sessionapi'], ['cartfood', 'myvalidation', 'on' => 'sessionapi'], ]; } public function myvalidation($attribute, $params){ if (!$this-

Yii2 phpdoc for Yii::$app->passport

My IDE PHPStorm marks next line as mistake (word "password") Yii::$app->passport->getLoginUrl($Url); How can i write phpdoc for it. May be in suchway or how? /** @var $Yii::$app->passport array */ Yii::$app->passport->getLoginUrl($Url);

Yii2: Using TinyMCE into Kartik's DetailView with custom settings

I'd like to insert 2amigos' TinyMCE widget in Kartik's DetailView edit mode. This is what I got by now: [ 'attribute' => 'myAttribute', 'format' => 'raw', 'type' => 'widget', 'widgetOptions' => ['class' => TinyMce::classname()], 'value' => $model->myAttribute, ], With this chunk I managed to show TinyMCE editor with default settings. What I'm trying to do now is to show it with custom settings defined

yii2 attribute display a value in a view

I have an attribute house_id, I want to get the address from the house_id and display it in a view. My view <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'house_id', ], ]) ?> Thanks Edit: Here is the solution Thanks to Raditz for the help. Model: public static function getHouseAddressPayroll($house_id) { if ($house_id) { $house = House::findOne($house_id); $address = $house->address_line_1.', '.$house->city.'

How to write the material design radio button in yii2?

I am facing issue with material design radio button using in yii2. this is the material design radio button which is working perfectly <div class="radio"> <label> <input type="radio" name="q_option" value="Recent advances in MS"> Recent advances in MS </label> </div> but when I write the same radio button in yii2 framework, the radio button dot become disappear and become non clickable <div class="radio"> <?= $form->field($m

can we use old database and table with records for developing new project with custom form in yii2

I have to sign up with old project's database with same table name "user" but fields name are different, so can I signup with custom code. So which class I have to extend, I am not using a table made Yii2 I am using my old table with records. My model code: <?php namespace app\models; use Yii; use yii\base\Model; /** * This is the model class for table "user". * * @property string $username * @property string $email * @property string $pass */ class Signup extends \yii\db\ActiveReco

Pretty URL in Yii2 LinkPager with custom params

I need LinkPager to create page URL like /site/page/1/job/2/order-price/3/order-exp/4/. The route works fine with the URL manager, but LinkPager ignores this route and creates URL with ?foo=bar parameters. $rules = [ 'site/page/<page:\d+>/job/<job_id:\d+>/order-price/<min_price:\d+>/order-exp/<experience:\d+>/' => 'site/index' ]; 'components' => [ 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false,

Yii2 How to update multiple images in kartik Upload widget?

Here i can only able preview the images on update the model. I want to load the images properly so user can remove one r more file and update will work accordingly Here is my controller public function actionUpdate($id) { $model = $this->findModel($id); $session_data = \common\models\Customer::find()->where(['user_id' => $model->customer_user_id])->one(); $towing = \common\models\TowingRequest::find()->where(['id' => $model->towing_request_id])->one();

yii2 show message from database error

I have related tables and show at gridview. When i want to delete data from gridview, i take the mysql error about this data using other tables field. At that time i want to show message to user for example "This data not deleting". I did it at yii 1.1 as follows. views/xxx/index.php <div id="statusMsg"> <?php if(Yii::app()->user->hasFlash('success')):?> <div class="flash-success" > <?php echo Yii::app()->user->getFlash('success'); ?>

Yii2 Opening existing project using xampp

I have a ready yii2 project but it was created another computer. Now I want to change the project using my localhost xampp. How can I open my yii2 project in order to change and can see using localhost xampp?

Yii2 Kartik Select2 error when try to use it with ajax

I've used kartiks select2 many time with ajax before. Now when I tried to implement it again this error is thrown in console: jquery.js:3850 Uncaught Error: Option 'ajax' is not allowed for Select2 when attached to a <select> element. There is no other errors. My implementation looks like: <?php echo $form->field($model, 'destination_from')->widget(Select2::class, [ 'initValueText' => isset($_GET['MassManagementSearch']) ? $_GET['MassMana

Yii2 Check existing of a pair attributes

I have a form model which creates record in the table. The table contains "many-to-many" relations. I want to check existing of the relation due creation of new one. So I did this validator: [ ['baseId', 'companyId'], 'exist', 'targetClass' => CompaniesToBases::class, 'targetAttribute' => ['baseId' => 'base_id', 'companyId' => 'company_id'], ], And it doesn't work. No errors, no messages in the debugger. And it allows to create same records in the table. Any ideas how

covert raw mysql query to yii2 query 2 left join subquery and sum all

I have created a raw query in mysql which is working fine. I am trying to convert it to yii2 query but I can't complete it Can anyone help me Raw query: SELECT ship.month_name, MIN(ship.average_value_percent) as minimum_container_utilization, MAX(ship.average_value_percent) as maximum_container_utilization, SUM(ship.average_value) / COUNT(ship.shipment) as volume, SUM(ship.average_weight) / COUNT(ship.shipment) as volume_kgs, SUM(ship.average_volume_cbm) / COUNT(ship.shipment) as vol

Yii2 Missing features in Ckeditor

Using yii2-ckeditor-widget but missing upload tab and browser, how can I integrate those features .. I have tried the 2amigos CKEditor Widget for editor. But cant upload the image though I paste the url of the image. any solution to get those features in yii2 ?

Updating Image in Yii2

While updating image using Yii2 I'm facing a problem with the validation.Its always asking me to upload an image. But I don't want this. Always updating an image is not necessary. I tried skipOnEmpty but its not working properly it cause effect while uploading a photo, which is also incorrect. Please help!! Model public function rules() { return [ [['carid', 'name'], 'required'], [['carid', 'coverphoto', 'status'], 'integer'], [['name'], 'stri

Undefined variable: yii2

Getting error when I am trying to create dynamic form in using yii2-dynamicform. at the time of create method it is working fine but at the time of update showing the error. I have two tables one is 1.vendors & 2.vendors_more_categories Relation is 1-* between vendors & vendors_more_categories I just refereed https://github.com/wbraganca/yii2-dynamicform this link. <?php namespace app\controllers; namespace backend\controllers; use Yii; use app\models\Vendors; use app\models\Ven

Yii2 and sqldataprovider in inner query, write one aggregating expression per reporting column, 2. In an outer query, build the horizontal sums

I'm trying to make an Pivot Table from rows to columns using Yii2 and I have the following table in Mysql: CREATE TABLE Sales (empID INT, yr SMALLINT, sales DECIMAL(10,2)); INSERT sales VALUES (1, 2005, 12000),(1, 2006, 18000),(1, 2007, 25000), (2, 2005, 15000),(2, 2006, 6000),(3, 2006, 20000),(3, 2007, 24000); and the following sqldataprovider in Yii2: and the final table view showing only the sums and not showing sums per year:

urlManager rules not working on modules Yii2

I am trying to make some url rules in Yii 2 so I can access an action from the controller like this: controller/action/1 -> controller/action (with a parameter) I tried some rules but they won't work in my modules (www.example.com/midend, www.example.com/backend). So, if I want to access www.example.com/controller/action/1 it's works just fine but if I want to access www.example.com/midend/controller/action/1 it return 404. These are the rules for modules: '<module:\w+>/<contro

Yii2 formatting boolean field in GridView

I remember to have done this before, but now it does not work and I can't get it out. [ 'label' => 'Sex', 'attribute' => 'gan_sex', 'filter' => [ '1' => 'Male', '2' => 'Female' ] ], The output is 1 2 2 1 instead of Male Female Female Male What is the problem now? I'd swear I used it just the same way but ...

Yii2 GridView Custom Search TextBox

As the design require to use the search Textbox out site the gridview what I want to do is to search from textbox outside the gridview by attribute 'name'. I don't know the way or best practice how to do it. Please help!!!

Yii2 relations with junction table

I have free tables: user, book, user_book, offers user table has method: public function getBooks() { return $this->hasMany(UserBook::className(), ['user_id' => 'id']); } user_book table has two fields: user_id, book_id; and methods public function getUser() { return $this->hasOne(User::className(), ['id' => 'user_id']); } public function getBook() { return $this->hasOne(Book::className(), ['id' => 'book_id']); } table offer h

Insert multiple records of a same table Yii2

I want to insert same record in one table. I have only one input array in the below form but i want to save multiple time record for label input array. my form is <div class="surveys-questions-form"> <?php $form = ActiveForm::begin(); ?> <?php if(isset($_GET['option_id']) and $_GET['option_id'] > 0) $id= $_GET['option_id']; else $id= $model->option_id; echo $form->field($model, 'question_id')->hiddenInput([

Yii2 Can not Store huge integer

I want to store huge integer minimum 13 digit max 15 digit. But every time it stored garbage. My model is: [['NIC'], 'integer'], i also tried by safe & string validator but could not save correct number in database. PS. I am using Oracle and from oracle forms and from back end with insert query data is stored perfectly.

How to extend a model that is part of an Yii2 extension?

In my application I'm using an extension (which I own and may modify). This extension has an ActiveRecord based class that I want to extend in the application with another property. Can I do this somehow? Can a Factory help anyhow or Yii behaviour? Class in extension: namespace extension; /** * @property integer $id * @property string $name */ class Product extends ActiveRecord { public static function tableName() { return 'product'; } /** * @inheritdoc */

How do I use yii2-dashboard?

I would like to use a dashboard for my system. I found this Yii2-dashboard module. I am not sure if it is like GII where you can create models, CRUD, etc. In short, does yii2-dashboard has a UI like GII? Or should I manually code it? Thanks a lot!

Hide header and footer in panel yii2

How to hide header and footer in view of yii2? view->panel One page without header and footer in yii2. <div class="wrap"> </div> and <footer class="footer"> </footer>

Yii2 appendTimestamp and registerAssetBundle

I am using the following configurations to add the timestamp in the assets path via asset manager. 'assetManager' => [ 'appendTimestamp' => true, appAsset.php class AppAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [ '/css/style.css' ]; } In view AppAsset::register($this); But in html I still see '/css/style.css' without timestamp. I saw solution https://github.com/yiisoft/yii2/issues/9101#issue

Yii2 "Edit" and "Close" Sign symbol while exporting Excel

When I try to export data in excel using "kartik\editable\Editable::widget" and "ExportMenu::widget" then "Edit" and "Close" sign symbols are also exported in my excel. How to remove that "Edit" and "Close" Sign symbol while exporting Excel? return kartik\editable\Editable::widget([ 'header'=>false, 'name' => 'status', 'size'=>'sm', 'type'=>'primary', 'placement'=>'right', 'containerO

Yii2 client side validation refreshes the page on form submit

I am trying to perform client side check but the page is being refreshed. My rules looks like: public function rules() { return [ [['email'], 'required'], [['email','cron'], 'string'], [['email'], 'string', 'max' => 100], [['cron', 'group', 'type'], 'integer'], [['email'], 'unique'], ['group', 'required', 'when' => function($model){ return $model->type == 1; }, 'whenClient' =

Yii2 Read Write splitting couldn't connect slave server in master slave configuration

Have done Master Slave configuration as per official Yii2 documentation. Below is actual configuration look like, 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=1.1.1.1;dbname=master_db', 'username' => 'user', 'password' => 'password', 'charset' => 'utf8', 'enableSchemaCache' => true, 'schemaCacheDuration' => 10, 'schemaCache' => 'cache', 'slaveConfig' => [ 'username

Yii2 Update swiftmailer configuration based on user input

I need to update SwiftMailer configuration based on user input, particularly, the user may decide to send emails using SMTP protocol or store them locally (in an specific filesystem's folder). The user will use a view to decide the option, then the controller catch the decision and update a session var. The current approach is to read that session var from config/web.php and then choose the appropriate configuration. I am not sure whether web.php is loaded just once during the application execu

Yii2 relation based on attribute values instead of keys

I have 2 tables in the db (mysql), and between the 2 there is no classic relationship through keys or ids. The only way I could define relationship would be through attribute values. E.g. table wheel and car and certain wheels would match certain cars because of the size only. Can it be defined on DB level, and/or in yii2, and if yes, how? In the relations I can add an onCondition(), but you have to define an attribute (???), too: public function getWheels() { return $this->hasMany(\app

Yii2 Gridview display all columns

How can I display all columns in gridview without define the columns that I want to displau in view ? In Yii2 doc, <?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ //define columns here 'id', 'name', 'created_at:datetime', // ... ], ]) ?> Can we just <?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => '*', ]) ?>

Yii2 Error Calling unknown method: omgdef\multilingual\MultilingualQuery::sort()?

Good afternoon, help me figure it out, using the OmgDef/yii2-multilingual-behavior extension, swears at this line: public function actionIndex() { $data = new ActiveDataProvider([ 'query' => FaqLang::find()->multilingual()->sort(), //error here ]); return $this->render('index', [ 'data' => $data ]); } My overridden model that stores the sort() method <? namespace admin\base; /** * Base active query class for

sjaakp/yii2-illustrated-behavior Yii2 extension for image not working

I am getting error; Is there any complete example of how to use the behavior(configuration in model,view,controller) practically;the documentation on github doesn't really help. In my model the field that store the img link in db is imglink; the code are: public $photo;//The file attributes public function behaviors(){ return [ [ "class" => "sjaakp\illustrated\Illustrated", "attributes"=>[ 'img'=>[ 'aspectRatio'=>1.0, 'cropSize'=>90,] ] ], ]; } //rules : $rules[] = ['photo','fil

Error in logging out in yii2

Am trying to logout uusing yii2 logout link but it returns an error of only method of post This is my code: "btn btn-default btn-flat" ,'data-method' => 'post']); ?>

  1    2   3   4   5   6  ... 下一页 最后一页 共 15 页