PHP's YII framework uses some of the error-solving methods and recommendations, YII framework _php Tutorial

Source: Internet
Author: User
Tags tmp folder

PHP's YII framework uses some of the error-solving methods and recommendations that YII framework


This article is intended to document the development process of Yii small problem solution, not comprehensive, not authoritative, not a tutorial. I have written, think can solve the problem, later may also use, remember it.

1. The introduction of Js and Css files in Yii.
Let's start with the simplest question, it's not a problem, it's just a grammar. Suppose our JS files are placed in the same level of Protected JS folder, CSS files are placed in and protected the same layer of CSS folder, well, the specification is like this ... Then we can write in the corresponding view interface as follows, CSS and JS function parameters are different oh ... (It's been tuned for one hours before.) )
The second parameter to register the JS file is the location of JS, optionally three: Cclientscript::P os_head in the HEAD section Cclientscript::P Os_begin placed at the beginning of the Body cclientscript::P os_e ND placed at the end of the Body, no special requirements will not be filled ... The second parameter to register the Css file is media, which is interested in the students point here, the current is still the default is good ...
For JS such as Jquery, with Registercorescript will not cause strange strange mistakes ...

2. Yii Isnewrecord Repair
The Isnewrecord attribute of the Model of Yii is very useful and can be discussed according to this attribute. However, if we open the transaction mechanism or other circumstances, causing the data to be inserted and then rolled back, there is no record in the database, but Isnewrecord is flase, that is, it is not a new record. The solution is to use the primary key to access the database, to determine whether it is a new record, and we have to use this property before the first to handle the following. 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)     

3.Yii Generate hidden input fields
Although it is easy to write an input field (not display:none), but sometimes jiabuzhu need to follow YII form code format ah, anyway, a word ...

4. Yii Generate drop-down menu
Most of the time we need a drop-down menu in the form, when the Chtml listdata is very useful. If there are very few fields in our database, such as 0 and 1, you can write as follows:

At this time, you see is the drop-down menu is and no, select ' is ' when submitting this field is filled with 1, ' No ' is 0. Of course, it's not always that simple, we can add a function to the Model to generate an array of drop-down menus and then call it in the view. The data for this function can be written by itself, or found in the database. The following uses the Listdata, which means that the name is the value of the model in the ID key.

/* Written in model */Public Function getuseroptions () {   $models = User::model ()->findall ();   $models = User::model ()->findallbyattributes (Array (' is_regeister ' = ' 1 '));   Return Chtml::listdata ($models, ' id ', ' name '); }  

5.Yii Open transaction mechanism
When you save several records to the database at the same time, you may need to turn on the transaction mechanism. Yii opens the transaction mechanism very easily, as long as three words is enough.

/* Open transaction mechanism */$transaction = Yii::app ()->db->begintransaction (); try {   /* succeeds commit */   $transaction->commit ();} catch (Exception $e) {   

A more complete look like this:

if ($_post[' Modela ')} {/   * turn on transaction mechanism */   $transaction = Yii::app ()->db->begintransaction ();   Try   {     /* omit a heap of logic here *     /$modelA->save ();     $modelB->save ();      /* Success is commit *     /$transaction->commit ();     $this->redirect (Array (' View ', ' id ' = = $model->id));   }   catch (Exception $e)   {     $transaction->rollback ();   

But I will generally like the following, what is the benefit of your own experience ...

if ($_post[' Modela ')} {/   * turn on transaction mechanism */   $transaction = Yii::app ()->db->begintransaction ();   Try   {     $validated = true;      /* Omit a bunch of logic here *     /$valid = $modelA->save ();     $validated = $valid & $validated;      /* Continue to omit a bunch of logic here *     /$valid = $modelB->save ();     $validated = $valid & $validated;      /* Success is commit */     if ($validated)     {       $transaction->commit ();       $this->redirect (Array (' View ', ' id ' = = $model->id));     }     else     {       /* failed to roll back       /$transaction->rollback ();     }   }   catch (Exception $e)   {     $transaction->rollback ();   

6. association table query the same field error.
Sometimes we build two tables, but two tables have the same field, and when using Cdbcriteria for query search, if there are no additional settings, there will be query errors, probably meaning that the Mysql statement is ambiguous. At this time, we set an alias on the main table, and then query the relevant fields when the name is added to the line.
For example: Two Model, Post and User, all have an ID, which we can write like this:

$criteria =new Cdbcriteria;  $criteria->alias = "POST";  $criteria->with = Array (' user ');  $criteria->compare (' post.id ', $Post->id,true);  

7. File Upload
said that this is not a Yii, the basic is the original HTML and PHP, lazy points, put here directly.
The following is html,action to your own URL, and the ID and name are also defined by yourself.

This is the server side to receive and save the file code, the file finally saved to the attached folder in the file 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 is wrong! Please try again.
"; Exit; } else { if (file_exists ("attached/tmp/". $file _name)) echo "File already exists! This time does not save! "; else { if (!is_dir ("attached/tmp/")) {/ * new folder, default permissions 777, true means that you can recursively create the */ if (!mkdir (" attached/tmp/", 0777,true) { echo" cannot find the Attached/tmp folder, and the creation failed!)
"; Exit; } } /* This function is only used to upload the file's movement * /Move_uploaded_file ($tmp _name, "attached/tmp/". $file _name); }

The following is the current date folder where the existing files are moved from the Old_file path to the attached/file. Here's the mobile with rename

/* Create 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 (' Cannot create folder! ');}   }  /* Move File */$file _name = basename ($old _file); $finish = Rename ($old _file, $dir. $file _name); if (! $finish) {   

8.YIi Scene and Security fields
To view the current Model scene:

View the security fields for the scene. The security field means that the data will not be filtered by Yii when it is submitted by the user. Once found that the Web page submitted some of the things have some not, tuned for a long time to know that the scene under the section is filtered.

Force assignment avoids the rule Rule filter field. Use SetAttributes to force the removal of Yii's security filter, as long as the second parameter is assigned a value of false. However, this can only be done for fields that are owned by the Model when it is generated, and it is better to define the scene and then specify a safe field in rule if you want to not filter all fields that include your own definition.

if (Isset ($_get[' Po '))   

Check date format legitimacy
Sometimes we need to verify that the user fill in the date is legal, you can use the following function.

function Checkdatetime ($dateStr, $format = "y-m-d h:i:s") {   $time = Strtotime ($DATESTR);   $checkDate = Date ($format, $time);    

Yii renders multiple model
Believe the novice have doubts, _form inside the form is to render a model and then submitted to the Controller to save data, if you want to render more than one model?
Below, we assume that there are two model classes, called Person and Addr, and what we want to do is to render a few Addr in the _form of a man, meaning that one can have several addresses. The basic idea is still very simple, that is, you define the model to be rendered in the controller and then pass it to the view interface, and finally still receive the Post data in the controller. Mainly is the writing problem only, I believe below everybody can understand, has the question child shoes again the message is good.

Inside the controller  $model =new person;/* $addrs store an array of ADDR model, and put a few you just look at it. */$addrs = array ();  if (isset ($_post[' person ")) {   $model->attributes = $_post[' person '];   /* Omit a heap of logic *   /foreach ($_post[' Addr '] as $one _addr)   {     $addr = new Addr ();     $addr->attributes = $one _addr;     /* Omit another heap of logic here *   /}}  $this->render (' Create ', array (   ' model ' = $model,   ' Addrs ' = $addrs,)) ;   In view  /* You can cycle through multiple model */$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));   ...; }  

http://www.bkjia.com/PHPjc/1049138.html www.bkjia.com true http://www.bkjia.com/PHPjc/1049138.html techarticle PHP's Yii framework uses some of the error resolution methods and recommendations, YII framework This article is intended to record the yii development process of small problem solutions, not comprehensive, not authoritative, not a tutorial. Own ...

  • 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.