DHTMLX integration with yii framework not working? - yii

I integrated dhtmlx with yii frame work based on the instruction given in their site.( DHTMLX With YII )
here my controller file code,
include_once(YII_BASE_PATH . "/dhtmlx/connector/grid_connector.php");
include_once(YII_BASE_PATH . "/dhtmlx/connector/scheduler_connector.php");
include_once(YII_BASE_PATH . "/dhtmlx/connector/db_phpyii.php");
class EventsController extends Controller
{
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','grid','scheduler'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
public function actionGrid()
{
// $this->render('grid'); //loads the 'grid' view that we will create later
$model = new Events();
$this->render('grid',array(
'model'=>$model,
));
}
public function actionGrid_data()
{
//$model = new Events;
$grid = new GridConnector(Events::model(), "PHPYii");
$grid->configure("-","event_id", "start_date, end_date, event_name");
$grid->render();
}
}
==============================================================================
my view file
<script src="<?php echo AT::getAdminBaseUrl()?>/dhtmlx/grid/dhtmlxcommon.js" type="text/javascript" charset="utf-8"></script>
<script src="<?php echo AT::getAdminBaseUrl()?>/dhtmlx/grid/dhtmlxgrid.js" type="text/javascript" charset="utf-8"></script>
<script src="<?php echo AT::getAdminBaseUrl()?>/dhtmlx/grid/dhtmlxgridcell.js" type="text/javascript" charset="utf-8"></script>
<script src="<?php echo AT::getAdminBaseUrl()?>/dhtmlx/dhtmlxdataprocessor.js" type="text/javascript" charset="utf-8"></script>
<script src="<?php echo AT::getAdminBaseUrl()?>/dhtmlx/connector/connector.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="<?php echo AT::getAdminBaseUrl()?>/dhtmlx/grid/dhtmlxgrid.css" type="text/css" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="<?php echo AT::getAdminBaseUrl()?>/dhtmlx/grid/skins/dhtmlxgrid_dhx_skyblue.css" type="text/css" media="screen" title="no title" charset="utf-8">
<div id="grid_here" style="width:600px; height:400px;"> </div>
<?php
// $this->widget('zii.widgets.CListView', array(
// 'dataProvider'=>$dataProvider,
// 'itemView'=>'_view',
// ));
?>
<script type="text/javascript">
mygrid = new dhtmlXGridObject('grid_here');
mygrid.setHeader("Start date,End date,Text");
mygrid.init();
mygrid.loadXML("./grid_data"); //refers to the 'Grid_data' action we created in the previous step
var dp = new dataProcessor("./grid_data"); //refers to the 'Grid_data' action as well
dp.init(mygrid);
</script>
===========================================================================
my modal file
<?php
/**
* This is the model class for table "vendor".
*
* The followings are the available columns in table 'vendor':
* #property integer $id
* #property string $vendor_name
* #property string $vendor_description
* #property string $status
*/
class Events extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return Vendor the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'events';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('event_name', 'length', 'max'=>255),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('start_date,end_date,event_name', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'event_id' => 'Event Id',
'start_date' => 'Start Date',
'end_date' => 'End Date',
'event_name' => 'Event Name',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('event_id',$this->event_id);
$criteria->compare('start_date',$this->start_date,true);
$criteria->compare('end_date',$this->end_date,true);
$criteria->compare('event_name',$this->event_name,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
when I run the action grid i got the error in the popup window like below,
I don't know what is the issue?. I doubt that may be '$grid = new GridConnector(Events::model(), "PHPYii"); ' this one causes the problem.
How can I resolve this one?. Can anyone help me?.

Yes. I found answer, I need to edit the core extension file dhtmlx/connector/db_phpyii.php
like below, (Remove &-reference operator).
Shows – $temp[]=&$obj->getAttributes();
Should read – $temp[]=$obj->getAttributes();
Ref: http://www.dhtmlx.com/blog/?p=1648

Please have a look at the question: Strict Standards: Only variables should be assigned by reference PHP 5.4
Looks like you're using strict standards and passing an object with a reference operator in line 16 of /dhtmlx/connector/db_phpyii.php.

Related

Save data in a model from a different view

I have two tables, business and review business, in review business I have user_id, business_id,rating and review field. I want to write a review, for that purpose, I need rating and review fields from the review business table, and I want to show them in a view of business which I called (user_business.php). I successfully bring the rating and review field from the review_business table, and user is able to give his review, but the thing is the data is not saving in the review business model. I am posting my code, please find the error.
This is my business controller.
<?php
class BusinessController extends RController
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/admin';
/**
* #return array action filters
*/
public function filters()
{
return array(
// 'accessControl', // perform access control for CRUD operations
// 'postOnly + delete', // we only allow deletion via POST request
'rights',
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
public function actionUserbusiness($id) // this is userbusiness
{
//render main layout
$this->layout='main';
$model2 = new ReviewBusiness(); getting fields of review business
$this->render('userbusiness',array(
'model'=>$this->loadModel($id),
'reviewmodel'=>$model2
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Business;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Business']))
{
$rnd = rand(0, 9999); // generate random number between 0-9999
$model->attributes = $_POST['Business'];
$uploadedFile = CUploadedFile::getInstance($model, 'image');
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$model->image = $fileName;
if ($model->save()) {
$uploadedFile->saveAs(Yii::app()->basePath . '/../img/' . $fileName);
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Business']))
{
//$model->attributes=$_POST['Business'];
$_POST['Business']['image'] = $model->image;
$model->attributes=$_POST['Business'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
if($model->save())
{ if(!empty($uploadedFile)) // check if uploaded file is set or not
{
$uploadedFile->saveAs(Yii::app()->basePath.'/../img/'.$model->image);
}
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Business');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Business('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Business']))
$model->attributes=$_GET['Business'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return Business the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=Business::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param Business $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='business-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
Now view of userbusiness is given below. Oh and I am using dzraty extension for rating.
<?php $form=$this->beginWidget('bootstrap.widgets.BsActiveForm', array(
'id'=>'review-business-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<?php
$this->widget('ext.DzRaty.DzRaty', array(
'model' => $reviewmodel,
'attribute' => 'rating',
)); ?>
</ul>
</div>
<div class="form-group">
<label>Review Text</label>
<?php echo $form->textarea($reviewmodel,'review',array('maxlength'=>500)); ?>
</div>
<?php echo BsHtml::submitButton('Submit', array('color' => BsHtml::BUTTON_COLOR_PRIMARY)); ?>
<?php $this->endWidget(); ?>

how to use main.php in modules in Yii

I'm creating an admin dashboard in Yii. here is my structure
- Protected
|
- Modules
|
-- Views
|
---Layouts
|
--- main.php
--- column1.php
--- column2.php
|
- Themes
|
-- Bootstrap
|
--- Views
|
--- Admin
|
---- Layouts
|
---- main.php
for some reason, my admin panel keeps reading the main.php in the bootstrap folder instead of /modules/admin/views/layouts/main.php
/**
* Base class for all admin controllers.
*/
class AdminController extends CController
{
/**
* #var string the default layout for the controller view. Defaults to '/layouts/column1',
* meaning using a single column layout. See 'protected/modules/admin/views/layouts/column2.php'.
*/
public $layout = '/layouts/column2';
/**
* #var string the pageTitle of the current page.
*/
public $pageTitle = "";
/**
* #var array the breadcrumbs of the current page. The value of this property will
* be assigned to {#link CBreadcrumbs::links}. Please refer to {#link CBreadcrumbs::links}
* for more details on how to specify this property.
*/
public $breadcrumbs = array();
/**
* #var array admin context menu items. This property will be assigned to {#link TbMenu::items}.
*/
public $adminMenu = array();
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow',
'users' => array('#'),
//'expression' => 'Yii::app()->user->isAdmin'
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
public function beforeRender($view)
{
if ($this->adminMenu && !Yii::app()->user->isGuest)
$this->renderPartial('/layouts/clips/_admin_clip');
return parent::beforeRender($view);
}
}
here is my column2.php
<?php /* #var $this Controller */ ?>
<?php $this->beginContent('/layouts/main'); ?>
<div class="row">
<div class="span2" id="sidebar">
<?php
//a clip is a piece of captured output that can be inserted elsewhere.
if (isset($this->clips['adminMenuClipID']))
echo $this->clips['adminMenuClipID'];
?>
</div>
<div class="span10" id="main-content">
<?php echo $content; ?>
</div>
</div>
<?php $this->endContent(); ?>
how do i make it ready main.php from /modules/admin/views/layouts/main.php ?
You need to alter the path to the decorative view that your view calls in CController::beginContent():
$this->beginContent('application.modules.admin.views.layouts.column2')
assuming the path is modules/admin/views/layouts/column2.php

Laravel Auth::check() only returns true on post page

I am new at Laravel and having some struggles with simple login and authorization pages.
I followed an awesome video tutorial by laracasts.com (credits for that one, really helpful).
My situation:
When implementing authorization to my page, the page after the login succeeds the authorization check.
So: loginform > press button > You are now logged in.
My problem:
After I press the back button and refresh, it still gives the login form. It shouldn't.
routes.php
<?php
Route::get('login', 'SessionsController#create');
Route::get('logout', 'SessionsController#destroy');
Route::resource('users', 'UsersController');
Route::resource('sessions', 'SessionsController');
Route::get('admin', function(){
return 'Admin page';
})->before('auth');
Route::get('dashboard', ['before' => 'auth', function(){
return 'Dashboard';
}]);
SessionsController.php:
<?php
class SessionsController extends BaseController{
public function create()
{
if ( Auth::check() )
{
Redirect::to('/admin');
}
return View::make('sessions.create');
}
public function store()
{
if( Auth::attempt(Input::only('email', 'password')) )
{
// if(Auth::check())
// {
// return 'check worked!';
// }
return 'Welcome ' . Auth::user()->username; //You are now logged in
}
return 'Failed';
}
public function destroy()
{
Auth::logout();
return Redirect::to('sessions.create');
}
}
User.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
public $timestamps = true;
protected $fillable = ['username', 'email', 'password'];
protected $guarded = ['id'];
public static $rules = [
'username' => 'required',
'password' => 'required'
];
public $errors;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
public function isValid()
{
$validation = Validator::make($this->attributes, static::$rules );
if($validation->passes() )
return true;
$this->errors = $validation->messages();
return false;
}
}
create.blade.php
#extends('layouts.default')
#section('content')
<h1>Create new user</h1>
{{Form::open([ 'route' => 'users.store' ]) }}
<div>
{{Form::label('username', 'Username: ')}}
{{Form::text('username')}}
{{$errors->first('username')}}
</div>
<div>
{{Form::label('password', 'Password: ')}}
{{Form::password('password')}}
{{$errors->first('password')}}
</div>
<div>
{{Form::submit('Create User')}}
</div>
{{Form::close() }}
#stop
So to speak: It never goes to the 'admin' route.
Your authentication code is correct and working. What you have is something going wrong in any other part of your Laravel application, web server or even PHP.
Since we are not seeing all your code, we can just guess, so my first one would be the Session not being stored correctly. Currently logged users are stored in Laravel Session. So, check your session driver, if it's in 'native', change it to 'database', but you'll have to create a sessions table, look at the docs. If you are already using 'database', change it back to 'native' or even 'file'.
Instead of run
return 'Welcome ' . Auth::user()->username; //You are now logged in
Please try
return Redirect::to('admin');

registration form using Yii framework

I am new to Yii framework. I want to implement a registration form with Yii .
I check the blog project on its demo projects but it hasn't got a registration form.
Do anyone knows a tutorial about this issue?
For registration system.
You should follow the steps.
1st you make a table user/signup/register as you wish.
Now create CRUD for that so you can easily insert your data in user table.
I have a table and it have five different fields i.e. id, name, conatct_no, email, password
Now you create a folder in view named it "register".
In view you just made a file index.php and register.php
register.php is your form. which you can made.
Register.php
<h2>Registration Form</h2>
<div class="form">
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($model); ?>
<div class="row">
<?php echo CHtml::activeLabel($model,'Name'); ?>
<?php echo CHtml::activeTextField($model,'name') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Contact Number'); ?>
<?php echo CHtml::activeTextField($model,'contact_no') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'email'); ?>
<?php echo CHtml::activeTextField($model,'email') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'password'); ?>
<?php echo CHtml::activePasswordField($model,'password') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Retype Password'); ?>
<?php echo CHtml::activePasswordField($model,'retypepassword') ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('Register'); ?>
</div>
<?php echo CHtml::endForm(); ?>
</div><!-- form -->
Now you need a controller file for registration i.e. registerController.php.
registerController.php
class registerController extends Controller
{
public function actionIndex() {
$this->render('index');
}
public function actionRegister() {
$model = new RegisterForm ;
$newUser = new User;
if(isset($_POST['RegisterForm'])) {
$model->attributes = $_POST['RegisterForm'];
if($model->validate()) {
$newUser->name = $model->name ;
$newUser->contact_no = $model->contact_no;
$newUser->email = $model->email;
$newUser->password = $model->password;
if($newUser->save()) {
$this->_identity = new UserIdentity($newUser->email,$newUser->password);
if($this->_identity->authenticate())
Yii::app()->user->login($this->_identity);
$this->redirect(Yii::app()->user->returnUrl);
}
}
}
$this->render('register',array('model'=>$model));
}
}
Now you need a model file for your validation. RegisterForm.php
class RegisterForm extends CFormModel
{
public $contact_no ;
public $name ;
public $email;
public $password ;
public $retypepassword;
public function tableName()
{
return 'user';
}
public function rules() {
return array(
array('name, contact_no, email, password, retypepassword', 'required'),
array('name, email, password, retypepassword', 'length', 'max'=>200),
array('email', 'email', 'message'=>'Please insert valid Email'),
array('contact_no', 'length', 'max'=>30),
array('retypepassword', 'required', 'on'=>'Register'),
array('password', 'compare', 'compareAttribute'=>'retypepassword'),
array('id, name, contact_no, email', 'safe', 'on'=>'search'),
);
}
}
You need to also change the UserIdentity.php file in your protected/component directory.
class UserIdentity extends CUserIdentity
{
private $_id ;
public function authenticate()
{
$email = strtolower($this->username);
$user = User::model()->find('LOWER(email)=?',array($email));
if($user === null)
$this->errorCode = self::ERROR_USERNAME_INVALID ;
else if(!$user->password === $this->password)
$this->errorCode = self::ERROR_PASSWORD_INVALID ;
else {
$this->_id = $user->id ;
$this->username = $user->email ;
$this->errorCode = self::ERROR_NONE ;
}
return $this->errorCode == self::ERROR_NONE ;
return !$this->errorCode;
}
public function getId() {
return $this->_id ;
}
}
That's it.
It is a complete registration form set up, i have made it myself.
If you are first timer, then you need to understand how the controller work and how controller interact with view and model. If you are already familiar with it then you may easily can make registration system with your own.
Here is the link which help you to understand yii.
http://www.yiiframework.com/screencasts/
Thanks.
First, create a table for Users. Generate a User model and a controller based on this table using gii and adjust the code to your liking. Inside the User controller create a function to handle the registration:
function actionRegister() {
$model = new User('register');
// collect user input data
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
// validate user input and redirect to the previous page if valid
$model->setAttributes(array(
'datereg' => time(), //additional data you want to insert
'lastlogin' => time() //additional
));
if($model->save())
{
//optional
$login=new LoginForm;
$login->username = $_POST['User']['username'];
$login->password = $_POST['User']['password'];
if($login->validate() && $login->login())
$this->redirect('/pages/welcome');
}
}
else
// display the registration form
$this->render('register',array('model'=>$model));
}
You must have a valid view file (register.php)
$login=new LoginForm;
$login->username = $_POST['User']['username'];
$login->password = $_POST['User']['password'];
if($login->validate() && $login->login())
$this->redirect('/pages/welcome');
This block of code 'authenticates' the user and logs him in right after a successful registration. It uses CUserIdentity. $login->login() hashes the password.
Also, you must have something like this to process the data before it inserts it into the table
public function beforeSave() {
if(parent::beforeSave() && $this->isNewRecord) {
$this->password = md5($this->password);
}
return true;
}
Hashing the password inside the controller is also fine. However I wanna do everything DB related inside the Model class.
You may notice that I didn't call $model-validate() here. This is because $model->save() also calls the validation method. More info: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-detail
It is easy to create a form with yii using CActiveForm.
Here is a link of yii documentation :: Yii CActiveForm
You must create Registration form, using CAvtiveForm (see LoginForm for example).
Create your Users model.
Create controller:
class UsersController extends Controller
{
public function actionSignup()
{
$model = new RegistrationForm;
if (isset($_POST['RegistrationForm'])) {
if ($model->validate()) {
$user = new Users;
$user->populateRecord($form->attributes);
$user->save();
$this->redirect(Yii::app()->createUrl('/'));
}
}
$this->render('signup', array('model' => $model));
}
}

Return value from external action in Yii

How to pass a value from external action in Yii to it's parent controller?
for example:
External action looks like:
<?php
class uploadAction extends CAction
{
/**
* Runs the action.
* This method is invoked by the controller owning this action.
*/
public function run()
{
.....
$fileName=$result['filename'];//GETTING FILE NAME
$this->controller->image = $fileName; // this line does not work!!
}
}
when I try to get the value of images in the parent controller, nothing return!! Any help I will appreciate.
Update:
I am using an extension to upload a file .. eajaxupload .
There is a long form.. have many fields, one of them is image. I want to upload that image by Ajax before submiting the whole form. Of course after user click on create button.. the controller must take all fields plus image name to store in the db.
The view ..
<div class="elem">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array('class'=>'inputbox grid-11-12','maxlength'=>45)); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="elem">
<?php echo $form->labelEx($model,'password1'); ?>
<?php echo $form->passwordField($model,'password1',array('class'=>'inputbox grid-11-12')); ?>
<?php echo $form->error($model,'password1'); ?>
</div>
<div class="elem">
<?php echo $form->labelEx($model,'password2'); ?>
<?php echo $form->passwordField($model,'password2',array('class'=>'inputbox grid-11-12')); ?>
<?php echo $form->error($model,'password2'); ?>
</div>
<div class="elem">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('class'=>'inputbox grid-11-12','maxlength'=>45)); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="elem">
<label for="content">User Image:</label>
<?php $this->widget('ext.EAjaxUpload.EAjaxUpload',
array(
'id'=>'uploadFile',
'config'=>array(
'action'=>Yii::app()->request->baseUrl .'/backend.php/user/upload',
'allowedExtensions'=>array("jpg"),//array("jpg","jpeg","gif","exe","mov" and etc...
'sizeLimit'=>3*1024*1024,// maximum file size in bytes
'minSizeLimit'=>50*1024,// minimum file size in bytes
'multiple'=>false,
//'onComplete'=>Yii::app()->request->baseUrl .'/backend.php/user/saveStuff/?fn='. "js:function(id, fileName, responseJSON){ alert(fileName); }",
//'messages'=>array(
// 'typeError'=>"{file} has invalid extension. Only {extensions} are allowed.",
// 'sizeError'=>"{file} is too large, maximum file size is {sizeLimit}.",
// 'minSizeError'=>"{file} is too small, minimum file size is {minSizeLimit}.",
// 'emptyError'=>"{file} is empty, please select files again without it.",
// 'onLeave'=>"The files are being uploaded, if you leave now the upload will be cancelled."
// ),
//'showMessage'=>"js:function(message){ alert(message); }"
)
)); ?>
</div>
This is the controller ..
<?php
class UserController extends Controller
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column1';
public $image;
.......
public function actions()
{
return array(
'upload' => array(
'class' => 'ext.actions.uploadAction',
),
);
}
........
public function actionCreate()
{
$model=new User;
$profile=new UserProfile;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
$profile->attributes=$_POST['UserProfile'];
if(!$this->saveUser($model, $profile))
Yii::app()->user->setFlash('error', 'Not Saved :)!');
}
$this->render('create',array(
'model'=>$model,
'profile'=>$profile,
));
}
public function saveUser($model, $profile)
{
$userValid = $model->validate();
$profileValid = $profile->validate();
$valid = $userValid && $profileValid;
if($valid)
{
$model->save(false);
$profile->user_id = $model->id;
$profile->image = !is_null($this->image)? $this->image : null; // name of image file which uploaded
$profile->save(false);
Yii::app()->user->setFlash('success', 'Saved :)!');
$this->redirect(array('index'));
return true;
}
return false;
}
}
the external action in details is:
<?php
class uploadAction extends CAction
{
/**
* Runs the action.
* This method is invoked by the controller owning this action.
*/
public function run()
{
Yii::import("ext.EAjaxUpload.qqFileUploader");
// make the directory to store the pic:
$folder=Yii::getPathOfAlias('webroot') .'/images/' . $this->controller->id . '/';// folder for uploaded files
if(!is_dir($folder))
{
mkdir($folder);
chmod($folder, 0755);
// the default implementation makes it under 777 permission, which you could possibly change
//recursively before deployment, but here's less of a headache in case you don't
}
$allowedExtensions = array("jpg");//array("jpg","jpeg","gif","exe","mov" and etc...
$sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload($folder);
$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
$fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
$fileName=$result['filename'];//GETTING FILE NAME
$this->controller->image = $fileName; // ??????
echo $return;// it's array
}
}
do this:
$this->controller->image = $fileName; // this line does not work!!
$this->controller->renderText($this->controller->image);
I bet this will display the $fileName.
Where do you try to access the controllers image property?
Values are not preserved between requests.
I've done something similar to this using a callback.
So in my controller actions() configuration I have a line:
'onSuccessCallback' => 'myCallback'
In my action class, at the end of run() I have:
call_user_func( array($this->getController(),$this->onSuccessCallback), $fileName);
In the controller I have
function myCallback($fileName)
{
this->image = $fileName;
}
I can then access the property from the controller via
$this->image