Yii – AJAX Validation ”; Previous Next The username validation should only be done on the server side because only the server has the needed information. In this case, you can use AJAX-based validation. Step 1 − To enable the AJAX validation, modify the registration view this way. <?php use yiibootstrapActiveForm; use yiibootstrapHtml; ?> <div class = “row”> <div class = “col-lg-5″> <?php $form = ActiveForm::begin([”id” => ”registration-form”, ”enableAjaxValidation” => true]); ?> <?= $form->field($model, ”username”) ?> <?= $form->field($model, ”password”)->passwordInput() ?> <?= $form->field($model, ”email”)->input(”email”) ?> <?= $form->field($model, ”country”) ?> <?= $form->field($model, ”city”) ?> <?= $form->field($model, ”phone”) ?> <div class = “form-group”> <?= Html::submitButton(”Submit”, [”class” => ”btn btn-primary”, ”name” => ”registration-button”]) ?> </div> <?php ActiveForm::end(); ?> </div> </div> We should also prepare the server, so that it can handle the AJAX requests. Step 2 − Modify the actionRegistration method of the SiteController this way. public function actionRegistration() { $model = new RegistrationForm(); if (Yii::$app->request->isAjax && $model->load(Yii::$app->request>post())) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } return $this->render(”registration”, [”model” => $model]); } Step 3 − Now, go to http://localhost:8080/index.php?r=site/registration, you will notice that the form validation is done by AJAX requests. Print Page Previous Next Advertisements ”;
Category: yii
Yii – Creating Extensions
Yii – Creating Extensions ”; Previous Next Let us create a simple extension displaying a standard “Hello world” message. This extension will be distributed via the Packagist repository. Step 1 − Create a folder called hello-world in your hard drive but not inside the Yii basic application template). Inside the hello-world directory, create a file named composer.json with the following code. { “name”: “tutorialspoint/hello-world”, “authors”: [ { “name”: “tutorialspoint” } ], “require”: {}, “autoload”: { “psr-0”: { “HelloWorld”: “src/” } } } We have declared that we are using the PSR-0 standard and all extension files are under the src folder. Step 2 − Create the following directory path: hello-world/src/HelloWorld. Step 3 − Inside the HelloWorld folder, create a file called SayHello.php with the following code. <?php namespace HelloWorld; class SayHello { public static function world() { return ”Hello World, Composer!”; } } ?> We have defined a SayHello class with a world static function, which returns our hello message. Step 4 − The extension is ready. Now create an empty repository at your github account and push this extension there. Inside the hello-world folder run − git init git add git commit -m “initial commit” git remote add origin <YOUR_NEWLY_CREATED_REPOSITORY> git push -u origin master We have just sent our extension to the github. Now, go to the https://packagist.org, sign in and click “submit” at the top menu. You will see a page where you should enter your github repository to publish it. Step 5 − Click the “check” button and your extension is published. Step 6 − Go back to the basic application template. Add the extension to the composer.json. { “name”: “yiisoft/yii2-app-basic”, “description”: “Yii 2 Basic Project Template”, “keywords”: [“yii2”, “framework”, “basic”, “project template”], “homepage”: “http://www.yiiframework.com/”, “type”: “project”, “license”: “BSD-3-Clause”, “support”: { “issues”: “https://github.com/yiisoft/yii2/issues?state=open”, “forum”: “http://www.yiiframework.com/forum/”, “wiki”: “http://www.yiiframework.com/wiki/”, “irc”: “irc://irc.freenode.net/yii”, “source”: “https://github.com/yiisoft/yii2” }, “minimum-stability”: “dev”, “prefer-stable” : true, “require”: { “php”: “>=5.4.0”, “yiisoft/yii2”: “>=2.0.5”, “yiisoft/yii2-bootstrap”: “*”, “yiisoft/yii2-swiftmailer”: “*”, “kartik-v/yii2-widget-datetimepicker”: “*”, “tutorialspoint/hello-world”: “*” }, “require-dev”: { “yiisoft/yii2-codeception”: “*”, “yiisoft/yii2-debug”: “*”, “yiisoft/yii2-gii”: “*”, “yiisoft/yii2-faker”: “*” }, “config”: { “process-timeout”: 1800 }, “scripts”: { “post-create-project-cmd”: [ “yii\composer\Installer::postCreateProject” ] }, “extra”: { “yii\composer\Installer::postCreateProject”: { “setPermission”: [ { “runtime”: “0777”, “web/assets”: “0777”, “yii”: “0755” } ], “generateCookieValidationKey”: [ “config/web.php” ] }, “asset-installer-paths”: { “npm-asset-library”: “vendor/npm”, “bower-asset-library”: “vendor/bower” } } } Step 7 − Inside the project root folder, run the composer update to install/update all the dependencies. Step 8 − Our extension should be installed. To use it, modify the About view of the actionAbout method of the SiteController. <?php /* @var $this yiiwebView */ use yiihelpersHtml; $this->title = ”About”; $this->params[”breadcrumbs”][] = $this->title; $this->registerMetaTag([”name” => ”keywords”, ”content” => ”yii, developing, views, meta, tags”]); $this->registerMetaTag([”name” => ”description”, ”content” => ”This is the description of this page!”], ”description”); ?> <div class = “site-about”> <h1><?= Html::encode($this->title) ?></h1> <p> This is the About page. You may modify the following file to customize its content: </p> <h1><?= HelloWorldSayHello::world(); ?></h1> </div> Step 9 − Type http://localhost:8080/index.php?r=site/about in the web browser. You will see a hello world message from our extension. Print Page Previous Next Advertisements ”;
Yii – URL Routing
Yii – URL Routing ”; Previous Next To change the default route of the application, you should configure the defaultRoute property. Step 1 − Modify the config/web.php file in the following way. <?php $params = require(__DIR__ . ”/params.php”); $config = [ ”id” => ”basic”, ”basePath” => dirname(__DIR__), ”bootstrap” => [”log”], ”defaultRoute” => ”site/contact”, ”components” => [ //other code ?> Step 2 − Got to http://localhost:8080/index.php. You will see the default contact page. To put your application in maintenance mode temporarily, you should configure the yiiwebApplication::$catchAll property. Step 3 − Add the following function to the SiteController. public function actionMaintenance() { echo “<h1>Maintenance</h1>”; } Step 4 − Then, modify the config/web.php file in the following way. <?php $params = require(__DIR__ . ”/params.php”); $config = [ ”id” => ”basic”, ”basePath” => dirname(__DIR__), ”bootstrap” => [”log”], ”catchAll” => [”site/maintenance”], ”components” => [ //OTHER CODE Step 5 − Now enter any URL of your application, you will see the following. Creating URLs To create various kinds of URLs you may use the yiihelpersUrl::to() helper method. The following example assumes the default URL format is being used. Step 1 − Add an actionRoutes() method to the SiteController. public function actionRoutes() { return $this->render(”routes”); } This method simply renders the routes view. Step 2 − Inside the views/site directory, create a file called routes.php with the following code. <?php use yiihelpersUrl; ?> <h4> <b>Url::to([”post/index”]):</b> <?php // creates a URL to a route: /index.php?r = post/index echo Url::to([”post/index”]); ?> </h4> <h4> <b>Url::to([”post/view”, ”id” => 100]):</b> <?php // creates a URL to a route with parameters: /index.php?r = post/view&id=100 echo Url::to([”post/view”, ”id” => 100]); ?> </h4> <h4> <b>Url::to([”post/view”, ”id” => 100, ”#” => ”content”]):</b> <?php // creates an anchored URL: /index.php?r = post/view&id=100#content echo Url::to([”post/view”, ”id” => 100, ”#” => ”content”]); ?> </h4> <h4> <b>Url::to([”post/index”], true):</b> <?php // creates an absolute URL: http://www.example.com/index.php?r=post/index echo Url::to([”post/index”], true); ?> </h4> <h4> <b>Url::to([”post/index”], ”https”):</b> <?php // creates an absolute URL using the https scheme: https://www.example.com/index.php?r=post/index echo Url::to([”post/index”], ”https”); ?> </h4> Step 3 − Type http://localhost:8080/index.php?r=site/routes, you will see some uses of the to() function. The route passed to the yiihelpersUrl::to() method can be relative or absolute according to the following rules − if the route is empty, the currently requested route will be used. if the route has no leading slash, it is considered to be a route relative to the current module. if the route contains no slashes, it is considered to be an action ID of the current controller. The yiihelpersUrl helper class also provides several useful methods. Step 4 − Modify the routes View as given in the following code. <?php use yiihelpersUrl; ?> <h4> <b>Url::home():</b> <?php // home page URL: /index.php?r=site/index echo Url::home(); ?> </h4> <h4> <b>Url::base():</b> <?php // the base URL, useful if the application is deployed in a sub-folder of the Web root echo Url::base(); ?> </h4> <h4> <b>Url::canonical():</b> <?php // the canonical URL of the currently requested URL // see https://en.wikipedia.org/wiki/Canonical_link_element echo Url::canonical(); ?> </h4> <h4> <b>Url::previous():</b> <?php // remember the currently requested URL and retrieve it back in later requests Url::remember(); echo Url::previous(); ?> </h4> Step 5 − If you enter the address http://localhost:8080/index.php?r=site/routes in the web browser, you will see the following. Print Page Previous Next Advertisements ”;
Yii – Configurations
Yii – Configurations ”; Previous Next Configurations are used to create new objects or initializing the existing ones. Configurations usually include a class name and a list of initial values. They may also include a list of event handlers and behaviors. The following is an example of the database configuration − <?php $config = [ ”class” => ”yiidbConnection”, ”dsn” => ”mysql:host = localhost;dbname = helloworld”, ”username” => ”vladimir”, ”password” => ”12345”, ”charset” => ”utf8”, ]; $db = Yii::createObject($config); ?> The Yii::createObject() method takes a configuration array and creates an object based on the class named in the configuration. The format of a configuration − [ //a fully qualified class name for the object being created ”class” => ”ClassName”, //initial values for the named property ”propertyName” => ”propertyValue”, //specifies what handlers should be attached to the object”s events ”on eventName” => $eventHandler, //specifies what behaviors should be attached to the object ”as behaviorName” => $behaviorConfig, ] The configuration file of a basic application template is one of the most complex − <?php $params = require(__DIR__ . ”/params.php”); $config = [ ”id” => ”basic”, ”basePath” => dirname(__DIR__), ”bootstrap” => [”log”], ”components” => [ ”request” => [ // !!! insert a secret key in the following (if it is empty) – this //is required by cookie validation ”cookieValidationKey” => ”ymoaYrebZHa8gURuolioHGlK8fLXCKjO”, ], ”cache” => [ ”class” => ”yiicachingFileCache”, ], ”user” => [ ”identityClass” => ”appmodelsUser”, ”enableAutoLogin” => true, ], ”errorHandler” => [ ”errorAction” => ”site/error”, ], ”mailer” => [ ”class” => ”yiiswiftmailerMailer”, // send all mails to a file by default. You have to set // ”useFileTransport” to false and configure a transport // for the mailer to send real emails. ”useFileTransport” => true, ], ”log” => [ ”traceLevel” => YII_DEBUG ? 3 : 0, ”targets” => [ [ ”class” => ”yiilogFileTarget”, ”levels” => [”error”, ”warning”], ], ], ], ”urlManager” => [ //”showScriptName” => false, //”enablePrettyUrl” => true, //”enableStrictParsing” => true, //”suffix” => ”/” ], ”db” => require(__DIR__ . ”/db.php”), ], ”modules” => [ ”hello” => [ ”class” => ”appmoduleshelloHello”, ], ], ”params” => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for ”dev” environment $config[”bootstrap”][] = ”debug”; $config[”modules”][”debug”] = [ ”class” => ”yiidebugModule”, ]; $config[”bootstrap”][] = ”gii”; $config[”modules”][”gii”] = [ ”class” => ”yiigiiModule”, ]; } return $config; ?> In the above configuration file, we do not define the class name. This is because we have already defined it in the index.php file − <?php //defining global constans defined(”YII_DEBUG”) or define(”YII_DEBUG”, true); defined(”YII_ENV”) or define(”YII_ENV”, ”dev”); //register composer autoloader require(__DIR__ . ”/../vendor/autoload.php”); //include yii files require(__DIR__ . ”/../vendor/yiisoft/yii2/Yii.php”); //load application config $config = require(__DIR__ . ”/../config/web.php”); //create, config, and process request (new yiiwebApplication($config))->run(); ?> Many widgets also use configurations as shown in the following code. <?php NavBar::begin([ ”brandLabel” => ”My Company”, ”brandUrl” => Yii::$app->homeUrl, ”options” => [ ”class” => ”navbar-inverse navbar-fixed-top”, ], ]); echo Nav::widget([ ”options” => [”class” => ”navbar-nav navbar-right”], ”items” => [ [”label” => ”Home”, ”url” => [”/site/index”]], [”label” => ”About”, ”url” => [”/site/about”]], [”label” => ”Contact”, ”url” => [”/site/contact”]], Yii::$app->user->isGuest ? [”label” => ”Login”, ”url” => [”/site/login”]] : [ ”label” => ”Logout (” . Yii::$app->user->identity->username . ”)”, ”url” => [”/site/logout”], ”linkOptions” => [”data-method” => ”post”] ], ], ]); NavBar::end(); ?> When a configuration is too complex, a common practice is to create a PHP file, which returns an array. Take a look at the config/console.php configuration file − <?php Yii::setAlias(”@tests”, dirname(__DIR__) . ”/tests”); $params = require(__DIR__ . ”/params.php”); $db = require(__DIR__ . ”/db.php”); return [ ”id” => ”basic-console”, ”basePath” => dirname(__DIR__), ”bootstrap” => [”log”, ”gii”], ”controllerNamespace” => ”appcommands”, ”modules” => [ ”gii” => ”yiigiiModule”, ], ”components” => [ ”cache” => [ ”class” => ”yiicachingFileCache”, ], ”log” => [ ”targets” => [ [ ”class” => ”yiilogFileTarget”, ”levels” => [”error”, ”warning”], ], ], ], ”db” => $db, ], ”params” => $params, ]; ?> The default configurations can be specified by calling the Yii::$container->set() method. It allows you to apply default configurations to all instances of the specified classes when they are called via the Yii::createObject() method. For example, to customize the yiiwidgetsLinkPager class, so that all link pagers will show at most three buttons, you can use the following code. Yii::$container->set(”yiiwidgetsLinkPager”, [ ”maxButtonCount” => 3, ]); Print Page Previous Next Advertisements ”;
Yii – ListView Widget
Yii – ListView Widget ”; Previous Next The ListView widget uses a data provider to display data. Each model is rendered using the specified view file. Step 1 − Modify the actionDataWidget() method this way. public function actionDataWidget() { $dataProvider = new ActiveDataProvider([ ”query” => MyUser::find(), ”pagination” => [ ”pageSize” => 20, ], ]); return $this->render(”datawidget”, [ ”dataProvider” => $dataProvider ]); } In the above code, we create a data provider and pass it to the datawidget view. Step 2 − Modify the datawidget view file this way. <?php use yiiwidgetsListView; echo ListView::widget([ ”dataProvider” => $dataProvider, ”itemView” => ”_user”, ]); ?> We render the ListView widget. Each model is rendered in the _user view. Step 3 − Create a file called _user.php inside the views/site folder. <?php use yiihelpersHtml; use yiihelpersHtmlPurifier; ?> <div class = “user”> <?= $model->id ?> <?= Html::encode($model->name) ?> <?= HtmlPurifier::process($model->email) ?> </div> Step 4 − Type http://localhost:8080/index.php?r=site/data-widget in the address bar of the web browser, you will see the following. Print Page Previous Next Advertisements ”;
Yii – HTML Forms
Yii – HTML Forms ”; Previous Next When a form is based upon a model, the common way of creating this form in Yii is via the yiiwidgetsActiveForm class. In most cases, a form has a corresponding model which is used for data validation. If the model represents data from a database, then the model should be derived from the ActiveRecord class. If the model captures arbitrary input, it should be derived from the yiibaseModel class. Let us create a registration form. Step 1 − Inside the models folder, create a file called RegistrationForm.php with the following code. <?php namespace appmodels; use Yii; use yiibaseModel; class RegistrationForm extends Model { public $username; public $password; public $email; public $subscriptions; public $photos; /** * @return array customized attribute labels */ public function attributeLabels() { return [ ”username” => ”Username”, ”password” => ”Password”, ”email” => ”Email”, ”subscriptions” => ”Subscriptions”, ”photos” => ”Photos”, ]; } } ?> We have declared a model for our registration form with five properties − username, password, email, subscriptions, and photos. Step 2 − To display this form, add the actionRegistration method to the SiteController. public function actionRegistration() { $mRegistration = new RegistrationForm(); return $this->render(”registration”, [”model” => $mRegistration]); } We create an instance of the RegistrationForm and pass it to the registration view. Now, it is time to create a view. Step 3 − Inside the views/site folder, add a file called registration.php with the following code. <?php use yiibootstrapActiveForm; use yiibootstrapHtml; ?> <div class = “row”> <div class = “col-lg-5″> <?php $form = ActiveForm::begin([”id” => ”registration-form”]); ?> <?= $form->field($model, ”username”) ?> <?= $form->field($model, ”password”)->passwordInput() ?> <?= $form->field($model, ”email”)->input(”email”) ?> <?= $form->field($model, ”photos[]”)->fileInput([”multiple”=>”multiple”]) ?> <?= $form->field($model, ”subscriptions[]”)->checkboxList([”a” => ”Item A”, ”b” => ”Item B”, ”c” => ”Item C”]) ?> <div class = “form-group”> <?= Html::submitButton(”Submit”, [”class” => ”btn btn-primary”, ”name” => ”registration-button”]) ?> </div> <?php ActiveForm::end(); ?> </div> </div> We observe the following − The ActiveForm::begin() function marks the beginning of the form. All the code between ActiveForm::begin() and ActiveForm::end() functions will be wrapped within the form tag. To create a field in the form you should call the ActiveForm::field() method. It creates all the input and label tags. Input names are determined automatically. For example, the password attribute will be RegistrationForm[password]. If you want an attribute to take an array, you should append [ ] to the attribute name. Step 4 − If you go to the address bar of the web browser and type http://localhost:8080/index.php?r=site/registration, you will see our form. Print Page Previous Next Advertisements ”;
Yii – URL Formats
Yii – URL Formats ”; Previous Next When a Yii application processes a requested URL, first, it parses the URL into a route. Then, to handle the request, this route is used to instantiate the corresponding controller action. This process is called routing. The reverse process is called URL creation. The urlManager application component is responsible for routing and URL creation. It provides two methods − parseRequest() − Parses a request into a route. createUrl() − Creates a URL from a given route. URL Formats The urlManager application component supports two URL formats − The default format uses a query parameter r to represent the route. For example, the URL /index.php?r=news/view&id=5 represents the route news/view and the id query parameter 5. The pretty URL format uses the extra path with the entry script name. For example, in the previous example, pretty format would be /index.php/news/view/5. To use this format you need to set the URL rules. To enable the pretty URL format and hide the entry script name, follow these steps − Step 1 − Modify the config/web.php file in the following way. <?php $params = require(__DIR__ . ”/params.php”); $config = [ ”id” => ”basic”, ”basePath” => dirname(__DIR__), ”bootstrap” => [”log”], ”components” => [ ”request” => [ // !!! insert a secret key in the following (if it is empty) – //this is required by cookie validation ”cookieValidationKey” => ”ymoaYrebZHa8gURuolioHGlK8fLXCKjO”, ], ”cache” => [ ”class” => ”yiicachingFileCache”, ], ”user” => [ ”identityClass” => ”appmodelsUser”, ”enableAutoLogin” => true, ], ”errorHandler” => [ ”errorAction” => ”site/error”, ], ”mailer” => [ ”class” => ”yiiswiftmailerMailer”, // send all mails to a file by default. You have to set // ”useFileTransport” to false and configure a transport // for the mailer to send real emails. ”useFileTransport” => true, ], ”log” => [ ”traceLevel” => YII_DEBUG ? 3 : 0, ”targets” => [ [ ”class” => ”yiilogFileTarget”, ”levels” => [”error”, ”warning”], ], ], ], ”urlManager” => [ ”showScriptName” => false, ”enablePrettyUrl” => true ], ”db” => require(__DIR__ . ”/db.php”), ], ”modules” => [ ”hello” => [ ”class” => ”appmoduleshelloHello”, ], ], ”params” => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for ”dev” environment $config[”bootstrap”][] = ”debug”; $config[”modules”][”debug”] = [ ”class” => ”yiidebugModule”, ]; $config[”bootstrap”][] = ”gii”; $config[”modules”][”gii”] = [ ”class” => ”yiigiiModule”, ]; } return $config; ?> We have just enabled the pretty URL format and have disabled the entry script name. Step 2 − Now, if you type http://localhost:8080/site/about in the address bar of the web browser, you will see the pretty URL in action. Notice, that the URL is no more http://localhost:8080/index.php?r=site/about. Print Page Previous Next Advertisements ”;
Yii – Views
Yii – Views ”; Previous Next Views are responsible for presenting the data to end users. In web applications, Views are just PHP script files containing HTML and PHP code. Creating Views Step 1 − Let us have a look at the ‘About’ view of the basic application template. <?php /* @var $this yiiwebView */ use yiihelpersHtml; $this->title = ”About”; $this->params[”breadcrumbs”][] = $this->title; ?> <div class=”site-about”> <h1><?= Html::encode($this->title) ?></h1> <p> This is the About page. You may modify the following file to customize its content: </p> <code><?= __FILE__ ?></code> </div> The $this variable refers to the view component that manages and renders this view template. This is how the ‘About’ page looks like − It is important to encode and/or filter the data coming from the end user in order to avoid the XSS attacks. You should always encode a plain text by calling yiihelpersHtml::encode() and HTML content by calling yiihelpersHtmlPurifier. Step 2 − Modify the ‘About’ View in the following way. <?php /* @var $this yiiwebView */ use yiihelpersHtml; use yiihelpersHtmlPurifier; $this->title = ”About”; $this->params[”breadcrumbs”][] = $this->title; ?> <div class=”site-about”> <h1><?= Html::encode($this->title) ?></h1> <p> This is the About page. You may modify the following file to customize its content: </p> <p> <?= Html::encode(“<script>alert(”alert!”);</script><h1>ENCODE EXAMPLE</h1>>”) ?> </p> <p> <?= HtmlPurifier::process(“<script>alert(”alert!”);</script><h1> HtmlPurifier EXAMPLE</h1>”) ?> </p> <code><?= __FILE__ ?></code> </div> Step 3 − Now type http://localhost:8080/index.php?r=site/about. You will see the following screen. Notice, that the javascript code inside the Html::encode() function is displayed as plain text. The same thing is for HtmlPurifier::process() call. Only h1 tag is being displayed. Views follow these conventions − Views, which are rendered by a controller, should be put into the @app/views/controllerID folder. Views, which are rendered in a widget, should be put into the widgetPath/views folder. To render a view within a controller, you may use the following methods − render() − Renders a view and applies a layout. renderPartial() − Renders a view without a layout. renderAjax() − Renders a view without a layout, but injects all registered js and css files. renderFile() − Renders a view in a given file path or alias. renderContent() − Renders a static string and applies a layout. To render a view within another view, you may use the following methods − render() − Renders a view. renderAjax() − Renders a view without a layout, but injects all registered js and css files. renderFile() − Renders a view in a given file path or alias. Step 4 − Inside the views/site folder, create two view files: _part1.php and _part2.php. _part1.php − <h1>PART 1</h1> _part2.php − <h1>PART 2</h1> Step 5 − Finally, render these two newly created views inside the ‘About’ View. <?php /* @var $this yiiwebView */ use yiihelpersHtml; $this->title = ”About”; $this->params[”breadcrumbs”][] = $this->title; ?> <div class=”site-about”> <h1><?= Html::encode($this->title) ?></h1> <p> This is the About page. You may modify the following file to customize its content: </p> <?= $this->render(“_part1”) ?> <?= $this->render(“_part2”) ?> <code><?= __FILE__ ?></code> </div> You will see the following output − When rendering a view, you can define the view using as a view name or a view file path/alias. A view name is resolved in the following way − A view name can omit the extension. For example, the about view corresponds to the about.php file. If the view name starts with “/”, then if currently active module is forum, and the view name is comment/post, the path would be @app/modules/forum/views/comment/post. If there is no active module, the path would be @app/views/comment/post. If the view name starts with “//”, the corresponding path would be @app/views/ViewName. For example, //site/contact corresponds to @app/views/site/contact.php. If the view name is contact, and the context controller is SiteController, then the path would be @app/views/site/contact.php. If the price view is rendered within the goods view, then price would be resolved as @app/views/invoice/price.php if it is being rendered in the @app/views/invoice/goods.php. Accessing Data in Views To access data within a view, you should pass the data as the second parameter to the view rendering method. Step 1 − Modify the actionAbout of the SiteController. public function actionAbout() { $email = “[email protected]”; $phone = “+78007898100″; return $this->render(”about”,[ ”email” => $email, ”phone” => $phone ]); } In the code given above, we pass two variables $email and $phone to render in the About view. Step 2 − Change the about view code. <?php /* @var $this yiiwebView */ use yiihelpersHtml; $this->title = ”About”; $this->params[”breadcrumbs”][] = $this->title; ?> <div class = “site-about”> <h1><?= Html::encode($this->title) ?></h1> <p> This is the About page. You may modify the following file to customize its content: </p> <p> <b>email:</b> <?= $email ?> </p> <p> <b>phone:</b> <?= $phone ?> </p> <code><?= __FILE__ ?></code> </div> We have just added two variables that we received from the SiteController. Step 3 − Type the URL http://localhost:8080/index.php?r=site/about in the web browser, you will see the following. Print Page Previous Next Advertisements ”;
Yii – Ad Hoc Validation
Yii – Ad Hoc Validation ”; Previous Next Sometimes you need to validate values that are not bound to any model. You can use the yiibaseDynamicModel class, which supports defining both attributes and rules on the fly. Step 1 − Add the actionAdHocValidation method to the SiteController. public function actionAdHocValidation() { $model = DynamicModel::validateData([ ”username” => ”John”, ”email” => ”[email protected]” ], [ [[”username”, ”email”], ”string”, ”max” => 12], [”email”, ”email”], ]); if ($model->hasErrors()) { var_dump($model->errors); } else { echo “success”; } } In the above code, we define a “dynamic” model with username and email attributes and validate them. Step 2 − Type http://localhost:8080/index.php?r=site/ad-hoc-validation in the address bar of the web browser, you will see an error message because our email is 14 characters long. Custom Validators There are two types of custom validators − Inline validators Standalone validators An inline validator is defined by a model method or an anonymous function. If an attribute fails the validation, you should call the yiibaseModel::addError() method to save the error message. The following example of the RegistrationForm validates the city property, so it can accept only two values – London and Paris. <?php namespace appmodels; use Yii; use yiibaseModel; class RegistrationForm extends Model { public $username; public $password; public $email; public $country; public $city; public $phone; public function rules() { return [ [”city”, ”validateCity”] ]; } public function validateCity($attribute, $params) { if (!in_array($this->$attribute, [”Paris”, ”London”])) { $this->addError($attribute, ”The city must be either “London” or “Paris”.”); } } } ?> A standalone validator extends the yiivalidatorsValidator class. To implement the validation logic, you should override the yiivalidatorsValidator::validateAttribute() method. Step 1 − To implement the previous example using the standalone validator, add a CityValidator.php file to the components folder. <?php namespace appcomponents; use yiivalidatorsValidator; class CityValidator extends Validator { public function validateAttribute($model, $attribute) { if (!in_array($model->$attribute, [”Paris”, ”London”])) { $this->addError($model, $attribute, ”The city must be either “Paris” or “London”.”); } } } ?> Step 2 − Then, modify the RegistrationForm model this way. <?php namespace appmodels; use appcomponentsCityValidator; use Yii; use yiibaseModel; class RegistrationForm extends Model { public $username; public $password; public $email; public $country; public $city; public $phone; public function rules() { return [ [”city”, CityValidator::className()] ]; } } ?> Print Page Previous Next Advertisements ”;
Yii – Asset Conversion
Yii – Asset Conversion ”; Previous Next Instead of writing CSS or JS code, developers often use extended syntax, like LESS, SCSS, Stylus for CSS and TypeScript, CoffeeScript for JS. Then they use special tools to convert these files into real CSS and JS. The asset manager in Yii converts assets in extended syntax into CSS and JS, automatically. When the view is rendered, it will include the CSS and JS files in the page, instead of the original assets in extended syntax. Step 1 − Modify the DemoAsset.php file this way. <?php namespace appassets; use yiiwebAssetBundle; use yiiwebView; class DemoAsset extends AssetBundle { public $basePath = ”@webroot”; public $baseUrl = ”@web”; public $js = [ ”js/demo.js”, ”js/greeting.ts” ]; public $jsOptions = [”position” => View::POS_HEAD]; } ?> We have just added a typescript file. Step 2 − Inside the web/js directory, create a file called greeting.ts with the following code. class Greeter { constructor(public greeting: string) { } greet() { return this.greeting; } }; var greeter = new Greeter(“Hello from typescript!”); console.log(greeter.greet()); In the above code, we define a Greeter class with a single method greet(). We write our greeting to the chrome console. Step 3 − Go to the URL http://localhost:8080/index.php. You will notice that the greeting.ts file is converted into the greeting.js file as shown in the following screenshot. Following will be the output. Print Page Previous Next Advertisements ”;