Changes
Title
unchanged
Yii v2 snippet guide
Category
unchanged
Tutorials
Yii version
unchanged
2.0
Tags
unchanged
tutorial,beginner,yii2
Content
changed
**Intro**
---
Hi all!
**This article had to be split as I reached the max length. Second part is here: **
- [https://www.yiiframework.com/wiki/2558/yii-v2-snippet-guide-ii](https://www.yiiframework.com/wiki/2558/yii-v2-snippet-guide-ii)
This snippet guide works with the basic Yii demo application and enhances it. It continues in my series of simple Yii tutorials. Previous two contain basic info about MVC concept, exporting to Excel and other topics so read them as well, but they are meant for Yii v1. I started with them cca in year 2011:
- [https://www.yiiframework.com/wiki/250/yii-for-beginners](https://www.yiiframework.com/wiki/250/yii-for-beginners)
- [https://www.yiiframework.com/wiki/462/yii-for-beginners-2](https://www.yiiframework.com/wiki/462/yii-for-beginners-2)
... and today I am beginning with Yii 2 so I will also gather my snippets and publish them here so we all can quickly setup the yii-basic-demo just by copying and pasting. This is my goal - to show how-to without long descriptions.
I was suprised that the Yii 2 demo application does not contain some basic functionalities (like login via DB, translations etc) which must be implemented in the most of web projects so I will focus on them. Plus I will talk about GitLab.
If you find any problems in my snippets, let me know, please.
**Prerequisities**
---
Skip this paragraph if you know how to run your Yii demo project...
I work with Win10 + [XAMPP Server](https://www.apachefriends.org/download.html) so I will expect this configuration. Do not forget to start the server and enable Apache + MySQL in the dialog. Then test that following 2 URLs work for you
- [http://localhost/](http://localhost/)
- [http://localhost/phpmyadmin/](http://localhost/phpmyadmin/)
You should also download the [Yii basic demo application](https://www.yiiframework.com/download) and place it into the **htdocs** folder. In my case it is here:
- C:\xampp\htdocs
And your index.php should be here:
- C:\xampp\htdocs\basic\web\index.php
If you set things correctly up, following URL will open your demo application. Now it will probably throw an exception:
- [http://localhost/basic/web/](http://localhost/basic/web/)
**The Exception is removed by entering any text into attribute 'cookieValidationKey' in file**:
- C:\xampp\htdocs\basic\config\web.php
Dont forget to connect Yii to the DB. It is done in file:
- C:\xampp\htdocs\basic\config\db.php
... but it should work out-of-the-box if you use DB name "yii2basic" which is also used in examples below ...
.
.
**Yii demo app + GitLab**
---
Once you download and run the basic app, I recommend to push it into [GitLab](https://gitlab.com/). You will probably need a SSH certificate which can be generated [like this](https://www.huber.xyz/?p=275) using [PuTTYgen](https://www.puttygen.com/). When I work with Git I use [TortoiseGIT](https://www.puttygen.com/) which integrates all git functionalities into the context menu in Windows File Explorer.
First go to GitLab web and [create a new project](https://gitlab.com/projects/new). Then you might need to fight a bit, because the process of connecting your PC to GIT seems to be quite complicated. At least for me.
Once things work, just create an empty folder, right click it and select Git Clone. Enter your git path, best is this format:
- git@gitlab.com:{username}/{projectName}.git
- or you can use also this URL:
- https://gitlab.com/{username}/{projectName}.git
- or you can use HTTP:
- http://gitlab.com/{username}/{projectName}.git
Note: What works for me the best is using the following command to clone my project and system asks me for the password. Other means of connection usually refuse me. Then I can start using TortoiseGIT.
```
git clone https://{username}@gitlab.com/{username}/{myProjectName}.git
```
When cloned, copy the content of the "basic" folder into the new empty git-folder and push everything except for folder "vendor". (It contains 75MB and 7000 files so you dont want to have it in GIT)
Then you can start to modify you project, for example based on this "tutorial".
Thanks to .gitignore files only 115 files are uploaded. Te vendor-folder can be recreated using command
```
composer install
```
which only needs file **composer.json** to exist.
**Automatical copying from GitLab to FTP**
---
I found these two pages where things are explained: [link](https://www.savjee.be/2019/04/gitlab-ci-deploy-to-ftp-with-lftp/) [link](https://stackoverflow.com/questions/49632077/use-gitlab-pipeline-to-push-data-to-ftpserver) and I just copied something.
You only need to create 1 file in your GitLab repository. It is named .gitlab-ci.yml and it should contain following code:
```
variables:
HOST: "ftp url"
USERNAME: "user"
PASSWORD: "password"
TARGETFOLDER: "relative path if needed, or just ./"
deploy:
script:
- apt-get update -qq && apt-get install -y -qq lftp
- lftp -c "set ftp:ssl-allow no; open -u $USERNAME,$PASSWORD $HOST; mirror -Rnev ./ $TARGETFOLDER --ignore-time --parallel=10 --exclude-glob .git* --exclude .git/ --exclude vendor --exclude web/assets --exclude web/index.php --exclude web/index-test.php"
only:
- master
```
I just added some exclusions (listed below) and will probably add **--delete** in the future. Read linked webs.
- exclude vendor = huge folder with 3rd party SW which is not in GIT
- exclude web/assets = also some cache
- exclude web/index.php = in GIT is your devel index with DEBUG mode enabled. You dont wanna have this file in productive environment
- exclude web/index-test.php = tests are only on your computer and in GIT
.
## My articles
Articles are separated into more files as there is the max lenght for each file on wiki.
* [Yii v1 for beginners](https://www.yiiframework.com/wiki/250/yii-for-beginners)
* [Yii v1 for beginners 2](https://www.yiiframework.com/wiki/462/yii-for-beginners-2)
* [Yii v2 snippet guide I](https://www.yiiframework.com/wiki/2552/yii-v2-snippet-guide)
* [Yii v2 snippet guide II](https://www.yiiframework.com/wiki/2558/yii-v2-snippet-guide-ii)
* [Yii v2 snippet guide III](https://www.yiiframework.com/wiki/2567/yii-v2-snippet-guide-iii)
* [Začínáme s PHP frameworkem Yii2 (I) česky - YouTube](https://youtu.be/ub06hNoL8B8)
* [Yii2 App Basic Plus](https://gitlab.com/radin.cerny/yii2-app-basic-plus) ... a compilation of the most used functionalities
* [VueJs3 PWA demo plus](https://gitlab.com/radin.cerny/vuejs3-pwa-demo-plus) ... a basic installable PWA project (written in JavaScript, VueJS3) for my REST offline clients (only 1 data transfer per day)
**Prerequisities**
---
Skip this paragraph if you know how to run your Yii demo project...
I work with Win10 + [XAMPP Server](https://www.apachefriends.org/download.html) so I will expect this configuration. Do not forget to start the server and enable Apache + MySQL in the dialog. Then test that following 2 URLs work for you
- [http://localhost/](http://localhost/)
- [http://localhost/phpmyadmin/](http://localhost/phpmyadmin/)
You should also download the [Yii basic demo application](https://www.yiiframework.com/download) and place it into the **htdocs** folder. In my case it is here:
- C:\xampp\htdocs
And your index.php should be here:
- C:\xampp\htdocs\basic\web\index.php
If you set things correctly up, following URL will open your demo application. Now it will probably throw an exception:
- [http://localhost/basic/web/](http://localhost/basic/web/)
**The Exception is removed by entering any text into attribute 'cookieValidationKey' in file**:
- C:\xampp\htdocs\basic\config\web.php
Dont forget to connect Yii to the DB. It is done in file:
- C:\xampp\htdocs\basic\config\db.php
... but it should work out-of-the-box if you use DB name "yii2basic" which is also used in examples below ...
.
.
**Yii demo app + GitLab**
---
Once you download and run the basic app, I recommend to push it into [GitLab](https://gitlab.com/). You will probably need a SSH certificate which can be generated [like this](https://www.huber.xyz/?p=275) using [PuTTYgen](https://www.puttygen.com/) or command "ssh-keygen" in Windows10. When I work with Git I use [TortoiseGIT](https://www.puttygen.com/) which integrates all git functionalities into the context menu in Windows File Explorer.
First go to GitLab web and [create a new project](https://gitlab.com/projects/new). Then you might need to fight a bit, because the process of connecting your PC to GIT seems to be quite complicated. At least for me.
Note: [Here](https://gitlab.com/-/profile/keys) you can add the public SSH key to GitLab. Private key must be named "id_rsa" and stored in Win10 on path C:\\Users\\{username}\\.ssh\\id_rsa
Once things work, just create an empty folder, right click it and select Git Clone. Enter your git path, best is this format:
- git@gitlab.com:{username}/{projectName}.git
- or you can use also this URL:
- https://gitlab.com/{username}/{projectName}.git
- or you can use HTTP:
- http://gitlab.com/{username}/{projectName}.git
Note: What works for me the best is using the following command to clone my project and system asks me for the password. Other means of connection usually refuse me. Then I can start using TortoiseGIT.
```
git clone https://{username}@gitlab.com/{username}/{myProjectName}.git
```
When cloned, copy the content of the "basic" folder into the new empty git-folder and push everything except for folder "vendor". (It contains 75MB and 7000 files so you dont want to have it in GIT)
Then you can start to modify you project, for example based on this "tutorial".
Thanks to .gitignore files only 115 files are uploaded. Te vendor-folder can be recreated using command
```
composer install
```
which only needs file **composer.json** to exist.
**Automatical copying from GitLab to FTP**
---
I found these two pages where things are explained: [link](https://www.savjee.be/2019/04/gitlab-ci-deploy-to-ftp-with-lftp/) [link](https://stackoverflow.com/questions/49632077/use-gitlab-pipeline-to-push-data-to-ftpserver).
You need to create file .gitlab-ci.yml in the root of your repository with following content. It will fire a Pipeline job on commit using "LFTP client" automatically. If you want to do it manually, add "when:manual", see below.
```
variables:
HOST: "ftp url"
USERNAME: "user"
PASSWORD: "password"
TARGETFOLDER: "relative path if needed, or just ./"
deploy:
script:
- apt-get update -qq && apt-get install -y -qq lftp
- lftp -c "set ftp:ssl-allow no; open -u $USERNAME,$PASSWORD $HOST; mirror -Rnev ./ $TARGETFOLDER --ignore-time --parallel=10 --exclude-glob .git* --exclude .git/ --exclude vendor --exclude web/assets --exclude web/index.php --exclude web/index-test.php --exclude .gitlab-ci.yml"
only:
- master
when: manual
```
I just added some exclusions (see the code) and will probably add **--delete** in the future. Read linked webs.
**Important info:** Your FTP server might block foreign IPs. If this happens, your transfer will fail with error 530. You must findout GitLab's IPs and whitelist them. [This link]( https://docs.gitlab.com/ee/user/gitlab_com/#ip-range) might help.
**User management + DB creation + login via DB**[...]
```
.
.
**Tests - unit + opa**
---
...
text ...
.
see next chapters ...
**Adding a google-like calendar**[...]
And right above your GridView place this link:
```php
<?php
$csvUrl = \yii\helpers\Url::current(['exportToCsv'=>1]);
echo Html::a('Export', $csvUrl, ['class' => 'btn btn-info', 'target'=>'_blank']);
?>
```
In my code above there were used 2 methods in the model which export things to the CSV format. My implementatino is here:
```php
public static function getCsvHeader() {
$result = [];
$result[] = "ID";
$result[] = "Username";
$result[] = "Email";
// ...
return implode(";", $result);
}
public function getCsvRow() {
$result = [];
$result[] = $this->id;
$result[] = $this->username;
$result[] = $this->email;
// ...
return implode(";", $result);
}
```
**Next chapters had to be moved to a new article!**
---
**This article had to be split as I reached the max length. Second part is here:**
- [https://www.yiiframework.com/wiki/2558/yii-v2-snippet-guide-ii](https://www.yiiframework.com/wiki/2558/yii-v2-snippet-guide-ii)html
<?php
// Pjax::begin(); // If you are using Pjax for GridView, it must start before following buttons.
?>
<div style="display:flex;flex-direction:row;">
<?= Html::a('+ Create new record', ['create'], ['class' => 'btn btn-success']) ?>
<div class="btn-group">
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Export to CSV <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><?php
echo Html::a('Ignore filters and sorting', ['index', 'exportToCsv' => 1], ['target' => '_blank', 'class' => 'text-left', 'data-pjax'=>'0']);
// 'data-pjax'=>'0' is necessaary to avoid PJAX.
// Now we need to open the link in a new tab, not to resolve it as an ajax request.
?></li>
<li><?php
$csvUrl = \yii\helpers\Url::current(['exportToCsv' => 1]);
echo Html::a('Preserve filters and sorting', $csvUrl, ['target' => '_blank', 'class' => 'text-left', 'data-pjax'=>'0']);
// 'data-pjax'=>'0' is necessaary to avoid PJAX.
// Now we need to open the link in a new tab, not to resolve it as an ajax request.
?></li>
</ul>
</div>
</div>
<php
// Here goes the rest ...
// echo GridView::widget([
// ...
?>
```
In my code above there were used 2 methods in the model which export things to the CSV format. My implementatino is here:
```php
public static function getCsvHeader() {
$result = [];
$result[] = "ID";
$result[] = "Username";
$result[] = "Email";
// ...
return implode(";", $result);
}
public function getCsvRow() {
$result = [];
$result[] = $this->id;
$result[] = $this->username;
$result[] = $this->email;
// ...
return implode(";", $result);
}
```
**Next chapters had to be moved to a new article!**
---