Some errors in the use of the YII framework in PHP and suggestions for _php tips

Source: Internet
Author: User

This article is intended to record the small problem solution in the development process of YII, 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, and that's not a problem, it's just grammar. Suppose our JS files are placed in the same level as Protected JS folder, CSS files are placed in the same layer with protected CSS folder, OK, the specification is like this ... Then we can in the corresponding view interface to write the following, CSS and JS function parameters are different oh ... (It's been tuned for one hours before.) )
The second parameter of the registration JS file is JS position, optional three: Cclientscript::P Os_head placed in the head part of the Cclientscript::P Os_begin placed in the body at the beginning of Cclientscript::P o S_end placed at the end of the body, no special requirements will not be filled out ... The second parameter for registering a CSS file is media, and interested students point here, or the default is good now ...
For Jquery such as JS, with Registercorescript will not cause inexplicable wonderful mistakes ...

Register JS file 
Yii::app ()->clientscript->registerscriptfile (Yii::app ()->baseurl. ' /js/project1.js ', Cclientscript::P os_head); 
Register CSS File 
yii::app ()->clientscript->registercssfile (Yii::app ()->baseurl. ' /css/project1.css '); 
Register jquery file 
Yii::app ()->clientscript->registercorescript (' jquery '); 

2. Yii Isnewrecord Repair
the Isnewrecord property 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, then there is no record in the database, but Isnewrecord is flase, that 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 need to use this attribute to first click on the following processing. 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 Build hidden input field
Although it is easy to write an input field (not just display:none), but sometimes jiabuzhu need to follow YII form code format ah, anyway, a word ...

<?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 Pull-down Menu
a lot of times we need a pull-down menu in form, when Chtml's listdata is very handy. If there are only a few possible fields in our database, such as 0 and 1, you can write as follows:

echo $form->dropdownlist ($model, ' Is_marry ', Array (' 0 ' => ' no ', ' 1 ' => ')); 

At this time, you see is the and no Drop-down menu, select ' is ' to submit this field is filled with 1, ' No ' is 0. Of course, often more than that, we can add a function to the Model to generate an array of Drop-down menus, and then call in the view. The data for this function can be written by itself or found in the database. The following uses the Listdata, the specific meaning is the model in the ID as the key, name is the value.

/* Write in Model */public 
function getuseroptions () 
{ 
  $models = User::model ()->findall 
  (); $models = User::model ()->findallbyattributes (Array (' Is_regeister ' => ' 1 ')); 
  Return Chtml::listdata ($models, ' id ', ' name '); 
} 
 
* * Written in the View interface/ 
echo $form->dropdownlist ($model, ' user_id ', User::model ()->getuseroptions ()); 


5.Yii Open transaction mechanism
when you save several records to a database, you may need to start a transaction mechanism. YII Open the transaction mechanism is easy, as long as three words is enough.

/* OPEN TRANSACTION Mechanism * * * 
$transaction = Yii::app ()->db->begintransaction (); 
Try 
{ 
  /* success commits 
  /$transaction->commit (); 
} 
catch (Exception $e) 
{ 
  $transaction->rollback (); 
} 

More complete like this:

if ($_post[' Modela ']) 
{/ 
  * open transaction mechanism */ 
  $transaction = Yii::app ()->db->begintransaction (); 
  Try 
  { 
    */* Here is omitted a bunch of logic * 
    /$modelA->save (); 
    $modelB->save (); 
 
    /* Success is a 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 ']) 
{/ 
  * open transaction mechanism */ 
  $transaction = Yii::app ()->db->begintransaction (); 
  Try 
  { 
    $validated = true; 
 
    /* Here omit a bunch of logic * 
    /$valid = $modelA->save (); 
    $validated = $valid & $validated; 
 
    /* Here continue to omit a bunch of logic * 
    /$valid = $modelB->save (); 
    $validated = $valid & $validated; 
 
    /* Successful COMMIT/ 
    if ($validated) 
    { 
      $transaction->commit (); 
      $this->redirect (Array (' View ', ' id ' => $model->id)); 
    } 
    else 
    { 
      //* rollback/$transaction->rollback () 
  } catch (Exception $e) 
  { 
    $transaction->rollback (); 
  } 
} 

6. The associated table query has the same field error.
Sometimes we build two tables, but two tables have the same field, in the use of Cdbcriteria with associated query search, if there is no additional settings, it will appear query errors, probably means that the Mysql statement fuzzy. At this point, we can set an alias on the main table, and then check the relevant fields to be careful to add the name on the line.
For example: Two Model, Post and User, all have an ID, which we can write 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
Speaking of this is not a Yii, basically are native HTML and PHP, lazy points, just put it here.
The following is html,action to your own URL, and ID and name are defined by you.

<form action= "Your url" method= ' post ' enctype= ' multipart/form-data ' id= ' fileform ' > 
  <p ' Display: Inline-block ' > File upload </p><input id= ' file1 ' name= ' file1 ' type= ' file '  ></input> 
  <br/ > 
  <input type= ' submit ' value= ' upload ' > 
</form> 

This is the server to receive and save the file code, the file was last saved in the attached folder in the file folder:

if (Isset ($_files[' file1 ')) 
{ 
  $xlsfile = $_files[' file1 ']; 
  $tmp _name = $xlsfile [' Tmp_name ']; 
  /* Get filename * * * 
  $file _name = basename ($xlsfile _name); 
 
  if ($xlsfile [' Error '] > 0] 
  { 
    echo file is out of error!) Please try again. <br/> "; 
    Exit; 
  } 
  else 
  { 
    if (file_exists ("attached/tmp/". $file _name)) 
      echo "File already exists! This time do not save! "; 
    else 
    { 
      if (!is_dir ("attached/tmp/")) 
      {/ 
        * new folder, default permissions 777, true means that you can recursively create/ 
        if (!mkdir (" attached/tmp/", 0777,true)) 
        { 
          echo" could not find the Attached/tmp folder and failed to create! <br/> "; 
          Exit; 
        } 
      } 
 
      /* This function is only used for uploading files of mobile 
      /Move_uploaded_file ($tmp _name, "attached/tmp/". $file _name);}} 
 

The following is the move of existing files from the Old_file path to the current date folder within the Attached/file. Here's the move 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) 
{ 
  exit (' cannot move file! '); 
} 

8.YIi Scene and Security field
View the current Model scene:

Var_dump ($model->scenario); 

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

$arr = $model->getsafeattributenames ($model->scenario); 
Var_dump ($arr); 

Force assignment to avoid rule filter fields. SetAttributes can be used to force the removal of security filtering for Yii, as long as the second parameter is assigned false. However, this can only take effect on the fields that this Model generates, and it is better to define the scene and then specify the safe field in rule if you want to filter all fields that include your definition.

if (Isset ($_get[' Po ')) 
  $model->setattributes ($_get[' Post '],false); 

Check date format legality
sometimes we need to verify that the date the user fills out is legitimate, and you can use the following function.

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

Yii renders multiple model
    believe the novice has doubts, _form inside the form is to render a model and then submit to controller save data, What if you want to render multiple model?
    below, we assume that there are two model classes, called person and Addr, what we want to do is to render a few ADDR's model in the _form of someone, meaning that one can have several addresses 。 The basic idea is actually still very simple, that is, you define the model to be rendered in the controller and then pass to the view interface, and finally still receive the data from the Post in controller. Mainly is the problem of writing, I believe that we can understand the following, there are questions about the children's shoes and then leave a message.

In the controller inside 
 
$model =new person; 
/* $addrs storage ADDR model Array, put a few you see do it! 
/$addrs = Array (); 
 
if (isset ($_post[' person ')) 
{ 
  $model the->attributes = $_post[' person ']; 
  /* Here omit a bunch of logical 
  /foreach ($_post[' Addr '] as $one _addr) 
  { 
    $addr = new Addr (); 
    $addr->attributes = $one _addr; 
    /* Here omit another heap of logic 
/}} 
 
$this->render (' Create ', array ( 
  ' model ' => $model, 
  ' Addrs ' => $ Addrs, 
)); 
 
 
Inside the view 
 
/* You can loop out 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)); 
  ...; 
} 
 
/* can also specify the output by number of a model 
/echo $form->labelex ($addrs [0], "[0]postcode"); 
echo $form->textfield ($addrs [0], "[0]postcode", Array (' Size ' =>10, ' maxlength ' =>10)); 

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.