EzDevInfo.com

yii interview questions

Top yii frequently asked interview questions

Yii: Render action using different layout than controller's layout

In Yii, is there a way to render a single action using a different layout than that defined for the controller? I have an action that I would like to format differently from the rest, and it's not clear from the documentation if that's possible.


Source: (StackOverflow)

URL in yii2 gridview

In yii2 gridview, I have this code:

<?php echo GridView::widget([
  'dataProvider' => $dataProvider,
  'filterModel' => $searchModel,
  'columns' => [
    ['class' => 'yii\grid\SerialColumn'],
    [
           'label'=>'bla',
           'format' => 'url',
       'value'=>function ($data) {
            return Html::url('site/index');
        },
    ],
    ['class' => 'yii\grid\ActionColumn'],
],
]); ?>

In grid view, text is being generated with url address.

/academia-new/advanced/admin/site/index

Url is working fine, but how can I set a text for link?


Source: (StackOverflow)

Advertisements

A CMS based on Yii? [closed]

i've been with Yii for a few months and before I use main CodeIgniter, SilverStripe in my projects. Does anyone know a good Yii based CMS such as SilverStripe based on Sapphire or EE based on CodeIgniter ?

My experience is working with Yii is much more easier and straightforward assuming you are good OOP coder but Yii is still young and there are not lot of samples that I can put together quickly for a real prodcution project.

A couple of YII based CMS I spotted at do not look really promising or maybe at a very early stage such as dotPlant, Web3CMS.


Source: (StackOverflow)

PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django

I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Although I have pretty good experience with python and PHP but I have no idea how to use either of the framework. We have plenty of time to experiment and learn one of the above frameworks.Could you please specify which one would be preferred for such a scenario considering speed, features, and security of the site.

Thanks, niting


Source: (StackOverflow)

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

I'm trying to send a Get request by ajax and output json data that is returned by server in html.

But, I got this error.

Uncaught TypeError: Cannot use 'in' operator to search for '324' in 
[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]

This is my code that sends a Get request to php file by ajax. When I use $.each method, it get the error that I showed in the above.

parentCat.on('change', function(e){
    parentCatId = $(this).val();

    $.get(
        'index.php?r=admin/post/ajax',
        {"parentCatId":parentCatId},
        function(data){                     
            $.each(data, function(key, value){
                console.log(key + ":" + value)
            })
        }
    )

})

This is my PHP code that returns query result in json format.

public function actionAjax(){

    $parentCatId=$_GET['parentCatId'];

        $catData = Category::getTargetCategoryData($parentCatId);

        echo CJSON::encode($catData);
        Yii::app()->end();

}

json data outputted by this php is like this.

[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]

Anyone knows how to fix this problem?

Please help me out. Thanks in advance :)


Source: (StackOverflow)

Yii framework: Controller/Action url & parameters

In my application , I have ApiController with actionUsers, So in YII the path becomes api/users. Now in order to get certain users info , I use the following path api/users/id/10 where 10 is the userID and id part of the path is basically a GET parameter (api/users?id=10).

Is there any way to do the same thing without id part of the path, i.e. I want my path to look like api/users/10?

Thank you!


Source: (StackOverflow)

OpenId support for Yii

I want to play with OpenID support in Yii.

After researching for possible plugins, I found these two. One for OpenidSelector and one for LightOpenId

http://www.yiiframework.com/extension/simpleopenidselector/

http://www.yiiframework.com/extension/loid

Are these the right extensions to use in Yii for OpenId support? Anything else? And I would like to get some guide line on what to do with these extensions if they are correct.

This is what I think I need to do beside installing them as per instructions on the page.

  1. Create OpenIdUserIdentity extends CUserIdentity and put the authenticate() code there
  2. Create a login page and put the simpleopenidselector code in a view.
  3. Create a actionOpenIdLogin methon in siteController

then I am kind of lost as I don't understand the Usage sample in Loid and I am not sure how to do (1) and (3) above.

Please let me know if I am on the right track and possibly provide some guidance. Thanks.


Source: (StackOverflow)

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

I'm developing Web app in Yii framework. I need use AJAX in my some pages. So, when I clicked the button (which I loaded them with AJAX the Google Chrome Developer Tools browser says me:

Failed to load resource: net::ERR_CACHE_MISS

How to solve this problem?

P.S: I know it's duplicate question, but I couldn't find the solution for my problem. In some posts users said use Ctrl+Shift+N and try it. it will works. and/or somebody said: reload pages with Ctrl+F5 because Google Chrome likes cache everything.. So, I read all of these topics and applied all solution tips. But there were not help. Please help me...

And also in other browsers some pages not working properly. But only the Google Chrome Developer Tools returns me the stupid error.

Best.


Source: (StackOverflow)

Yii multi page form wizard best practice

I am trying to build a multi-page form with Yii, but am quite new to PHP and Yii and am wondering what the best practice is for writing a multi page form. So far, what I am planning to do is to add a hidden field named 'step' which contains the current step the user is on in the form (the form is broken into 3 steps/pages). So with that in mind, this is how I plan to handle the user clicking on previous/next buttons in the Controller:

public function actionCreate()
 {
  $userModel = new User;

  $data['activityModel'] = $activityModel; 
  $data['userModel'] = $userModel; 

  if (!empty($_POST['step']))
  {
   switch $_POST['step']:
    case '1':
     $this->render('create_step1', $data);
     break;

    case '2':
     $this->render('create_step2', $data);
     break;

  }else
  {
   $this->render('create_step1', $data);
  }
 }

Does this approach make sense? Or am I way off base and there is a much better and more optimized way of doing this in Yii/PHP?

Thanks!


Source: (StackOverflow)

Yii2 how does search() in SearchModel work?

Please can someone explain how the search method in a Yii2 SearchModel works? I generated it using Gii. Here it is:

public function search($params){
    $query = MyModel::find();
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }

    $this->addCondition($query, 'att1');
    $this->addCondition($query, 'att1', true);
    $this->addCondition($query, 'att2');
    $this->addCondition($query, 'att2', true);

    return $dataProvider;
}

This is how I call it:

$search = new MyModelSearch();
$myModels = $search->search(['att3' => '3']);

Regardless of what attributes I use in calling search, I always get back the same result - i.e. all the entries in the table. I'm missing something here that I just do not understand.

Any help would be really appreciated. Thanks.


Source: (StackOverflow)

Basic Hidden field in yii

I'm trying to place data in hidden text in yii, but I don't know how. I need a similar code to a regular php syntax:

<input type="hidden" name="field_name" value="a"/>

It's supposed to be a field with static value of a. I just need it to go with my $_POST variables for error checking.

Is it possible to avoid modifying the models and controllers just to put the field in?I cant use gii cause I only have snippets of code with me.Sorry as well as I have little understanding of yii so I have no clue if what I'm saying about the last 2 sentences is correct.


Source: (StackOverflow)

Yii: Multi-language website - best practices

I find Yii great framework, and the example website created with yiic shell is a good point to start... however it doesn't cover the topic of multi-language websites, unfortunately. The docs covers the topic of translating short messages, but not keeping the multi-lingual content ...

I'm about to start working on a website which needs to be in at least two languages, and I'm wondering what is the best way to keep content for that ... The problem is that the content is mixed extensively with common elements (like embedded video files).

I need to avoid duplicating those commons ... so far I used to have an array of arrays containing texts (usually no more than 1-2 short paragraphs), then the view file was just rendering the text from an array.

Now I'd like to avoid keeping it in arrays (which requires some attention when putting double quotations " " and is inconvenient in general...).

So, what is the best way to keep those short paragraphs? Should I keep them in DB like (id | msg_id | language | content ) and then select them by msg_id & language? That still requires me to create some msg_id's and embed them into view file ...

Is there any recommended paradigm for which Yii has some solutions?

Thanks, m.


Source: (StackOverflow)

Emberjs, server side vs client side, All in?

I have been looking into Ember.js, and it looks really great, but one thing that concerns me, and that I can't get my mind around it, is if I start using it on an already running project.

Will I eventually have to move everything client side, and make my application a single page application at some point?

let me clarify...

So far the best way to communicate between client and server using Ember is REST. and that looks great, but what I don't like is having all the templates loaded for the first time. and moving all the logic in my server to the client (or am I getting all of this wrong?), cause it looks like my server side will become a logic-less REST API.

Also, I'm using Yii Framework which has some JavaScript (Ajax enabled) components like grids. how can I have ember interact with all of this on navigation without having to rewrite a bunch of stuff already working on my application?

I'm on the login page (or state), and then after login in, I have to display a grid, that is just easy with Yii, and a full page load, but If I am using Ember, how can I have my grid display as it normally would? do I have to pre-load a handlebar template for the grid, and also the JavaScript that controls it?


Source: (StackOverflow)

How to use the swiftMailer in Yii2

I can't finally understand how to use the swiftMailer extension in Yii2. Judging by that on this subject I didn't find questions, the task is trivial, but up to the end I couldn't understand.

There are examples which don't describe in more detail all cycle of sending the letter or I don't understand something :(

Setup

    return [
    //....
   'components' => [
    ......
    'mail' => [
      'class' => 'yii\swiftmailer\Mailer',
      'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'localhost',
        'username' => 'username',
        'password' => 'password',
        'port' => '587',
        'encryption' => 'tls',
      ],
    ],
  ]
];

Send

Yii::$app->mail->compose()
->setTo($toEmail)
->setFrom([$this->email => $this->name])
->setSubject($this->subject)
->setTextBody($this->body)
->send();

I want will receive a concrete working example. Thank you.

P.S. I adjusted domain records MX, DKIM, SPF added.

UPD (some answer):

E-mail which is passed in "From" field, it is put down by default in the field of "Return-path", has to be the existing address. Some providers don't allow sending mail from nonexistent email addresses.


Source: (StackOverflow)

Get current URL/URI without some of $_GET variables

How, in Yii, to get the current page's URL. For example:

http://www.yoursite.com/your_yii_application/?lg=pl&id=15

but excluding the $GET_['lg'] (without parsing the string manually)?

I mean, I'm looking for something similar to the Yii::app()->requestUrl / Chtml::link() methods, for returning URLs minus some of the $_GET variables.

Edit: Current solution:

unset $_GET['lg'];

echo Yii::app()->createUrl(
  Yii::app()->controller->getId().'/'.Yii::app()->controller->getAction()->getId() , 
  $_GET 
);

Source: (StackOverflow)