PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label yii-components. Show all posts
Showing posts with label yii-components. Show all posts

Saturday, March 12, 2022

[FIXED] Yii2 Multiple instances of the same model

 March 12, 2022     php, yii, yii-components, yii-extensions, yii2     No comments   

Issue

I want to get multiplie instance of the same model in my controller. I saw this wiki for Yii 1.1 and tried like that but in my code only last instance in form was acceble from controller my code is here (I commented code with error and variable values):

$model = new Person(['scenario' => 'create_update']);
$contractDate = new DatePart(); // DatePart is my own class
$contractExpirationDate = new DatePart(); // DatePart is my own class

if ($model->load(Yii::$app->request->post()) &&
    $contractDate->load(Yii::$app->request->post()) &&
    $contractExpirationDate->load(Yii::$app->request->post())){

    Yii::info(Yii::$app->request->post(),'test'); // only one instance of Person and one instance of DatePart are available here
    Yii::info($_POST['DatePart'],'test'); // only last instance of DatePart (contractExpirationDate in html form) is available here
    Yii::info($_POST['DatePart'][0],'test'); // Error: Undefined offset: 0
    Yii::info($_POST['DatePart'][1],'test'); // Error: Undefined offset: 1

    $model->save();
    return $this->redirect(['view', 'id' => $model->id]);
} else {
    return $this->render('create', [
        'model' => $model,
        'contractDate' => $contractDate,
        'contractExpirationDate' => $contractExpirationDate,
    ]);
}

It is my form view in _form.php:

<?php

use yii\helpers\Html;
//use yii\widgets\ActiveForm;
use kartik\widgets\ActiveForm;
use common\models\DataOperations;

/* @var $this yii\web\View */
/* @var $model app\models\Person */
/* @var $contractDate backend\viewModels\DatePart */
/* @var $contractExpirationDate backend\viewModels\DatePart */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="user-form">
    <?php
    $form = kartik\widgets\ActiveForm::begin(
        [
            'id' => $model->isNewRecord ? 'user-form-create' : 'user-form-update',
            'type' => ActiveForm::TYPE_VERTICAL,
            //'enableAjaxValidation' => true,
            'fieldConfig' => [
                //'autoPlaceholder'=>true
            ]
        ]);
    ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => 60]) ?>  
    <?= $form->field($model, 'family')->textInput(['maxlength' => 60]) ?>
    <?= $form->field($model, 'mobile')->textInput() ?>

    <?= $form->field($contractDate, 'year')->textInput() ?>
    <?= $form->field($contractDate, 'month')->textInput() ?>
    <?= $form->field($contractDate, 'day')->textInput() ?>

    <?= $form->field($contractExpirationDate, 'year')->textInput() ?>
    <?= $form->field($contractExpirationDate, 'month')->textInput() ?>
    <?= $form->field($contractExpirationDate, 'day')->textInput() ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>  
</div>

It is log result for: Yii::info(Yii::$app->request->post(),'test') in debugger as you seen only last DatePart available but I have two DatePart model instance (contractDate and contractExpirationDate):

[
    '_csrf' => 'Vl81R0ZvMk1hD1oELT9aDzkIe3EPHFgiIBJTBhA9RD8GbFM.AhlVBw==',
    'Person' => [
        'name' => 'test name',
        'family' => 'test family',
        'mobile' => '09121212123',
    ],
    'DatePart' => [
        'year' => '2015',
        'month' => 'Jun',
        'day' => 'Mon',
    ],
]

Solution

Controller:

    $model = new Person(['scenario' => 'create_update']);
    $dates = [
        'contractDate' => new DatePart(),
        'contractExpirationDate' => new DatePart()
    ];
    if ($model->load(Yii::$app->request->post())) {

        if (Model::loadMultiple($dates, Yii::$app->request->post()) && Model::validateMultiple($dates)) {
            foreach ($dates as $date) {
                $date->save();
            }
            // or
            $contractDate = $dates['contractDate'];
            $contractExpirationDate = $dates['contractExpirationDate'];
            // ...... some logic

            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        }
    }
    else {
            return $this->render('create', [
                'model' => $model,
                'dates' => $dates
            ]);
    }

View Form:

<?= $form->field($dates, '[contractDate]year')->textInput() ?>
<?= $form->field($dates, '[contractDate]month')->textInput() ?>
<?= $form->field($dates, '[contractDate]day')->textInput() ?>

<?= $form->field($dates, '[contractExpirationDate]year')->textInput() ?>
<?= $form->field($dates, '[contractExpirationDate]month')->textInput() ?>
<?= $form->field($dates, '[contractExpirationDate]day')->textInput() ?>


Answered By - zelenin
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, March 6, 2022

[FIXED] how to use gii generator with modules in yii framework?

 March 06, 2022     form-generator, gii, yii, yii-components, yii-extensions     No comments   

Issue

i am using the gii generator to create a module.

the issue is when i try to create a form or some model for that module... i can't tell it to generate those files in that module... it only does it in the main application folders.

any ideas?

thanks.enter image description here


Solution

To create a model for a specific module in yii you can give input to the model path text field like 'application.modules..models'.



Answered By - Kapil gopinath
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, March 5, 2022

[FIXED] SQLSTATE[HY000] [1049] on YiiFramework

 March 05, 2022     yii, yii-components     No comments   

Issue

$ yii migrate

Yii Migration Tool (based on Yii v2.0.13-dev)

Exception 'yii\db\Exception' with message 'SQLSTATE[HY000] [1049] Unknown database 'yii''

in E:\laragon\www\website\vendor\yiisoft\yii2\db\Connection.php:586

Stack trace:

    #0 E:\laragon\www\website\vendor\yiisoft\yii2\db\Connection.php(932): yii\db\Connection->open()
    #1 E:\laragon\www\website\vendor\yiisoft\yii2\db\Connection.php(919): yii\db\Connection->getMasterPdo()
    #2 E:\laragon\www\website\vendor\yiisoft\yii2\db\Command.php(219): yii\db\Connection->getSlavePdo()
    #3 E:\laragon\www\website\vendor\yiisoft\yii2\db\Command.php(1031): yii\db\Command->prepare(true)
    #4 E:\laragon\www\website\vendor\yiisoft\yii2\db\Command.php(362): yii\db\Command->queryInternal('fetchAll', NULL)
    #5 E:\laragon\www\website\vendor\yiisoft\yii2\db\mysql\Schema.php(320): yii\db\Command->queryAll()
    #6 E:\laragon\www\website\vendor\yiisoft\yii2\db\mysql\Schema.php(111): yii\db\mysql\Schema->findColumns(Object(yii\db\TableSchema))
    #7 E:\laragon\www\website\vendor\yiisoft\yii2\db\Schema.php(661): yii\db\mysql\Schema->loadTableSchema('migration')
    #8 E:\laragon\www\website\vendor\yiisoft\yii2\db\Schema.php(174): yii\db\Schema->getTableMetadata('{{%migration}}', 'schema', true)
    #9 E:\laragon\www\website\vendor\yiisoft\yii2\console\controllers\MigrateController.php(201): yii\db\Schema->getTableSchema('{{%migration}}', true)
    #10 E:\laragon\www\website\vendor\yiisoft\yii2\console\controllers\BaseMigrateController.php(864): yii\console\controllers\MigrateController->getMigrationHistory(NULL)
    #11 E:\laragon\www\website\vendor\yiisoft\yii2\console\controllers\BaseMigrateController.php(166): yii\console\controllers\BaseMigrateController->getNewMigrations()
    #12 [internal function]: yii\console\controllers\BaseMigrateController->actionUp(0)
    #13 E:\laragon\www\website\vendor\yiisoft\yii2\base\InlineAction.php(57): call_user_func_array(Array, Array)
    #14 E:\laragon\www\website\vendor\yiisoft\yii2\base\Controller.php(157): yii\base\InlineAction->runWithParams(Array)
    #15 E:\laragon\www\website\vendor\yiisoft\yii2\console\Controller.php(135): yii\base\Controller->runAction('', Array)
    #16 E:\laragon\www\website\vendor\yiisoft\yii2\base\Module.php(528): yii\console\Controller->runAction('', Array)
    #17 E:\laragon\www\website\vendor\yiisoft\yii2\console\Application.php(180): yii\base\Module->runAction('migrate', Array)
    #18 E:\laragon\www\website\vendor\yiisoft\yii2\console\Application.php(147): yii\console\Application->runAction('migrate', Array)
    #19 E:\laragon\www\website\vendor\yiisoft\yii2\base\Application.php(386): yii\console\Application->handleRequest(Object(yii\console\Request))
    #20 E:\laragon\www\website\yii(20): yii\base\Application->run()
    #21 {main}

this my db

return [ 'class' => 'yii\db\Connection', 'driverName' => 'mysql', 'dsn' => 'mysql:host=localhost;dbname=yii', 'username' => 'root', 'password' => '', 'charset' => 'utf8',

// Schema cache options (for production environment)
//'enableSchemaCache' => true,
//'schemaCacheDuration' => 60,
//'schemaCache' => 'cache', ];

Solution

The error message means you need to create a database name 'yii'.

Just use Menu > MySQL > Create database to create the database.



Answered By - Leo Khoa
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, February 15, 2022

[FIXED] how to fix this session with my CJuiDialog box content in Yii 1.4.x?

 February 15, 2022     jquery, yii, yii-components     No comments   

Issue

The part I am working on is one of the modules of a web application powered by Yii 1.4.x .I have a CGridView in my index view file. Then inside it,I have custom buttons. One of the buttons is popping up a dialog box. here's the snippet for that custom button that i mentioned

        'see' => array(
             'label' => 'View',
             'url' => 'Yii::app()->controller->createUrl("myControllerName/view",array("id" => "$data->id"))',

             'options' => array(
                 'ajax' => array(
                    'type' => 'POST',
                     'url' => "js:$(this).attr('href')",
                     'dataType' => "json",
                     'async' => false,
                     'success' => 'function(data){
                            $("#detail-dialog").dialog("open"); return false;
                        }',
                     'update' => '#detail'
                 )
             )
        ),

Here is the snippet of the controller action that named 'view' in the controller

   public function actionView(){

        $gid = $_GET['id'];

        $data = array();
        if(Yii::app()->request->isAjaxRequest) {
            $model = MyModelName::model()->findById($gid);
            if (!empty($model) || !is_null($model)) {
                $attributes = $model->getAttributes();
                $result = MyModelName::model()->findByKey($attributes['key'], $attributes['new_key']);
                if(!empty($result)){
                    foreach($result as $key => $val){
                        $data['model'][$key] = $val;
                    }
                    $data['code'] = self::CODE_AJAX_SUCCESS;
                  }
            } else {
                $data['code'] = self::CODE_AJAX_ERROR;
            }
           $_SESSION['ajaxresponse'] = json_encode($data);
           echo json_encode($data);
           exit;
        }

at the bottom of the CGridView of my view file, I have this snippet of the CJuiDialog

$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
    'id' => 'detail-dialog',
    'options' => array(
        'title' => 'Edit Data',
        'autoOpen' => false,
        'modal' => false,
        'width' => 600,
        'height' => 500,
        'close' => 'js:function(){
            //nothing here
        }'
    ),
)); ?>

$result = $_SESSION['ajaxresponse'];
$this->renderPartial('_view',array('viewajaxresponse' => $result));
$this->endWidget('zii.widgets.jui.CJuiDialog');

Whenever I click a row in the CGridView, It pops out the CJuiDialog box, along with the ajax response inside it because I rendered partial it from the session.

Now the issue is, let's say I closed the CJuiDialog box then I clicked the 2nd row or another row in the CGridView, the contents of the Dialog box remains with the first row that I clicked unless I force refresh the browser like two or three times before the data inside the Dialog box changes .How to solve this problem?

I even implemented an ajax function of the 'close' event of the CJuiDialog box in order to kill the session

  $.ajax({
            url: "'.Yii::app()->controller->createUrl("MyControllerName/destroysession", array("s"=>"ajaxresponse")).'",
            type: "POST",
            dataType: "json",
            async: true,
            success: function(data){
               document.location.reload(true);
        }
    });

and then in the controller action

public function actionDestroysession(){
        $name = !empty($_GET['s'])?$_GET['s']:'';
        if(isset($name)){
            unset($_SESSION[$name]);
            $data['code'] = self::CODE_AJAX_SUCCESS;
            echo json_encode($data);
            exit;
        }
        echo $data['code'] = self::CODE_AJAX_ERROR;
        exit;

    }

the problem this time, is , it totally kills the session even if you see in the function, I only killed a specific session variable because I passed the name, but then when I click any of the rows in CGridView, no data displays in side the CJuiDialog box .. so how to solve this session problem ?


Solution

The fix for this was, never use sessions when creating CJuiTabs inside a CjuiDialog box. better generate the Cjuitab from the controller, then use it as an ajax response to the view file that fires the CjuiDialog box



Answered By - sasori
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, February 10, 2022

[FIXED] Yii 2 How add a custom validation check on file upload

 February 10, 2022     php, yii, yii-components, yii2, yii2-basic-app     No comments   

Issue

I am building a CSV uploader and I want to add a custom validation function that will check the header row of the CSV file to ensure the correct columns are in place.

I am trying to put a custom validation rule in the model to do this but failing at the first hurdle.

I am getting

Setting unknown property: yii\validators\FileValidator::0

exception but as far as I can tell from the documentation this should work.

Model

/**
* UploadForm is the model behind the upload form.
*/
class UploadForm extends Model
{
/**
 * @var UploadedFile file attribute
 */
public $file;

/**
 * @return array the validation rules.
 */
public function rules()
{
    return [
        [['file'], 'file', 'extensions' => 'csv', 'checkExtensionByMimeType'=>false, 'headerCheck', 'skipOnEmpty' => false]
    ];
}

public function attributeLabels(){
    return [
        'file'=>'Select csv'
    ];
}

 function headerCheck($attribute, $params, $validato){

    $this->addError($attribute, "error");
}
}

Controller function:

     public function actionUpload()
{
    $model = new UploadForm();

    if (Yii::$app->request->isPost) {
        $model->file = UploadedFile::getInstance($model, 'file');
        $filename = $model->file->baseName . '.' . $model->file->extension;

        if ($model->file && $model->validate()) {
            $upload = $model->file->saveAs('uploads/'.$filename );

            if($upload){
                define('CSV_PATH','uploads/');
                $csv_file = CSV_PATH . $filename;
                $filecsv = file($csv_file);

                foreach($filecsv as $data){
                    $lines = explode(',',$data);
                    $t=1;
                }
            }
        }
    }

    return $this->render('csvUpload', ['model' => $model]);
}

View

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>

<?= $form->field($model, 'file')->fileInput() ?>

<button>Submit</button>

<?php ActiveForm::end() ?>

Why is headerCheck() not getting picked up as a custom validation function?


Solution

Short Answer

Your rules should be written like so:

return [
    [['file'], 'file', 'extensions' => 'csv', 'checkExtensionByMimeType'=>false, 'skipOnEmpty' => false],
    [["file"], "headerCheck"],
];

Note that your validation rule, "headerCheck", is a separate item in the array.

Long Answer

A rule's structure is like so:

[["attributes_to_validate"],"vaildatorCallback","param1"=>"value","param2"=>"value]

Note the first two items are the attributes and the callback respectively, and then after that you can specify params that should be assigned to the validator, or passed to your validator callback. These params are expected in a form where the key is the name of the property, and the value is the value to assign to the property.

In the example you provided, Yii sees that you want to utilize the "file" validator, so it creates an instance of yii\validators\FileValidator. It then sees that you want the parameter "extensions" set to "csv", so it does:yii\validators\FileValidator::$extensions = "csv"; But then, because you have included your custom validator in this part of the array, it thinks that "headerCheck" is actually a value of a property you want to assign to the validator. Because you have entered this "param" without a key, the key defaults to 0 and so Yii thinks the property you want to assign is called '0'. Thus, Yii attempts this: yii\validators\FileValidator::0 = "headerCheck";

Of course, there is no property '0' on FileValidator, and so that's where the error you're getting is coming from.



Answered By - ethan
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, February 1, 2022

[FIXED] Using Multiple Database Connection Not Working For Extension

 February 01, 2022     yii, yii-components, yii-extensions     No comments   

Issue

I am doing multiple database connection using the tutorial at http://www.yiiframework.com/wiki/544/multiple-database-connection-select-database-based-on-login-user-id-dynamic/ . The code is working fine in the model. But the problem is I am using an extension where I am using db connection using Yii::app()->db; Here I am getting exception Property "CWebApplication.dbadvert" is not defined. The controller of the extension is extended from CExtController. Please help.


Solution

I wrote the query for the extension in a model as functions. and in the CExtController created an instance of the model. Then I called those functions and everything is working fine.



Answered By - Akhilesh
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 22, 2022

[FIXED] Installing Yii composer asset plugin on composer

 January 22, 2022     composer-php, php, yii, yii-components, yii2     No comments   

Issue

I am trying to install "fxp/composer-asset-plugin:^1.2.0" on windows 32bit composer but always failed. Here is the message

Installation failed, reverting ./composer.json to its original content.

[Composer\Downloader\TransportException]
Content-Length mismatch

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] []...

Anyone know what is the problem here? Please help Thank you


Solution

You should update composer at first with

composer selfupdate

And be sure, you installing "fxp/composer-asset-plugin" globally, like official install guide says:

composer global require "fxp/composer-asset-plugin:^1.2.0"

If you are using windows, try running composer from cmd "as Administator". To clarify, if you have access to global directory, run

composer global show -s

And check output directory manually



Answered By - wormi4ok
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, January 10, 2022

[FIXED] How to send multiple settextbody yii2 send mail?

 January 10, 2022     php, sendmail, yii, yii-components, yii2     No comments   

Issue

Hi I've trying to make a form that can send email using yii/mail, the problem is I only can send one form to become text body, I've code the models like this:

     class CareerForm extends Model

    {

        public $name;

        public $email;

        public $subject;

        public $body;

        public $verifyCode;

        public $gender;

        public function rules()

        {

            return [

            [['name', 'email', 'subject', 'body','gender'], 'required'],

            ['email', 'email'],

            ['verifyCode', 'captcha'],

            ];

         }
         public function career($email)

         {

            if ($this->validate()) {

            Yii::$app->mailer->compose()

                ->setTo($email)

                ->setFrom([$this->email => $this->name])

                ->setSubject($this->subject)

                ->setTextBody($this->body)

                ->send();



            return true;

        }

        return false;

        }
    }

How can I use multiple parameters to

->setTextBody($this->body)

like

->setTextBody($this->body,$this->gender)

because in view I have several text input and radio list to send as an email, how can I do that?

My expectation on the text message will be like:

name
gender
variable 1
variable 2
variable n

SUMMARY edit = both answer is correct but I use

public function career($email)
{
    if ($this->validate()) {
        Yii::$app->mailer->compose('filename.html' ,[
            'email' => $this->email,
            'name' => $this->name,
             ])
            ->setTo($email)
            ->setFrom([$this->email => $this->name])
            ->setSubject('career')
            ->send();

        return true;
    }
    return false;}

Thanks for Ankur Garg and Pratik Karmakar


Solution

good practice to put you html in separate file and prepare mail body in that file

$body = $this->renderPartial('_mail_body.php' .[
                'gender' => $this->gender,
                'name' => $this->name,
    ]);

and the content _mail_body.php will be like this

<html>
<body>
<table cellpadding="0" cellspacing="0" align="center"  width="672px" style="font-size:24px; text-align:center;">
<tr>
    <td width="670px" align="center" style="border-left:1px solid #e0e0e0; border-right:1px solid #e0e0e0; font-size:24px; font-family:Arial, Helvetica, sans-serif; padding-top:47px;">
        <table width="608px" cellpadding="0" cellspacing="0" align="center">
            <tr>
                <td width="178px" style="font-family:Arial, Helvetica, sans-serif; font-size:14px; border-right:1px solid #e0e0e0; padding:11px;">
                    Name
                </td>
                <td width="427px" style="font-family:Arial, Helvetica, sans-serif; font-size:14px;padding:11px; color:#4e4e4e;">
                    <?php echo $name;?>
                </td>
            </tr>
            <tr>
                <td width="178px" style="font-family:Arial, Helvetica, sans-serif; font-size:14px; border-right:1px solid #e0e0e0; padding:11px;">
                    Gender
                </td>
                <td width="427px" style="font-family:Arial, Helvetica, sans-serif; font-size:14px;padding:11px; color:#4e4e4e;">
                    <?php echo $gender;?>
                </td>
            </tr>
        </table>
    </td>
</tr>
</table>
</body>
</html>


Answered By - Ankur Garg
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing