2014-05-09

hello guys now i am going to show you how to Reuse File Upload Code across multiple projects.

for to reuse this code now am going to create new Behavior called UploadBehavior under components directory that extends CActiveRecordBehavior this is because our Behavior work on events such as beforeSave() and beforeValidate().

now create two public properties called $field and $paths one for attribute that accepts file uploads and another for path to save the uploaded file.

now create beforeValidate() function that assigns uploaded file to the $field as

now create beforeSave() function to save uploaded file to the $path

now our Behavior is ready to reuse. the whole Class looks like this:

now it is time for Action. attach this behavior to your model like this:

for this example you can use Post model of Blog demo. in real time it can be any of your model that allows file uploads.

that's all. from now we can reuse this behavior across multiple projects without rewriting the similar code for every file upload.

Note: the above example shows you how to manage single file upload only. you can slightly rewrite the above behavior to accept multiple file uploads.

Extending this Behavior: this behavior can be further extended such as uploading file with unique file name, delete previous file when new file is uploaded, delete the uploaded file when parent record is deleted.

Download this behavior: you can download this behavior from here

Suggestions and Feedbacks: you can suggest your ideas and feedback regarding this.

Show more