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

Saturday, March 19, 2022

[FIXED] How to just display the data on a dropdown field in yii2.0 but being able to write any option?

 March 19, 2022     php, yii, yii-extensions, yii2, yii2-advanced-app     No comments   

Issue

I´m more or less new in the Yii 2.0 framework and I´ve been having a serious problem with this situation. I want a dropdown list that shows the differents values I already used in the past but that let me write whatever I want. Like this:

enter image description here

this is the code:

$form->field($model, 'order_idorder')->widget(Select2::classname(), [
        'data' => ArrayHelper::map(Order::find()->joinWith('compartmentIdCompartment')->joinWith('hybridIdHybr')->orderBy('idorder')->all(),
            'idorder', 'fullName'),
        'options' => ['placeholder' => Yii::t('app', 'Choose Order')],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);`

The problem with this is that I need to choose one of the options in the dropdown. And I want just the information being display, without the need of actually selecting anything.


Solution

After some days searching for the answer, I finally found this:

Demo: http://www.dhtmlgoodies.com/scripts/form_widget_editable_select/form_widget_editable_select.html

Code:
http://www.dhtmlgoodies.com/index.html?whichScript=form_widget_editable_select



Answered By - Matías Joaquín Tucci
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

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

Tuesday, March 8, 2022

[FIXED] Yii: Can not Display Data in Grid View

 March 08, 2022     cgridview, php, yii, yii-extensions     No comments   

Issue

I can't list data in grid using yii framework. My controller is Sitecontroller.php, My view is list_jobseeker.php.

I got the error:

Parse error: syntax error, unexpected '*', expecting ']' in C:\wamp\www\yii_new\framework\base\CComponent.php(612) : eval()'d code on line 1

Anybody give any suggestion to correct these issue?

My controller:

 public function actionlist_jobseeker()
  {
  $session_id=Yii::app()->session['user_id']; 
  if ($session_id == "")
    {
        $this->redirect( array('/employee/site/login'));
    }
  $user_id  =$session_id;
  $items = Yii::app()->db->createCommand()
     ->select('*')
     ->from('job_seeker_profile s')
     ->join('job_profile j','s.user_id = j.user_id')
     ->order('s.id')
     ->queryAll();
     $this->render('list_jobseeker',array('items' =>$items));
}

My view page - list_jobseeker.php

<h1>View Jobseeker</h1>

<div class="flash-success">

</div>

<div class="form">
<?php
 $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'rates-phase-grid',
   'htmlOptions' => array('class' => 'table table-striped table-bordered table-hover'),
    'dataProvider'=>new CArrayDataProvider($items),
    'columns' => array(
        array(
            'name' => 'Name',
            'type' => 'raw',
            'value' => 'CHtml::encode($data[*]->name)',
            'htmlOptions' => array('style'=>'width:90px;','class'=>'zzz'),

     ),
        array(
            'name' => 'Email',
            'type' => 'raw',
            'value' => 'CHtml::encode($data[*]->email)',
            'htmlOptions' => array('style'=>'width:250px;','class'=>'zzz')

        ),
        array(
            'name' => 'Password',
            'type' => 'raw',
            'value' => 'CHtml::encode($data[*]->password)',
            'htmlOptions' => array('style'=>'width:90px;','class'=>'zzz')
        ),
        array(
            'name' => 'Contact No',
            'type' => 'raw',
            'value' => 'CHtml::encode($data[*]->contact_no)',
            'htmlOptions' => array('style'=>'width:40px;','class'=>'zzz')

        ),
         array(
            'name' => 'Gender',
            'type' => 'raw',
            'value' => 'CHtml::encode($data[*]->gender)',
            'htmlOptions' => array('style'=>'width:40px;','class'=>'zzz')

        ),


        array(
            'class' =>'CButtonColumn',
            'deleteConfirmation'=>'Are you sure you want to delte this item?',
            'template'=>'{update}{delete}',

            'buttons' =>array('update'=>array(

             'label'=>'edit',
     'url'=>'Yii::app()->controller->createUrl("UpdateJob",array("id"=>$data["id"]))',

                ),
             'delete'=>array('label'=>'delete',
     'url'=>'Yii::app()->controller->createUrl("DeleteJob",array("id"=>$data["id"]))'),

                )
            )
          ),
));
?>

</tbody>


Solution

change all the [*]

 $data[*]->name

to match columns

$data["name"]


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

[FIXED] Yii Framework with Twitter Bootstrap not loading

 March 08, 2022     php, twitter-bootstrap, yii, yii-extensions     No comments   

Issue

I'm new to Yii and wanted to implement the Twitter Bootstrap extension, I have followed cniska but apparently I'm doing something wrong.

When I load the page in the browser with extension code, the images/effects don't load.

In my html page I got this simple toggle button found here.

  <?php $this->widget('bootstrap.widgets.TbButton', array(
      'buttonType'=>'button',
      'type'=>'primary',
      'label'=>'Toggle me',
      'toggle'=>true,
  )); ?>

The result with this is as if I have just done a simple HTML button with no classes applied to it, a 'bare' sytle button, so do speak.

My config/main.php:

Yii::setPathOfAlias('bootstrap', dirname(__FILE__).'/../extensions/bootstrap');

return array(
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'Test App',

// preloading 'log' component
'preload'=>array('log'),

// autoloading model and component classes
'import'=>array(
    'application.models.*',
    'application.components.*',
),

'modules'=>array(
    'gii'=>array(
        'class'=>'system.gii.GiiModule',
        'password'=>'<password>',
        'ipFilters'=>array('127.0.0.1','::1'),
    ),
),

'components'=>array(
    'user'=>array(
      'allowAutoLogin'=>true,
  ),
  'bootstrap'=>array(
    'class'=>'bootstrap.components.Bootstrap',
   ),

  'theme'=>'bootstrap', -// requires you to copy the theme under your themes directory
    'modules'=>array(
        'gii'=>array(
            'generatorPaths'=>array(
                'bootstrap.gii',
            ),
        ),
    ),

    'db'=>array(
        'connectionString' => 'mysql:host=localhost;dbname=<bdname>',
        'emulatePrepare' => true,
        'username' => '<bd username>',
        'password' => '<bd password>',
        'charset' => 'utf8',
    ),

    'errorHandler'=>array(
        'errorAction'=>'site/error',
    ),
    'log'=>array(
        'class'=>'CLogRouter',
        'routes'=>array(
            array(
                'class'=>'CFileLogRoute',
                'levels'=>'error, warning',
            ),

        ),
    ),
),

// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
    // this is used in contact page
    'adminEmail'=>'webmaster@example.com',
),
);

I also believe I have the latest versions as I downloaded Yii's framework this week as well as the extension. Any tips?

Thanks in advance


Solution

you need to register css and js files, in the main lay out add this line

Yii::app()->bootstrap->register();


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

[FIXED] how to add downloaded extension to yii 1.11?

 March 08, 2022     yii, yii-extensions     No comments   

Issue

can any one tell me how to add extension to my yii? i googled and downloaded Bootstrap 0.9.8 extension and followed the steps described in it but it not working for me. am using Ubuntu , can you please explain step by step am just beginner.

and i don't know how to add extension to yii


Solution

@raghulrnair, assuming that you have some basic knowledge of yii. If not then read the Yii doc http://www.yiiframework.com/doc/guide/1.1/en/quickstart.what-is-yii

explaining it in conjunction with http://www.cniska.net/yii-bootstrap/setup.html#setup


1) Download the bootstrap extension, and unzip it into "protected/extensions/bootstrap". Once this step is done, then you must see following folders.

protected/extensions/bootstrap/assets
protected/extensions/bootstrap/gii
protected/extensions/bootstrap/components
protected/extensions/bootstrap/lib
protected/extensions/bootstrap/widgets

2) "Application Configuration" plays important role when installing extensions. By default this configuration will be in a php file (i.e protected/config/main.php )


3) Simply edit that file and search for "preload". if found then add "bootstrap" to that array

'preload'=>array( 'log', 'bootstrap'),

if not found,

'preload'=>array('bootstrap'),

4) Now Search for "components", then add bootstrap to that array like below

'components'=>array(
    .....
    'bootstrap'=>array(
        'class'=>'ext.bootstrap.components.Bootstrap',
    ),
),

5) If you want to auto generate bootstrap code ( crud, views, models etc.. ) follow this step. ( This is optional if you don't want ) add bootstrap to gii in 'modules' configuration.

'modules'=>array(
    .....
    'gii'=>array(
        .....
        'generatorPaths'=>array(
            'bootstrap.gii',
        ),
    ),
),

6) Your configuration is done. SETUP IS DONE.


7) Start coding using bootstrap in your views or use gii to generate code.

Many examples are given at http://www.cniska.net/yii-bootstrap/

one example, If you want to display a menu, then edit the view file and add this code.

<?php $this->widget('bootstrap.widgets.TbMenu', array(
    'type'=>'tabs', // '', 'tabs', 'pills' (or 'list')
    'stacked'=>false, // whether this is a stacked menu
    'items'=>array(
        array('label'=>'Home', 'url'=>'#', 'active'=>true),
        array('label'=>'Profile', 'url'=>'#'),
        array('label'=>'Messages', 'url'=>'#'),
    ),
)); ?>

8) Thats it.



Answered By - SuVeRa
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

Monday, February 28, 2022

[FIXED] Post inside controller not loading into model in Yii2

 February 28, 2022     yii, yii-extensions, yii-form, yii2, yii2-advanced-app     No comments   

Issue

When I want to get the variable from the form the post action doesn't load .

This is my view:

<?php
        $form = ActiveForm::begin();
        ?>
            <div class="form-group">
                <input type="text" name="username" placeholder="FullName">

                <?= Html::a(Yii::t('app', 'Start'), ['start', 'link' => $model->link], ['type' => 'button','class' => 'btn btn-primary btn-round']) ?>
            </div>

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

This is my controller:

if ($model->load(Yii::$app->request->post())){
    exit(var_dump('everything is ok'));
}else {
    exit(var_dump('nothing is right'));

}

The result is 'nothing is right'.


Solution

Finally I find the solution

<?php
$form = ActiveForm::begin(
    [
        'action' => 'start',
    ]
);
?>
<div class="form-group">
    <input type="text" name="username" placeholder="FullName">
    <?= Html::a('submit', Url::to(['start', 'link' => $model->link]), ['data-method' => 'POST']) ?>
</div>

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

thank you for all



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

Sunday, February 27, 2022

[FIXED] How to upgrade Yii 1.x to Yii 2.0

 February 27, 2022     yii, yii-extensions, yii2, yii2-advanced-app, yii2-basic-app     No comments   

Issue

How to upgrade Yii 1.x version to Yii 2.0 latest release version? I am using ubuntu OS , Process to updating my old Yii to new Yii release version 2.0?


Solution

The Yii2 guide has excellent documentation in this regard see Upgrade from v1

I recently migrated couple of moderately complex applications from Yii 1.x to Yii 2.0. There are two ways to go about it , either you can run Yii 1.x and Yii 2 at the same time see using-yii-2-with-yii-1. Then migrate part by part, while it is possible it was quite bit of pain, like trying to rebuild the second floor while living on the third.

Alternatively you can rewrite the entire application bottom up with the exact same functionality, I found this to be much more efficient, significant code could be reused with only minor modifications, also that gave opportunity to tweak the design without changing functionality.

The important thing is to ensure the exposed API ( i.e. the frontend / UI / functionality) remains the same. It is always tempting to update functionality or change features during a rewrite, however if you stick to strictly reimplementing everything for Yii2 then consider changing your API, your migration will be smoother.



Answered By - Manquer
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

Wednesday, January 26, 2022

[FIXED] How to call yii user login in restfullyii?

 January 26, 2022     yii, yii-extensions     No comments   

Issue

I'm using yii user and rights for creating rbac in yii. i also uses restfullyii for Restfull services.

Now i need to merge the yii user and restfullyii, so that when i submit username and password in the client side(frontend), i should pass it through restfullyii to yii user and checks for the login credentials and return the appropriate message to the client.

When i tried the url with the Chrome Advanced Rest Client Application extension, i get the following error.

  <h2>Error 404</h2>

  <div class="error">
   Unable to resolve the request &quot;user/REST.POST&quot;.</div></div><!-- content -->

How to merge yii user and restfullyii extensions.


Solution

Your routes are wrong that's why you are not able to resolv any page. check on configuration main.php your restfull yii routes first. then try to get into the app using domain.me/index.php/api/



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

[FIXED] masonry + isotope + imagesLoaded not defined yii

 January 26, 2022     javascript, jquery-isotope, masonry, yii, yii-extensions     No comments   

Issue

Hello i´m new to web development. I´m struggling with a JS function using Yii 1.1: isotope-jquery. Trying to show a masonry image gallery with infinite scrolling. If i leave it as it is it works, but when using images they get all overlapped at the end. i should use imagesLoaded, but applying it´s being a pain...

Original code:

 $defaultCallback="
        function( newElements ) { 
        /* hide new items while they are loading*/ 
        var newElems = jQuery( newElements ); 
        \$isoContainer.isotope( 'appended', newElems, true );
        {$this->infiniteCallback}
        }";

Modified:

function( newElements ) { 
        /* hide new items while they are loading*/ 
        var newElems = jQuery( newElements );
        \$newElems.imagesLoaded(function(){         
            \$isoContainer.masonry( 'insert', newElems);
        });
        {$this->infiniteCallback}
        }"

Error on browser console:

["math:", 222, 2853] jquery.infinitescroll.js:171
["math:", 0, 2853] jquery.infinitescroll.js:171
["heading into ajax", Array[2]] jquery.infinitescroll.js:171
["Using HTML via .load() method"] jquery.infinitescroll.js:171
["contentSelector", div.items.isotope] jquery.infinitescroll.js:171
Uncaught ReferenceError: $newElems is not defined index.php?r=products:112(anonymous function) index.php?r=products:112opts.callback jquery.infinitescroll.js:159infscr_loadcallback jquery.infinitescroll.js:327infscr_ajax_callback jquery.infinitescroll.js:501jQuery.extend.each jquery.js:595jQuery.fn.jQuery.each jquery.js:241jQuery.ajax.complete jquery.js:7465fire jquery.js:974self.fireWith jquery.js:1084done jquery.js:7818callback

i´ve tried several things, defining the var inside, passing parameters, but i cannot make it work...

probably it´s a newbie issue...

thanks for your help


Solution

So this is the solution, and works like a charm!

function( newElements ) { 
        /* hide new items while they are loading*/ 
        var newElems = jQuery( newElements );
        \$isoContainer.imagesLoaded(function(){         
        \$isoContainer.isotope( 'appended', newElems,true);
        });

thanks @Macsupport



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

Monday, January 24, 2022

[FIXED] Yii throwing exception

 January 24, 2022     ckeditor, yii, yii-extensions     No comments   

Issue

An app that seems fine in local throwing me following exception on live:

CException

Alias "application.extensions.TheCKEditor.theCKEditorWidget" is invalid. 
Make sure it points to an existing PHP file and the file is readable. 

Code:

   <?php $this->widget('application.extensions.TheCKEditor.theCKEditorWidget',array(
        'model'=>$model,                # Data-Model (form model)
        'attribute'=>'wordMeaning',         # Attribute in the Data-Model
        'height'=>'400px',
        'width'=>'100%',
        'toolbarSet'=>'Full',          # EXISTING(!) Toolbar (see: ckeditor.js)
        'ckeditor'=>Yii::app()->basePath.'/../assets/ckeditor3.6.5/ckeditor.php',
                                        # Path to ckeditor.php
        'ckBasePath'=>Yii::app()->baseUrl.'/assets/ckeditor3.6.5/',
                                        # Relative Path to the Editor (from Web-Root)
        //'css' => Yii::app()->baseUrl.'/css/index.css',
                                        # Additional Parameters
    ) ); ?>  

Any idea ?


Solution

Check path ./protected/extensions/TheCKEditor/theCKEditorWidget. Also check case of path TheCKEditor



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

Thursday, January 20, 2022

[FIXED] Ajax button in Cgridview doesn't work

 January 20, 2022     php, yii, yii-extensions     No comments   

Issue

I have CGriview with ajax button,but when i click on the button, the page refreshed and doesnt send ajax parameter to my action,my code is like this:

enter code here
array(
                        'class'=>'CButtonColumn',
                        'template'=>'{reset}',
                        'buttons'=>array(
                            'reset'=>array(
                                'label'=>'reset',
                         'url'=>'Yii::app()->controller->createUrl("place/viewHallModal/",array("row"=>"1"))',
                                'options'=>array(
                                    'class' => 'btn',
                                        'ajax'=>array(
                                            'type'=>'post',
                                            'url'=>'js:$(this).attr("href")',
                                            'update'=>'#section-update',
                                            'success' =>'js:function(data) {alert("suc");}'
                                        )), 
                             ),
                        ),

                ),

Solution

I haven't 50+ reputation for commenting, so I can help you only with answering to the question.

In jQuery you can write this ajax function like this

...
$.ajax({
   type: 'post',
   url: 'your_url_will_goes_here',
   cache: false, // or true
   data: {
      'your_data': $variable,
      'your_data1': $variable1,
   },
   success: function(data){
      alert("success !");
});
....

but I couldn't see your data ajax function. So which data you want to pass to your action?



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

[FIXED] Skip the first line of a CSV file in Yii2

 January 20, 2022     csv, phpmyadmin, yii-extensions, yii2     No comments   

Issue

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

    if($model->load(Yii::$app->request->post())){
        $file = UploadedFile::getInstance($model,'file');
        $filename = 'Data.'.$file->extension;
        $upload = $file->saveAs('uploads/'.$filename);
        if($upload){
            define('CSV_PATH','uploads/');
            $csv_file = CSV_PATH . $filename;
            $filecsv = file($csv_file);
            print_r($filecsv);
            foreach($filecsv as $data){

                $modelnew = new Customer1();
                $hasil = explode(",",$data);
                $nim = $hasil[0];
                $nama = $hasil[1];
                $jurusan = $hasil[2];
                $angkatan = $hasil[3];

                $modelnew->username = $nim;
                $modelnew->firstname = $nama;
                $modelnew->lastname = $jurusan;
                $modelnew->password = $angkatan;

                $modelnew->save();
            }
            unlink('uploads/'.$filename);
            return $this->redirect(['site/index']);
        }
    }else{
        return $this->render('upload',['model'=>$model]);
    }
}

This is my CSV data

user1,name,pass,info user2,name,pass,info etc..,

So I want to skip Bold content and proceed my execution.


Solution

You could shift the array

$filecsvtemp = file($csv_file);
$filecsv = array_shift($filecsvtemp );

in this way the first row of the array is not present in the resulting array

otherwise use a counter

        $cnt = 0;
        $filecsv = file($csv_file);
        print_r($filecsv);
        foreach($filecsv as $data){

            if ($cnt!=0){
              $modelnew = new Customer1();
              $hasil = explode(",",$data);
              $nim = $hasil[0];
              $nama = $hasil[1];
              $jurusan = $hasil[2];
              $angkatan = $hasil[3];

              $modelnew->username = $nim;
              $modelnew->firstname = $nama;
              $modelnew->lastname = $jurusan;
              $modelnew->password = $angkatan;

              $modelnew->save();

            }
            $cnt++;
        }


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

Wednesday, January 12, 2022

[FIXED] Extension YiiMaill (Swiftmailer) can't send SMTP from gmail

 January 12, 2022     email, php, swiftmailer, yii, yii-extensions     No comments   

Issue

I've a PHP application that's running with Yii Framework and it's using the YiiMail extension that's is based in Swiftmailer.

My application was working perfectly yesterday, but today the follow error was launched:

fsockopen(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

My Yii app config:

'mail' => 
  array('class' => 'application.extensions.yii-mail.YiiMail',
        'transportType' => 'smtp', 
        'transportOptions' => array(
             'host' => 'smtp.gmail.com', 
             'username' => '**@gmail.com', 
             'password' => '***', 
             'port' => '465', 
             'encryption'=>'tls' ), 
         'viewPath' => 'application.views.mail', 
         'logging' =>false, 
         'dryRun' => false
 )

ANSWER: A FAST SOLUTION

My app is running in Windows, so I did a fast configuration to solve this problem at moment.

I did a configuration with sendmail and it enable into my php.ini file.

Ps: The main problem is if you have many apps running in the same php. How don't this problem to me, it's is stand alone application, I just did.

Something like this:

sendmail.ini

[sendmail]
smtp_server=smtp.gmail.com
smtp_port = 587
#default_domain = gmail.com it's is not necessary
auth_username= your gmail@gmail.com
auth_password=your password

php.ini

[mail function]
sendmail_path = "path to sendmail installation"
SMTP = smtp.gmail.com
smtp_port = 587

Solution

If your current config was previously working, then suddenly stopped. Consider looking into the following:

  • Generating an APP password for a gmail account

  • Enabling Less SecureApps settings for your gmail account

I have encountered a similar problem before, enabling Less Secure Apps, then when I set 2 Step Verification for my google account, it stopped working.

Then generating an APP password, did the trick!



Answered By - Mark Ryan Orosa
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Yii2 role management with rbac and database storage

 January 12, 2022     php, rbac, yii, yii-extensions, yii2     No comments   

Issue

I want to learn Yii2 membership and use Yii to store and retrieve roles using a database.

I have read Security Authorization and How to add role to user? and Does Anyone Have A Working Example Of Rbac? and also try using the yii2-admin extension and tried to understand how Yii manages user roles but I can't find any working samples or simple step by step examples.

Please guide me and tell me the simplest solution.


Solution

Implementing a role based access control is a very easy process and you can even load your roles from the database if you want.

Step1: Creating necessary tables in the database [ You can also apply migrations with console command yii migrate instead of step 1 ]

The first step is to create necessary tables in the database.Below is the sql you need to run in the database.

drop table if exists `auth_assignment`;
drop table if exists `auth_item_child`;
drop table if exists `auth_item`;
drop table if exists `auth_rule`;

create table `auth_rule`
(
`name` varchar(64) not null,
`data` text,
`created_at` integer,
`updated_at` integer,
    primary key (`name`)
) engine InnoDB;

create table `auth_item`
(
`name` varchar(64) not null,
`type` integer not null,
`description` text,
`rule_name` varchar(64),
`data` text,
`created_at` integer,
`updated_at` integer,
primary key (`name`),
foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade,
key `type` (`type`)
) engine InnoDB;

create table `auth_item_child`
(
`parent` varchar(64) not null,
`child` varchar(64) not null,
primary key (`parent`, `child`),
foreign key (`parent`) references `auth_item` (`name`) on delete cascade on update cascade,
foreign key (`child`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

create table `auth_assignment`
(
`item_name` varchar(64) not null,
`user_id` varchar(64) not null,
`created_at` integer,
primary key (`item_name`, `user_id`),
foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

Step2: Setting up the config file

Now you can set up the config file to use the authmanager as DbManager. This is done by adding the following lines to the components section of your config file

     'authManager' => [
                           'class' => 'yii\rbac\DbManager',
                           'defaultRoles' => ['guest'],
          ],

Step3: Adding and assigning roles.

Now you can add roles by simply writing the following code to your corresponding controller.

    use yii\rbac\DbManager;
    $r=new DbManager;
    $r->init();
    $test = $r->createRole('test');
    $r->add($test);

And you can assign it to the users by

    $r->assign($test, 2);

http://www.yiiframework.com/doc-2.0/guide-security-authorization.html



Answered By - Dency G B
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to resize image by imagine extension in yii2

 January 12, 2022     yii, yii-extensions, yii2, yii2-advanced-app     No comments   

Issue

I use the bellow function to resize images after upload to show on my post. but it works just for images larger than 500px 300px. when I upload image smaller than this size, my website images row breaks down.

use yii\imagine\Image;    
public function upload() {
            $this->pictureFile->saveAs('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);

            Image::thumbnail('../files/upload/' . $this->pictureFile, 500, 300)
                    ->save('../files/upload/thumbnail-500x300/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension, 
                            ['quality' => 70]);
            unlink('../files/upload/' . $this->pictureFile->baseName . '.'  . $this->pictureFile->extension);
        }

Solution

Use resize method as below

 use yii\imagine\Image;  
 use Imagine\Image\Box;  

 public function upload() {
        $this->pictureFile->saveAs('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);

        Image::thumbnail('../files/upload/' . $this->pictureFile, 500, 300)
                ->resize(new Box(500,300))
                ->save('../files/upload/thumbnail-500x300/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension, 
                        ['quality' => 70]);
        unlink('../files/upload/' . $this->pictureFile->baseName . '.'  . $this->pictureFile->extension);
    }


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

Monday, January 10, 2022

[FIXED] Yii: why my default index of controller is not working?

 January 10, 2022     php, rights, yii, yii-extensions     No comments   

Issue

I am a Yiibie, stuck in a problem. I have installed yii users and rights. It gives me error whenever I try to run localhost/webapp/table it gives an error which is "Error 404 The system is unable to find the requested action "list" , but when I try to run localhost/webapp/table/index it shows me the view of index action which is working fine. Here is my config/main.php

<?php

// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');

// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.

return array(
     'theme' => 'bootstrap',
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
    'name'=>'emergency response system',

    // preloading 'log' component
    'preload'=>array('log'),
'aliases' => array(
        'bootstrap' => 'ext.bootstrap'),
    // autoloading model and component classes
    'import'=>array(
        'application.models.*',
        'application.components.*',
         'bootstrap.behaviors.*',
                'bootstrap.helpers.*',
                'bootstrap.widgets.*',
                'application.modules.user.models.*',
                'application.modules.user.components.*',
                'application.modules.rights.*',
                'application.modules.rights.components.*',
    ),

    'modules'=>array(
        // uncomment the following to enable the Gii tool

        'gii'=>array(
            'class'=>'system.gii.GiiModule',
            'password'=>'ers',
                     'generatorPaths' => array(
                'bootstrap.gii', ),
            // If removed, Gii defaults to localhost only. Edit carefully to taste.
            'ipFilters'=>array('127.0.0.1','::1'),
        ),
            'user' => array(
            'tableUsers' => 'user',
            'tableProfiles' => 'profiles',
            'tableProfileFields' => 'profiles_fields',
                # encrypting method (php hash function)
                'hash' => 'md5',

                # send activation email
                'sendActivationMail' => true,

                # allow access for non-activated users
                'loginNotActiv' => false,

                # activate user on registration (only sendActivationMail = false)
                'activeAfterRegister' => false,

                # automatically login from registration
                'autoLogin' => true,

                # registration path
               'registrationUrl' => array('/user/registration'),

                # recovery password path
                'recoveryUrl' => array('/user/recovery'),

                # login form path
                'loginUrl' => array('/user/login'),

                # page after login
                'returnUrl' => array('/user/profile'),

               # page after logout
               'returnLogoutUrl' => array('/user/login'),


    ),
             'rights'=>array(
             'install'=>true,
                 'superuserName'=>'Admin', // Name of the role with super user privileges. 
               'authenticatedName'=>'Authenticated',  // Name of the authenticated user role. 
               'userIdColumn'=>'id', // Name of the user id column in the database. 
               'userNameColumn'=>'username',  // Name of the user name column in the database. 
               'enableBizRule'=>true,  // Whether to enable authorization item business rules. 
               'enableBizRuleData'=>true,   // Whether to enable data for business rules. 
               'displayDescription'=>true,  // Whether to use item description instead of name. 
               'flashSuccessKey'=>'RightsSuccess', // Key to use for setting success flash messages. 
               'flashErrorKey'=>'RightsError', // Key to use for setting error flash messages. 
               'baseUrl'=>'/rights', // Base URL for Rights. Change if module is nested. 
               'layout'=>'rights.views.layouts.main',  // Layout to use for displaying Rights. 
               'appLayout'=>'application.views.layouts.main', // Application layout. 
               'cssFile'=>'rights.css', // Style sheet file to use for Rights. 
               'install'=>false,  // Whether to enable installer. 
               'debug'=>false, 
        ),
            ),

    // application components
    'components'=>array(

        'user'=>array(
                    'class'=>'RWebUser',
            // enable cookie-based authentication
            'allowAutoLogin'=>true,
                    'loginUrl'=>array('/user/login'),
        ),
            'authManager'=>array(
                'class'=>'RDbAuthManager',
                'connectionID'=>'db',
                'defaultRoles'=>array('Authenticated', 'Guest'),

                'itemTable'=>'authitem',
                'itemChildTable'=>'authitemchild',
                'assignmentTable'=>'authassignment',
                'rightsTable'=>'rights',
        ),


        'bootstrap' => array(
            'class' => 'bootstrap.components.BsApi',),

        // uncomment the following to enable URLs in path-format

        'urlManager'=>array(
            'urlFormat'=>'path',
                     'showScriptName'=>false,
            'rules'=>array(
                 '<controller:\w+>'=>'<controller>/list',
                '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
                '<controller:\w+>/<id:\d+>/<title>'=>'<controller>/view',
                '<controller:\w+>/<id:\d+>'=>'<controller>/view',
            ),
        ),


        // database settings are configured in database.php
//      'db'=>require(dirname(__FILE__).'/database.php'),

        'db'=>array(
            'connectionString' => 'mysql:host=localhost;dbname=response_system',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ),

        'errorHandler'=>array(
            // use 'site/error' action to display errors
            'errorAction'=>'site/error',
        ),

        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'error, warning',
                ),
                // uncomment the following to show log messages on web pages

                array(
                    'class'=>'CWebLogRoute',
                ),

            ),
        ),

    ),

    // application-level parameters that can be accessed
    // using Yii::app()->params['paramName']
    'params'=>array(
        // this is used in contact page
        'adminEmail'=>'webmaster@example.com',
    ),

);

and here is my model file

<?php

/**
 * This is the model class for table "story".
 *
 * The followings are the available columns in table 'story':
 * @property integer $id
 * @property string $title
 * @property string $story
 *
 * The followings are the available model relations:
 * @property UserWriteStory[] $userWriteStories
 */
class Story extends CActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Story the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'story';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, story', 'required'),
            array('title', 'length', 'max'=>100),
            array('story', 'length', 'max'=>1000),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, title, story', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'userWriteStories' => array(self::HAS_MANY, 'UserWriteStory', 'story_story_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'title' => 'Title',
            'story' => 'Story',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('title',$this->title,true);
        $criteria->compare('story',$this->story,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }
}

and this is my related controller.

<?php

class StoryController extends RController
{
    /**
    * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
    * using two-column layout. See 'protected/views/layouts/column2.php'.
    */
    public $layout='//layouts/admin';

    /**
    * @return array action filters
    */
    public function filters()
    {
        return array(
//          'accessControl', // perform access control for CRUD operations
//          'postOnly + delete', // we only allow deletion via POST request
                    'rights',
        );
    }

    /**
    * Specifies the access control rules.
    * This method is used by the 'accessControl' filter.
    * @return array access control rules
    */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    /**
    * Displays a particular model.
    * @param integer $id the ID of the model to be displayed
    */
    public function actionView($id)
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }

    /**
    * Creates a new model.
    * If creation is successful, the browser will be redirected to the 'view' page.
    */
    public function actionCreate()
    {
        $model=new Story;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Story']))
        {
            $model->attributes=$_POST['Story'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
        'model'=>$model,
        ));
    }

    /**
    * Updates a particular model.
    * If update is successful, the browser will be redirected to the 'view' page.
    * @param integer $id the ID of the model to be updated
    */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Story']))
        {
            $model->attributes=$_POST['Story'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }

    /**
    * Deletes a particular model.
    * If deletion is successful, the browser will be redirected to the 'admin' page.
    * @param integer $id the ID of the model to be deleted
    */
    public function actionDelete($id)
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
    * Lists all models.
    */
    public function actionIndex()
    {
        $dataProvider=new CActiveDataProvider('Story');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }

    /**
    * Manages all models.
    */
    public function actionAdmin()
    {
        $model=new Story('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Story']))
            $model->attributes=$_GET['Story'];

        $this->render('admin',array(
            'model'=>$model,
        ));
    }

    /**
    * Returns the data model based on the primary key given in the GET variable.
    * If the data model is not found, an HTTP exception will be raised.
    * @param integer $id the ID of the model to be loaded
    * @return Story the loaded model
    * @throws CHttpException
    */
    public function loadModel($id)
    {
        $model=Story::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
    * Performs the AJAX validation.
    * @param Story $model the model to be validated
    */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='story-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}

Solution

In your main.php of config file, comment out this line:

<controller:\w+>'=>'<controller>/list


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

Thursday, December 30, 2021

[FIXED] model->attributes in Yii2 always has NULL value

 December 30, 2021     php, yii, yii-extensions, yii2     No comments   

Issue

I have one temporary model as viewModel. In my CRUD actions (for example actionCreate) I want to get this viewModel data and assign that to a ActiveRecord model. I used below code but my model object atrribute always show NULL value for attributes:

$model = new _Users();
if ($model->load(Yii::$app->request->post())) {
    Yii::info($model->attributes,'test'); // NULL
    $attributesValue =[
            'title' => $_POST['_Users']['title'],
            'type' => $_POST['_Users']['type'],
        ];
    $model->attributes = $attributesValue;
    Yii::info($model->attributes,'test'); // NULL

    $dbModel = new Users();
    $dbModel->title = $model->title;
    $dbModel->type = $model->type . ' CYC'; // CYC is static type code
    Yii::info($dbModel->attributes,'test'); // NULL

    if ($dbModel->save()) {
            return $this->redirect(['view', 'id' => $dbModel->id]); // Page redirect to blank page
        }
}
else {
        return $this->render('create', [
            'model' => $model,
        ]);
}

I think $model->load(Yii::$app->request->post()) not working and object attribute being NULL. Is it Yii2 bug or my code is incorrect??


Solution

If there is no rule for your attribute the $model->load() will ignore those not in the rules of the model.

Add your attributes to the rules function

public function rules()
{
    return [
        ...
        [['attribute_name'], 'type'],
        ...
    ];
}


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

Tuesday, December 28, 2021

[FIXED] How can I disable yii-debug-toolbar on a specific view?

 December 28, 2021     debugging, php, yii, yii-extensions     No comments   

Issue

How can I disable yii-debug-toolbar on a specific view especially on partial rendered views?

Is this possible?

p.s. Yii-debug-toolbar does unfortunately not exist as a tag below.


Solution

Put this in your layout or view file:

if (class_exists('yii\debug\Module')) {
    $this->off(\yii\web\View::EVENT_END_BODY, [\yii\debug\Module::getInstance(), 'renderToolbar']);
}

This removes the callback that renders the toolbar from the event that runs at the end of the layout, where you have $this->endBody().



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

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