yii2 interview questions
Top yii2 frequently asked interview questions
Hello I am trying to create my own custom helper class to use with Yii2. It is going to handle times so I'll be working with PHP's DateTime class. I have
<?php
namespace yii\helpers;
use Yii;
class Time
{
public static function getTime()
{
$time = new DateTime('now', new DateTimeZone('UTC'));
return $time->format('m-d-Y H:i:s');
}
}
To test it I added
use yii\helpers\Time;
to a view file and called Time::getTime();
but Yii2 throws an ErrorException saying Class 'yii\helpers\DateTime' not found.
The php DateTime object works fine if I place the code directly into a view file and execute it so I'm not sure what my problem is.
Source: (StackOverflow)
I'm doing this:
$students = Student::find()->all();
return $this->render('process', array('students' => $students));
and then this in the view:
foreach($students as $student)
{
echo $student->name . ', ';
echo $student->getQuizActivitiesCount(); ?> <br /> <?php
}
i would like to see the sql query being performed. a student "has many" quiz activities, and the query performs perfectly, but i need to see the raw SQL. is this possible?
Source: (StackOverflow)
Asset bundle generate empty js and css files
namespace frontend\assets;
return [
'bundles' => [
'frontend\assets\AppAsset',
],
'targets' => [
'frontend\assets\AppAsset' => [
'basePath' => 'e:/path/yii2.loc/www',
'baseUrl' => '',
'js' => 'js/{ts}.js',
'css' => 'css/{ts}.css',
],
],
'assetManager' => [
'basePath' => 'e:/path/yii2.loc/www/assets',
'baseUrl' => '',
],
];
config.php
return [
'bundles' => [
'frontend\assets\AppAsset',
],
'targets' => [
'frontend\assets\AppAsset' => [
'basePath' => 'e:/path/yii2.loc/www',
'baseUrl' => '',
'js' => 'cache/{ts}.js',
'css' => 'cache/{ts}.css',
],
],
'assetManager' => [
'basePath' => 'e:/path/yii2.loc/www/assets',
'baseUrl' => '',
],
];
then in console
yii asset e:\path\config.php e:\path\compressed.php
//compresed.php it's result file with name of compressed files
and in config
'assetManager' => [
'bundles' => require dirname(__DIR__) . '/assets/compressed.php',
],
css and js files are in a directory :
e:/path/yii2.loc/www/css
and
e:/path/yii2.loc/www/js
bundle generate empties to:
e:/path/yii2.loc/www/cache/css and e:/path/yii2.loc/www/cache/js
what i do wrong?
Source: (StackOverflow)
We are about to start a new project and we want to use Yii for it. After reading Yii website, I found out that the release date for Yii 2 beta has been set to early 2014 and judging by github, that milestone is 94% ready.
What is our best bet in this case when choosing Yii version? If we go with stable Yii 1, is it going to be easy to later update that code to Yii 2.0 or is it going to be a complete rewrite or some bad hack? Or if we go with Yii 2.0 alpha, will it be relatively easy to update then? The instability of alpha is ok, we anyway will likely be working on basic things such as authentication, registration, etc by the time beta is released? And finally is using the latest github commit (which is a 94% complete beta) a good idea or is it in a semi-functional "development" state and might not work at all?
Also how compatible are the Yii extensions? If we go with Yii 2, are we going to be limited to a relatively small selection of Yii 2 extensions?
Source: (StackOverflow)
I am using Yii2
and have been reading about theming and theme inheritance; however have some questions:
Consider the following example:
'view' => [
'theme' => [
'pathMap' => [
'@app/views' => [
'@app/themes/current',
'@app/themes/default',
],
],
'baseUrl' => '@web/themes/current',
'basePath' => '@webroot/themes/current',
],
],
Now, imagine we request the theme file foo
; as I understand it this will first be looked for in the following order:
@app/themes/current/foo.php
@app/themes/default/foo.php
@app/views/foo.php
Now imagine foo.php
isn't found in the @app/themes/current/
theme, so it would use the file found in @app/themes/default/
.
Now, considering the baseUrl
and basePath
settings I am a little confused how these are used in these situations.
Now, imagine foo.php
references an image file inside the file, wouldn't this still attempt to find @web/themes/current/images/myImage.jpg
rather than @web/themes/default/images/myImage.jpg
?
Source: (StackOverflow)
I am facing a problem in YII2. Problem is i want to send a parameter from controller to layout (ie. main.php). But i am not able to get the param in main.php
I tried :
Controller Code :
$this->render('index',array('param' => $paramValue));
And this is how i was trying to get this in layout ie. main.php
$this->param
(as in yii 1)
$param
But i am not able to get param value in layout. Can anyone tell me how to do this?
Many Thanks,
M.
Source: (StackOverflow)
I have this code to find a user from db which status is active and role is user
public static function findByUsername($username)
{
return static::find(['username' => $username, 'status' => static::STATUS_ACTIVE, 'role'=>'user']);
}
I need to find a user that role is not equal to "user". How can I do this?
P.S: I'm using YII2
Source: (StackOverflow)
As the title clarifies why is the auth key is introduced in Yii2? What're it's main usages and how it is useful in authentication?
Source: (StackOverflow)
yii2 Question
My yii2 install in d:\wamp\www\yii2store
I want to get above path to save images which will be uploaded by me or users.
I have pass all available arguments in Yii::getAlias('@webroot')
(below are the lists of argument which I have used).
@yii
- framework directory.
@app
- base path of currently running application.
@runtime
- runtime directory.
@vendor
- Composer vendor directory.
@webroot
- web root directory of currently running web application.
@web
- base URL of currently running web application.
And also once I will get above path to save images then how can I get path something like this localhost/yiistore2/upload
to be use in img tag src.
One more thing how can I create my own alias with Yii::setAlias()
and where to create this so that I can load it on every controller.
Source: (StackOverflow)
The Yii2 preview was recently released and is available on github. I want to take it for a test drive, but the "documentation" so far gets outdated almost instantly since it is still under heavy development. I have tried to follow this guide on creating a simple CRUD app with Yii2, but it fails at the step:
php yiic.php app/create /var/www/yii2
With the error:
Could not open input file: yiic.php
Indicating that there is no file called yiic.php
. The only folder within the framework folder is yii (framework/yii
), and within that folder there is no file yiic.php
, only Yii.php
which when called in the command line gives the command list:
The following commands are available:
- asset
- cache
- help
- message
- migrate
Anyone managed to successfully setup a Yii2 app? Care to share how you got it done?
Source: (StackOverflow)
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)
I have a problem with setting flash messages.
So, i have an action which in some cases should redirect with flash. It looks like this:
if(!$this->_isSameOrg($reports)){
\Yii::$app->session->setFlash('consol_v_error',\Yii::t('app/consol', 'some_text'));
$this->redirect(\Yii::$app->request->getReferrer());
return;
}
After redirect in view i have this
<div class="col-lg-12">
<?php if(Yii::$app->session->hasFlash('consol_v_error')): ?>
<div class="alert alert-danger" role="alert">
<?= Yii::$app->session->getFlash('consol_v_error') ?>
</div>
<?php endif; ?>
</div>
The problem is i don't see any message here. In Debug panel i see SESSION var populated with good flash, but it doesn't display with this if-statement.
Maybe i need to configure session component or something?...
Source: (StackOverflow)
Adding a javascript inside my view results in the ReferenceError: $ is not defined
. I assume that the problem is due to the jquery.ui
is calling after the content or my js when i view the page source. How to fix this?
Or how will I prevent Yii2 from autoloading the script files?
My view
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\UrlManager;
use yii\widgets\ActiveForm;
use backend\controllers\StandardController;
use backend\models\standard;
?>
<div class="domain-form">
<?php $form = ActiveForm::begin(); ?>
<?php
<?= $form->field($model, 'clause')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'name')->textarea(['rows' => 6]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script type="text/javascript">
$("document").ready( function () {
alert("hi");
});</script>
I need to get this simple script to show an alert after the page loaded. I hav'nt called any of the script file here since yii loads automatically(i think) in the layout by calling
AppAsset::register($this);
This results in script files to be registered at the end of the page,after my custom script.
How to solve this?
Source: (StackOverflow)
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)
Same as title, i don't want using bootstrap.css and bootstrap.js. I try using:
'assetManager' => [
'bundles' => [
'yii\bootstrap\BootstrapAsset' => [
'css' => [],
],
],
],
It remove bootstrap.css but can't remove bootstrap.js. Somebody can help me?
Source: (StackOverflow)