Yii incomplete solution (2), yii complete solution

Source: Internet
Author: User

Yii incomplete solution (2), yii complete solution

I have encountered many Yii problems recently. I would like to provide several solutions to Yii problems again.


1. 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);


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

<Form action = "your url" method = 'post' enctype = "multipart/form-data" id = 'fileform'> <p style = 'display: inline-Block'> file Upload </p> <input id = 'file1' name = 'file1' type = 'file'> </input> <br/> <input type = 'submit 'value = 'upload'> </form>
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. <Br/> "; 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! <Br/> "; 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! ');}

3. 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);

4. Check the validity of the 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;}


5. 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 ));


When the PHP framework Yii framework uses yiic commands, the system prompts that "phpexe" is not an internal or external command. How can this problem be solved?

The reason is that the yiic. bat of Yii cannot find php.exe.
Solution: use notepad ++ to open yii/framework/yiic. bat and modify
If "% PHP_COMMAND %" = "" set php_command#php.exe
→ If "% PHP_COMMAND %" = "" set PHP_COMMAND = D: \ wamp \ php \ php.exe

Modify
If "% PHP_COMMAND %" = "" set PHP_COMMAND = C: \ wamp \ bin \ php \ php5.4.3 \ php.exe

Why can't YII introduce files?

Since you use the absolute path, enter the framework/yii directly. php's complete path is fine (TIPS: Start-> Run, delete the characters in it, and drag the file into the text box that is running ).
We recommend that you use relative paths../indicates the current directory, and ../indicates the upper level (parent level) of the directory where the current file is located)
 

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.