Problem:
You cannot directly assign values to model attributes in the Yii framework.
First take a look at the source code:
$menuId = isset($_GET['mId']) ? $_GET['mId'] : 0; if ($menuId) { $menu = MenuTree::model()->findByPk($menuId); if(isset($_POST['MenuTree'])){ var_dump($menu->attributes); //在这里跟踪输出的数据正常,跟表单中填写的一致 $menu->attributes = $_POST['MenuTree']; //对attributes进行赋值 var_dump($menu->attributes); //输出$menu模型中的attributes,不正常,结果并不是POST接收到的值,而是数据库原有的值 if($menu->save()){ Yii::app()->user->setFlash('success',"恭喜您,修改成功,请继续!"); $this->redirect(Yii::app()->createUrl('menu/contentEdit',array('mId'=>$menuId))); }else{ throw new CException("修改失败!"); } } $this->render("contentEdit", array('menu' => $menu)); } else { throw new CHttpException('404'); }
(Related article tutorials recommended: yii framework)
This is the action code of a page, Looking at the comments in the code, you can see the error that occurred. The POST assignment is not accepted. I tried using the setAttributes function and it was also not accepted. The output is still the value of the original database, but it can be operated with updateByPk. After tracking the setAttributes function, I found that The function definition is as follows:
public function setAttributes($values,$safeOnly=true) { if(!is_array($values)) return; $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames()); foreach($values as $name=>$value) { if(isset($attributes[$name])) $this->$name=$value; else if($safeOnly) $this->onUnsafeAttribute($name,$value); } }
Analyzing the setAttributes function code, we can see that security checks are performed when assigning values to attributes, so I think the reason may be that the rules of the model are not set to be safe for the fields modified in those forms. After finding the reason, the solution comes out. In the rules of the model, just set the attribute of the field you want to modify to safe.
public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( // more code... array('field1 , field2 ,field3', 'safe'), //Modify the fields in here // more code... ); }
For more programming-related content, please pay attention to the Programming Introduction column on the php Chinese website!
The above is the detailed content of Failed to assign values to model attributes in Yii. For more information, please follow other related articles on the PHP Chinese website!

The Yii community provides rich support and resources. 1. Visit the official website and GitHub to get the documentation and code. 2. Use official forums and StackOverflow to solve technical problems. 3. Report bugs and make suggestions through GitHubIssues. 4. Use documents and tutorials to learn the Yii framework.

Yii is a high-performance PHP framework designed for fast development and efficient code generation. Its core features include: MVC architecture: Yii adopts MVC architecture to help developers separate application logic and make the code easier to maintain and expand. Componentization and code generation: Through componentization and code generation, Yii reduces the repetitive work of developers and improves development efficiency. Performance Optimization: Yii uses latency loading and caching technologies to ensure efficient operation under high loads and provides powerful ORM capabilities to simplify database operations.

Yii is a high-performance framework based on PHP, suitable for rapid development of web applications. 1) It adopts MVC architecture and component design to simplify the development process. 2) Yii provides rich functions, such as ActiveRecord, RESTfulAPI, etc., which supports high concurrency and expansion. 3) Using Gii tools can quickly generate CRUD code and improve development efficiency. 4) During debugging, you can check configuration files, use debugging tools and view logs. 5) Performance optimization suggestions include using cache, optimizing database queries and maintaining code readability.

YiiremainspopularbutislessfavoredthanLaravel,withabout14kGitHubstars.ItexcelsinperformanceandActiveRecord,buthasasteeperlearningcurveandasmallerecosystem.It'sidealfordevelopersprioritizingefficiencyoveravastecosystem.

Yii is a high-performance PHP framework that is unique in its componentized architecture, powerful ORM and excellent security. 1. The component-based architecture allows developers to flexibly assemble functions. 2. Powerful ORM simplifies data operation. 3. Built-in multiple security functions to ensure application security.

Yii framework adopts an MVC architecture and enhances its flexibility and scalability through components, modules, etc. 1) The MVC mode divides the application logic into model, view and controller. 2) Yii's MVC implementation uses action refinement request processing. 3) Yii supports modular development and improves code organization and management. 4) Use cache and database query optimization to improve performance.

Strategies to improve Yii2.0 application performance include: 1. Database query optimization, using QueryBuilder and ActiveRecord to select specific fields and limit result sets; 2. Caching strategy, rational use of data, query and page cache; 3. Code-level optimization, reducing object creation and using efficient algorithms. Through these methods, the performance of Yii2.0 applications can be significantly improved.

Developing a RESTful API in the Yii framework can be achieved through the following steps: Defining a controller: Use yii\rest\ActiveController to define a resource controller, such as UserController. Configure authentication: Ensure the security of the API by adding HTTPBearer authentication mechanism. Implement paging and sorting: Use yii\data\ActiveDataProvider to handle complex business logic. Error handling: Configure yii\web\ErrorHandler to customize error responses, such as handling when authentication fails. Performance optimization: Use Yii's caching mechanism to optimize frequently accessed resources and improve API performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.