Some error solutions and suggestions in the use of PHP Yii Framework, yii Framework _ PHP Tutorial

Source: Internet
Author: User
Some incorrect solutions and suggestions in the use of PHP Yii Framework, yii Framework. The Yii Framework of PHP is intended to record the minor problem solution in the yii development process, which is incomplete, unauthoritative, and not a tutorial. Some incorrect solutions and suggestions in the Yii Framework of PHP, yii Framework

This article is intended to record the minor problem solutions in the Yii development process, which are incomplete, unauthoritative, and not a tutorial. I wrote it myself and thought it could solve the problem. I may use it later. just remember.

1. introduction of Js and Css files in Yii.
Let's start with the simplest problem. it's not a problem, but a syntax. Suppose that all our js files are placed in the js folder at the same layer as protected, and all css files are placed in the css folder at the same layer as protected. well, the specification is like this... then we can write the corresponding view interface as follows. the parameters of css and js functions are different... (I called it for an hour ..)
The second parameter for registering a js file is the location where the js file is stored. three options are available: CClientScript: POS_HEAD; Head; CClientScript: POS_BEGIN; and CClientScript :: POS_END is placed at the end of the Body. you do not need to enter it unless otherwise specified... the second parameter for registering a Css file is media. if you are interested, click here. it is still the default parameter...
For js like Jquery, using registerCoreScript will not cause inexplicable errors...

// Register the js file Yii: app ()-> clientScript-> registerScriptFile (Yii: app ()-> baseUrl. '/js/project1.js', CClientScript: POS_HEAD); // register the css file Yii: app ()-> clientScript-> registerCssFile (Yii: app () -> baseUrl. '/css/project1.css'); // register the Jquery file Yii: app ()-> clientScript-> registerCoreScript ('jquery ');

2. Yii isNewRecord repair
The isNewRecord attribute of the Model of Yii is very useful and can be discussed based on this attribute. However, if we have enabled the transaction mechanism or other circumstances, this record is not found in the database, but isNewRecord is flase, that is to say, it is no longer a new record. The solution is to use the primary key to access the database and determine whether it is a new record. before using this attribute, we need to process it as follows. The following Model is Post and the primary key is id:

if(!$model->isNewRecord) {   $db_exist = Post::model()->findByPk($model->id);   if($db_exist == NULL)     $model->isNewRecord = true; } 

3. Yii generate hidden input fields
Although it is easy to write an input field by yourself (not display: none), sometimes the format of the Yii form code is not enough. it is just one sentence...

<?php echo $form->hiddenField($model,'name'); ?> <?php if($model->isNewRecord) echo $form->hiddenField($model,'path',array('size'=>60,'maxlength'=>128,'id'=>'path1')); ?> 

4. Yii generate drop-down menu
In most cases, we need a drop-down menu in form. at this time, the Chtml listdata is very useful. If the fields in our database are only few possible, such as 0 and 1, you can write as follows:

Echo $ form-> dropDownList ($ model, 'is _ marry', array ('0' => 'no', '1' => 'yes '));

In this case, you can see the "yes" and "no" drop-down menus. when you select "yes", this field is set to 1 and "no" is set to 0. Of course, it is often not that simple. we can add a function in the Model to generate an array of the drop-down menu, and then call it in the view. The data of this function can be written by yourself or searched in the database. Listdata is used below, which specifically means that the id in the model is the key and the name is the value.

/* Write in the model */public function getUserOptions () {$ models = User: model ()-> findAll (); $ models = User: model () -> findAllByAttributes (array ('is _ regeister '=> '1'); return CHtml: listdata ($ models, 'id', 'name ');} /* write it in the view interface */echo $ form-> dropDownList ($ model, 'User _ id', user: model ()-> getUserOptions ());

5. Yii enable transaction mechanism
When you save several records to the database at the same time, you may need to enable the transaction mechanism. Yii is easy to enable the transaction mechanism. only three sentences are enough.

/* Enable the transaction mechanism */$ transaction = Yii: app ()-> db-> beginTransaction (); if try {/* succeeds, commit */$ transaction-> commit ();} catch (Exception $ e) {$ transaction-> rollBack ();}

Relatively complete:

If ($ _ POST ['modela']) {/* enable transaction mechanism */$ transaction = Yii: app ()-> db-> beginTransaction (); try {/* a bunch of logic is omitted here */$ modelA-> save (); $ modelB-> save (); /* if the operation succeeds, commit */$ transaction-> commit (); $ this-> redirect (array ('View ', 'id' => $ model-> id);} catch (Exception $ e) {$ transaction-> rollBack ();}}

However, I will generally be like the following. please feel free to understand the advantages...

If ($ _ POST ['modela']) {/* enable transaction mechanism */$ transaction = Yii: app ()-> db-> beginTransaction (); try {$ validated = true;/* a bunch of logic is omitted here */$ valid = $ modelA-> save (); $ validated = $ valid & $ validated; /* a bunch of logic will be omitted here */$ valid = $ modelB-> save (); $ validated = $ valid & $ validated; /* if it succeeds, commit */if ($ validated) {$ transaction-> commit (); $ this-> redirect (array ('View ', 'id' => $ model-> id);} else {/* roll back if it is unsuccessful */$ transaction-> rollBack ();}} catch (Exception $ e) {$ transaction-> rollBack ();}}

6. An error occurred while querying the same field in the associated table.
Sometimes we create two tables, but the two tables have the same fields. If no additional settings are made when using CDbCriteria for the with association query, a query error occurs, the approximate meaning is that the Mysql statement is fuzzy. At this time, we can set a single name in the master table, and then pay attention to add the name when querying related fields.
For example, two models, Post, and User have an id, which can be written as follows:

$criteria=new CDbCriteria;  $criteria->alias = "post";  $criteria->with = array('user');  $criteria->compare('post.id',$Post->id,true);  $model = Post::model()->find($criteria); 

7. file Upload
This is not Yii. it is basically native HTML and PHP. if you are too lazy to score, just put it here.
The following is HTML, and the action is changed to your own url. the id and name are also defined by you.

 

This is the code for the server to receive and save the file. the file is finally saved to the file folder in the attached folder:

If (isset ($ _ FILES ['file1']) {$ xlsfile = $ _ FILES ['file1']; $ tmp_name = $ xlsfile ['tmp _ name']; /* Get file name */$ file_name = basename ($ xlsfile_name); if ($ xlsfile ['error']> 0) {echo "file upload error! Please try again.
"; Exit;} else {if (file_exists (" attached/tmp/". $ file_name) echo" the file already exists! This time will not be saved! "; Else {if (! Is_dir ("attached/tmp/") {/* create a folder. the default permission is 777. true means that the folder can be recursively created */if (! Mkdir ("attached/tmp/", 0777, true) {echo "the folder attached/tmp cannot be found and creation failed!
"; Exit ;}}/* This function is only used to move the uploaded file */move_uploaded_file ($ tmp_name," attached/tmp/". $ file_name );}}}

The following shows how to move an existing file from the old_file path to the current date folder in attached/file. Here, rename is used for moving.

/* Create a folder */$ date = date ('Y-m-D', time (); $ date = str_replace ('-', "", $ date ); $ dir = "attached/file /". $ date. '/'; if (! Is_dir ($ dir) {if (! Mkdir ($ dir, 0777, true) {exit ('folder cannot be created! ') ;}}/* Move the file */$ file_name = basename ($ old_file); $ finish = rename ($ old_file, $ dir. $ file_name); if (! $ Finish) {exit ('file cannot be moved! ');}

8. YIi scenarios and security fields
View the current Model scenario:

var_dump($model->scenario); 

View the security fields of a scenario. The security field means that the data is not filtered out by Yii when submitted by the user. I once found that some of the items submitted on the web page were missing. after a long call, I realized that some of the items were filtered out in that scenario.

$arr = $model->getSafeAttributeNames($model->scenario); var_dump($arr); 

Force value assignment to prevent fields from being filtered by rule rules. You can use setAttributes to forcibly cancel Yii security filtering, as long as the second parameter is assigned to false. However, this can only take effect for fields that are generated when the Model is created. if you do not need to filter all fields that contain your own definitions, it is better to define the scenario and specify the security field in the rule.

if(isset($_GET['Po']))   $model->setAttributes($_GET['Post'],false); 

Check validity of date format
Sometimes we need to check whether the date entered by the user is valid. the following function can be used.

function checkDatetime($dateStr, $format = "Y-m-d H:i:s") {   $time = strtotime($dateStr);   $checkDate = date($format, $time);    return $checkDate == $dateStr; } 

Yii renders multiple models
I believe that all new users have doubts. the forms in _ form render a model and submit it to the controller to save the data. what if I want to render multiple models?
Next, let's assume there are two model classes called Person and Addr respectively. what we want to do is to render several Addr models in a Person's _ form, A person can have several addresses. The basic idea is actually quite simple, that is, you define the model to be rendered in the controller, then pass it to the view interface, and finally still receive Post data in the controller. This is mainly about writing. I believe everyone can understand it below. if you have any questions, leave a message.

// In the controller, $ model = new Person;/* $ addrs stores the Addr model array. just put a few of them and you can do it. */$ addrs = array (); if (isset ($ _ POST ['person ']) {$ model-> attributes = $ _ POST ['person']; /* a bunch of logic is omitted here */foreach ($ _ POST ['addr '] as $ one_addr) {$ Addr = new addr (); $ addr-> attributes = $ one_addr;/* The other logic is omitted here */} $ this-> render ('create ', array ('model' => $ model, 'addrs '=> $ addrs ,)); // In the view, you can output multiple models cyclically */$ num = count ($ addrs); for ($ I = 0; $ I <$ num; + $ I) {echo $ form-> labelEx ($ addrs [$ I], "[{$ I}] postcode "); echo $ form-> textField ($ addrs [$ I], "[{$ I}] postcode", array ('size' => 10, 'maxlength' => 10 ));...;} /* You can also specify a number to output a model */echo $ form-> labelEx ($ addrs [0], "[0] postcode "); echo $ form-> textField ($ addrs [0], "[0] postcode", array ('size' => 10, 'maxlength' => 10 ));

This article is intended to record the minor problem solutions in the Yii development process, which are incomplete, unauthoritative, and not a tutorial. Yourself...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.