Yii Framework Forum: [Extension] Xupload - Yii Framework Forum

Jump to content

  • (20 Pages)
  • +
  • « First
  • 8
  • 9
  • 10
  • 11
  • 12
  • Last »
  • You cannot start a new topic
  • You cannot reply to this topic

[Extension] Xupload

#181 User is offline   zanforlin 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 20
  • Joined: 06-September 11

Posted 17 September 2012 - 08:56 AM

here is the html code generated.

Thanks again

Attached File(s)


0

#182 User is offline   Asgaroth 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 371
  • Joined: 17-July 09
  • Location:Bogota, Colombia

Posted 17 September 2012 - 05:14 PM

Not sure what is happening, couldn't tell with out taking a deeper look, and I don't have much time currently I'm moving away so I may even be without internet for a while too.
- Extension: Dynamic DataProvider Behavior
- Extension: XUpload - jQuery File Upload Extension
- Extension: PhpQuickProfiler - A Web Log Router that will help you profile your application
- Extension: XDateView - A Date grouped Grid View
- Extension: Foundation - An easy to use, powerful, and flexible framework for building prototypes and production code on any kind of device.



- Wiki: How to generate Yii like Documentation
- Wiki: How to re enable logging during unit testing
0

#183 User is offline   zanforlin 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 20
  • Joined: 06-September 11

Posted 17 September 2012 - 06:32 PM

ok! no problem... thanks!
0

#184 User is offline   Thiago Prado 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 27-August 12

Posted 20 September 2012 - 09:20 AM

I tried everything but I always get 500 Internal Server Error when I click upload.

Controller (controllers/ArquivoController)

class ArquivoController extends GxController {

////////////XUPLOAD///////////

	public function actions() {
		return array('upload' => array('class' => 'xupload.actions.XUploadAction', 'path' => Yii::app() -> getBasePath() . "/../images/uploads", "publicPath" => Yii::app()->getBaseUrl()."/images/uploads" ), );
	}

////////////XUPLOAD///////////
	
	public function actionCreate() {
	$model = new Arquivo;
    Yii::import( "xupload.models.XUploadForm" );
    //$photos = new XUploadForm;
    //Check if the form has been submitted
    if( isset( $_POST['Arquivo'] ) ) {
        //Assign our safe attributes
        $model->attributes = $_POST['Arquivo'];
        //Start a transaction in case something goes wrong
        $transaction = Yii::app( )->db->beginTransaction( );
        try {
            //Save the model to the database
            if($model->save()){
                $transaction->commit();
            }
        } catch(Exception $e) {
            $transaction->rollback( );
            Yii::app( )->handleException( $e );
        }
    }
    $this->render( '_form', array(
        'model' => $model,
        'photos' => $photos,
    ));
	}
	
	////////////XUPLOAD///////////
	
	public function actionUpload( ) {
    Yii::import( "xupload.models.XUploadForm" );
    //Here we define the paths where the files will be stored temporarily
    $path = realpath( Yii::app( )->getBasePath( )."/../images/uploads/tmp/" )."/";
    $publicPath = Yii::app( )->getBaseUrl( )."/images/uploads/tmp/";
 
    //This is for IE which doens't handle 'Content-type: application/json' correctly
    header( 'Vary: Accept' );
    if( isset( $_SERVER['HTTP_ACCEPT'] ) 
        && (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) ) {
        header( 'Content-type: application/json' );
    } else {
        header( 'Content-type: text/plain' );
    }
 
    //Here we check if we are deleting and uploaded file
    if( isset( $_GET["_method"] ) ) {
        if( $_GET["_method"] == "delete" ) {
            if( $_GET["file"][0] !== '.' ) {
                $file = $path.$_GET["file"];
                if( is_file( $file ) ) {
                    unlink( $file );
                }
            }
            echo json_encode( true );
        }
    } else {
        $model = new XUploadForm;
        $model->file = CUploadedFile::getInstance( $model, 'file' );
        //We check that the file was successfully uploaded
        if( $model->file !== null ) {
            //Grab some data
            $model->mime_type = $model->file->getType( );
            $model->size = $model->file->getSize( );
            $model->name = $model->file->getName( );
            //(optional) Generate a random name for our file
            $filename = md5( Yii::app( )->user->id.microtime( ).$model->name);
            $filename .= ".".$model->file->getExtensionName( );
            if( $model->validate( ) ) {
                //Move our file to our temporary dir
                $model->file->saveAs( $path.$filename );
                chmod( $path.$filename, 0777 );
                //here you can also generate the image versions you need 
                //using something like PHPThumb
 
 
                //Now we need to save this path to the user's session
                if( Yii::app( )->user->hasState( 'images' ) ) {
                    $userImages = Yii::app( )->user->getState( 'images' );
                } else {
                    $userImages = array();
                }
                 $userImages[] = array(
                    "path" => $path.$filename,
                    //the same file or a thumb version that you generated
                    "thumb" => $path.$filename,
                    "filename" => $filename,
                    'size' => $model->size,
                    'mime' => $model->mime_type,
                    'name' => $model->name,
                );
                Yii::app( )->user->setState( 'images', $userImages );
 
                //Now we need to tell our widget that the upload was succesfull
                //We do so, using the json structure defined in
                echo json_encode( array( array(
                        "name" => $model->name,
                        "type" => $model->mime_type,
                        "size" => $model->size,
                        "url" => $publicPath.$filename,
                        "thumbnail_url" => $publicPath."thumbs/$filename",
                        "delete_url" => $this->createUrl( "upload", array(
                            "_method" => "delete",
                            "file" => $filename
                        ) ),
                        "delete_type" => "POST"
                    ) ) );
            } else {
                //If the upload failed for some reason we log some data and let the widget know
                echo json_encode( array( 
                    array( "error" => $model->getErrors( 'file' ),
                ) ) );
                Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ),
                    CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction" 
                );
            }
        } else {
            throw new CHttpException( 500, "Could not upload file" );
        }
    }}
	}



Form View (views/arquivo/_form)

<div class="form">


<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
	'id' => 'arquivo-form',
	'enableAjaxValidation' => false,
));
?>

	<p class="note">
		<?php echo Yii::t('app', 'Fields with'); ?> <span class="required">*</span> <?php echo Yii::t('app', 'are required'); ?>.
	</p>

	<?php echo $form->errorSummary($model); ?>

		<div class="row">
		<?php echo $form->labelEx($model,'nome'); ?>
		<?php echo $form->textField($model, 'nome', array('maxlength' => 255)); ?>
		<?php echo $form->error($model,'nome'); ?>
		</div><!-- row -->
		<div class="row">
		<?php echo $form->labelEx($model,'categoria_id'); ?>
		<?php echo $form->dropDownList($model, 'categoria_id', GxHtml::listDataEx(Categoria::model()->findAllAttributes(null, true))); ?>
		<?php echo $form->error($model,'categoria_id'); ?>
		</div><!-- row -->
		<div class="row">
		<?php echo $form->labelEx($model,'usuario_id'); ?>
		<?php echo $form->dropDownList($model, 'usuario_id', GxHtml::listDataEx(Usuario::model()->findAllAttributes(null, true))); ?>
		<?php echo $form->error($model,'usuario_id'); ?>
		</div><!-- row -->
		<div class="row">
            <?php echo $form->labelEx($model,'file'); ?>
            <?php
            $this->widget( 'xupload.XUpload', array(
                'url' => Yii::app( )->createUrl( "/arquivo/upload", array('id'=>$model->id)),
                //our XUploadForm
                'model' => $model,
                //We set this for the widget to be able to target our own form
                'htmlOptions' => array('id'=>'arquivo-form'),
                'attribute' => 'file',
                'multiple' => true,
                //Note that we are using a custom view for our widget
                //Thats becase the default widget includes the 'form' 
                //which we don't want here
                'formView' => 'application.views.arquivo._upload',
				
                )    
            );
            ?>
            <?php echo $form->error($model,'file'); ?>
        </div>


<div class="form-actions">
		<?php $this->widget('bootstrap.widgets.TbButton', array(
			'buttonType'=>'submit',
			'type'=>'primary',
			'label'=>$model->isNewRecord ? 'Criar' : 'Salvar',
		)); ?>
	</div>

<?php $this->endWidget(); ?>
</div><!-- form -->



Upload form (views/arquivo/_upload

<!-- The file upload form used as target for the file upload widget -->
<div class="row fileupload-buttonbar">
	<div class="span7">
		<!-- The fileinput-button span is used to style the file input field as button -->
		<span class="btn btn-success fileinput-button"> <i class="icon-plus icon-white"></i> <span>Add files...</span>
			<?php
            if ($this -> hasModel()) :
                echo CHtml::activeFileField($this -> model, $this -> attribute, $htmlOptions) . "\n";
            else :
                echo CHtml::fileField($name, $this -> value, $htmlOptions) . "\n";
            endif;
            ?>
		</span>
		<button type="submit" class="btn btn-primary start">
			<i class="icon-upload icon-white"></i>
			<span>Start upload</span>
		</button>
		<button type="reset" class="btn btn-warning cancel">
			<i class="icon-ban-circle icon-white"></i>
			<span>Cancel upload</span>
		</button>
		<button type="button" class="btn btn-danger delete">
			<i class="icon-trash icon-white"></i>
			<span>Delete</span>
		</button>
		<input type="checkbox" class="toggle">
	</div>
	<div class="span5">
		<!-- The global progress bar -->
		<div class="progress progress-success progress-striped active fade">
			<div class="bar" style="width:0%;"></div>
		</div>
	</div>
</div>
<!-- The loading indicator is shown during image processing -->
<div class="fileupload-loading"></div>
<br>
<!-- The table listing the files available for upload/download -->
<table class="table table-striped">
	<tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody>
</table>

0

#185 User is offline   Asgaroth 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 371
  • Joined: 17-July 09
  • Location:Bogota, Colombia

Posted 20 September 2012 - 09:59 AM

First if you are not ussing the generic upload action you do not need to install it in your controller, so remove this:

public function actions() {
                return array('upload' => array('class' => 'xupload.actions.XUploadAction', 'path' => Yii::app() -> getBasePath() . "/../images/uploads", "publicPath" => Yii::app()->getBaseUrl()."/images/uploads" ), );
        }


Now you have an uploadAction in your controller, that isn't customized, so it is still looking for an XUploadForm model, but in your actionCreate you are creating an 'Arquivo' model, so the if is failing and you are getting the 500: Could not upload file:

        $model = new XUploadForm;
        $model->file = CUploadedFile::getInstance( $model, 'file' );
        //We check that the file was successfully uploaded
        if( $model->file !== null ) { 
                ...
        } else {
            throw new CHttpException( 500, "Could not upload file" );
        }


so change it so that it search for your own model

        $model = new Arquivo;
        $model->file = CUploadedFile::getInstance( $model, 'file' );
        //We check that the file was successfully uploaded
        if( $model->file !== null ) { 
                ...
        } else {
            throw new CHttpException( 500, "Could not upload file" );
        }

- Extension: Dynamic DataProvider Behavior
- Extension: XUpload - jQuery File Upload Extension
- Extension: PhpQuickProfiler - A Web Log Router that will help you profile your application
- Extension: XDateView - A Date grouped Grid View
- Extension: Foundation - An easy to use, powerful, and flexible framework for building prototypes and production code on any kind of device.



- Wiki: How to generate Yii like Documentation
- Wiki: How to re enable logging during unit testing
0

#186 User is offline   Thiago Prado 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 27-August 12

Posted 20 September 2012 - 11:21 AM

View PostAsgaroth, on 20 September 2012 - 09:59 AM, said:

First if you are not ussing the generic upload action you do not need to install it in your controller, so remove this:

public function actions() {
                return array('upload' => array('class' => 'xupload.actions.XUploadAction', 'path' => Yii::app() -> getBasePath() . "/../images/uploads", "publicPath" => Yii::app()->getBaseUrl()."/images/uploads" ), );
        }


Now you have an uploadAction in your controller, that isn't customized, so it is still looking for an XUploadForm model, but in your actionCreate you are creating an 'Arquivo' model, so the if is failing and you are getting the 500: Could not upload file:

        $model = new XUploadForm;
        $model->file = CUploadedFile::getInstance( $model, 'file' );
        //We check that the file was successfully uploaded
        if( $model->file !== null ) { 
                ...
        } else {
            throw new CHttpException( 500, "Could not upload file" );
        }


so change it so that it search for your own model

        $model = new Arquivo;
        $model->file = CUploadedFile::getInstance( $model, 'file' );
        //We check that the file was successfully uploaded
        if( $model->file !== null ) { 
                ...
        } else {
            throw new CHttpException( 500, "Could not upload file" );
        }




Thanks for help!
I did as you told but still getting the error...

The widget

<div class="row">
            <?php echo $form->labelEx($model,'file'); ?>
            <?php
            $this->widget( 'xupload.XUpload', array(
                'url' => Yii::app( )->createUrl( "/arquivo/upload", array('id'=>$model->id)),
                //our XUploadForm
                'model' => $model,
                //We set this for the widget to be able to target our own form
                'htmlOptions' => array('id'=>'arquivo-form'),
                'attribute' => 'file',
                'multiple' => true,
                //Note that we are using a custom view for our widget
                //Thats becase the default widget includes the 'form' 
                //which we don't want here
                'formView' => 'application.views.arquivo._upload',
				
                )    
            );
            ?>
            <?php echo $form->error($model,'file'); ?>
        </div>


The controller

////////////XUPLOAD///////////
	
	public function actionCreate() {
	$model = new Arquivo;
    Yii::import( "xupload.models.XUploadForm" );
    //Check if the form has been submitted
    if( isset( $_POST['Arquivo'] ) ) {
        //Assign our safe attributes
        $model->attributes = $_POST['Arquivo'];
        //Start a transaction in case something goes wrong
        $transaction = Yii::app( )->db->beginTransaction( );
        try {
            //Save the model to the database
            if($model->save()){
                $transaction->commit();
            }
        } catch(Exception $e) {
            $transaction->rollback( );
            Yii::app( )->handleException( $e );
        }
    }
    $this->render( '_form', array(
        'model' => $model,
    ));
	}
	
	////////////XUPLOAD///////////
	
	public function actionUpload( ) {
    Yii::import( "xupload.models.XUploadForm" );
    //Here we define the paths where the files will be stored temporarily
    $path = realpath( Yii::app( )->getBasePath( )."/../images/uploads/tmp/" )."/";
    $publicPath = Yii::app( )->getBaseUrl( )."/images/uploads/tmp/";
 
    //This is for IE which doens't handle 'Content-type: application/json' correctly
    header( 'Vary: Accept' );
    if( isset( $_SERVER['HTTP_ACCEPT'] ) 
        && (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) ) {
        header( 'Content-type: application/json' );
    } else {
        header( 'Content-type: text/plain' );
    }
 
    //Here we check if we are deleting and uploaded file
    if( isset( $_GET["_method"] ) ) {
        if( $_GET["_method"] == "delete" ) {
            if( $_GET["file"][0] !== '.' ) {
                $file = $path.$_GET["file"];
                if( is_file( $file ) ) {
                    unlink( $file );
                }
            }
            echo json_encode( true );
        }
    } else {
        $model = new Arquivo;
        $model->file = CUploadedFile::getInstance( $model, 'file' );
        //We check that the file was successfully uploaded
        if( $model->file !== null ) {
            //Grab some data
            $model->mime_type = $model->file->getType( );
            $model->size = $model->file->getSize( );
            $model->name = $model->file->getName( );
            //(optional) Generate a random name for our file
            $filename = md5( Yii::app( )->user->id.microtime( ).$model->name);
            $filename .= ".".$model->file->getExtensionName( );
            if( $model->validate( ) ) {
                //Move our file to our temporary dir
                $model->file->saveAs( $path.$filename );
                chmod( $path.$filename, 0777 );
                //here you can also generate the image versions you need 
                //using something like PHPThumb
 
 
                //Now we need to save this path to the user's session
                if( Yii::app( )->user->hasState( 'images' ) ) {
                    $userImages = Yii::app( )->user->getState( 'images' );
                } else {
                    $userImages = array();
                }
                 $userImages[] = array(
                    "path" => $path.$filename,
                    //the same file or a thumb version that you generated
                    "thumb" => $path.$filename,
                    "filename" => $filename,
                    'size' => $model->size,
                    'mime' => $model->mime_type,
                    'name' => $model->name,
                );
                Yii::app( )->user->setState( 'images', $userImages );
 
                //Now we need to tell our widget that the upload was succesfull
                //We do so, using the json structure defined in
                echo json_encode( array( array(
                        "name" => $model->name,
                        "type" => $model->mime_type,
                        "size" => $model->size,
                        "url" => $publicPath.$filename,
                        "thumbnail_url" => $publicPath."thumbs/$filename",
                        "delete_url" => $this->createUrl( "upload", array(
                            "_method" => "delete",
                            "file" => $filename
                        ) ),
                        "delete_type" => "POST"
                    ) ) );
            } else {
                //If the upload failed for some reason we log some data and let the widget know
                echo json_encode( array( 
                    array( "error" => $model->getErrors( 'file' ),
                ) ) );
                Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ),
                    CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction" 
                );
            }
        } else {
            throw new CHttpException( 500, "Could not upload file" );
        }
    }}

0

#187 User is offline   Asgaroth 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 371
  • Joined: 17-July 09
  • Location:Bogota, Colombia

Posted 20 September 2012 - 11:25 AM

check that your form has enctype="multipart/form-data"
- Extension: Dynamic DataProvider Behavior
- Extension: XUpload - jQuery File Upload Extension
- Extension: PhpQuickProfiler - A Web Log Router that will help you profile your application
- Extension: XDateView - A Date grouped Grid View
- Extension: Foundation - An easy to use, powerful, and flexible framework for building prototypes and production code on any kind of device.



- Wiki: How to generate Yii like Documentation
- Wiki: How to re enable logging during unit testing
0

#188 User is offline   Thiago Prado 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 27-August 12

Posted 20 September 2012 - 11:31 AM

View PostAsgaroth, on 20 September 2012 - 11:25 AM, said:

check that your form has enctype="multipart/form-data"



Yes

The full form code

<div class="form">


<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
	'id' => 'arquivo-form',
	'enableAjaxValidation' => false,
	'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>

	<p class="note">
		<?php echo Yii::t('app', 'Fields with'); ?> <span class="required">*</span> <?php echo Yii::t('app', 'are required'); ?>.
	</p>

	<?php echo $form->errorSummary($model); ?>

		<div class="row">
		<?php echo $form->labelEx($model,'nome'); ?>
		<?php echo $form->textField($model, 'nome', array('maxlength' => 255)); ?>
		<?php echo $form->error($model,'nome'); ?>
		</div><!-- row -->
		<div class="row">
		<?php echo $form->labelEx($model,'categoria_id'); ?>
		<?php echo $form->dropDownList($model, 'categoria_id', GxHtml::listDataEx(Categoria::model()->findAllAttributes(null, true))); ?>
		<?php echo $form->error($model,'categoria_id'); ?>
		</div><!-- row -->
		<div class="row">
		<?php echo $form->labelEx($model,'usuario_id'); ?>
		<?php echo $form->dropDownList($model, 'usuario_id', GxHtml::listDataEx(Usuario::model()->findAllAttributes(null, true))); ?>
		<?php echo $form->error($model,'usuario_id'); ?>
		</div><!-- row -->
		<div class="row">
            <?php echo $form->labelEx($model,'file'); ?>
            <?php
            $this->widget( 'xupload.XUpload', array(
                'url' => Yii::app( )->createUrl( "/arquivo/upload", array('id'=>$model->id)),
                //our XUploadForm
                'model' => $model,
                //We set this for the widget to be able to target our own form
                'htmlOptions' => array('id'=>'arquivo-form'),
                'attribute' => 'file',
                'multiple' => true,
                //Note that we are using a custom view for our widget
                //Thats becase the default widget includes the 'form' 
                //which we don't want here
                'formView' => 'application.views.arquivo._upload',
				
                )    
            );
            ?>
            <?php echo $form->error($model,'file'); ?>
        </div>


<div class="form-actions">
		<?php $this->widget('bootstrap.widgets.TbButton', array(
			'buttonType'=>'submit',
			'type'=>'primary',
			'label'=>$model->isNewRecord ? 'Criar' : 'Salvar',
		)); ?>
	</div>

<?php $this->endWidget(); ?>
</div><!-- form -->



I don't known if it is a problem, but I'm using Giix
0

#189 User is offline   Asgaroth 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 371
  • Joined: 17-July 09
  • Location:Bogota, Colombia

Posted 20 September 2012 - 11:33 AM

Check your logs, the extension seems to be configured properly, it might be an issue with uploading files in your server.
- Extension: Dynamic DataProvider Behavior
- Extension: XUpload - jQuery File Upload Extension
- Extension: PhpQuickProfiler - A Web Log Router that will help you profile your application
- Extension: XDateView - A Date grouped Grid View
- Extension: Foundation - An easy to use, powerful, and flexible framework for building prototypes and production code on any kind of device.



- Wiki: How to generate Yii like Documentation
- Wiki: How to re enable logging during unit testing
0

#190 User is offline   Thiago Prado 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 27-August 12

Posted 20 September 2012 - 11:34 AM

View PostAsgaroth, on 20 September 2012 - 11:33 AM, said:

Check your logs, the extension seems to be configured properly, it might be an issue with uploading files in your server.


PHP, Apache or Yii log?
0

#191 User is offline   Asgaroth 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 371
  • Joined: 17-July 09
  • Location:Bogota, Colombia

Posted 20 September 2012 - 11:36 AM

View PostThiago Prado, on 20 September 2012 - 11:34 AM, said:

PHP, Apache or Yii log?


Most likely apache, since its a 500 server error, then php.
- Extension: Dynamic DataProvider Behavior
- Extension: XUpload - jQuery File Upload Extension
- Extension: PhpQuickProfiler - A Web Log Router that will help you profile your application
- Extension: XDateView - A Date grouped Grid View
- Extension: Foundation - An easy to use, powerful, and flexible framework for building prototypes and production code on any kind of device.



- Wiki: How to generate Yii like Documentation
- Wiki: How to re enable logging during unit testing
0

#192 User is offline   Thiago Prado 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 27-August 12

Posted 20 September 2012 - 11:46 AM

View PostAsgaroth, on 20 September 2012 - 11:36 AM, said:

Most likely apache, since its a 500 server error, then php.


Nothing in Apache and PHP logs...
Trying for one week to fix this error, getting crazy...

The full codes again


///FORM

<div class="form">


<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
	'id' => 'arquivo-form',
	'enableAjaxValidation' => false,
	'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>

	<p class="note">
		<?php echo Yii::t('app', 'Fields with'); ?> <span class="required">*</span> <?php echo Yii::t('app', 'are required'); ?>.
	</p>

	<?php echo $form->errorSummary($model); ?>

		<div class="row">
		<?php echo $form->labelEx($model,'nome'); ?>
		<?php echo $form->textField($model, 'nome', array('maxlength' => 255)); ?>
		<?php echo $form->error($model,'nome'); ?>
		</div><!-- row -->
		<div class="row">
		<?php echo $form->labelEx($model,'categoria_id'); ?>
		<?php echo $form->dropDownList($model, 'categoria_id', GxHtml::listDataEx(Categoria::model()->findAllAttributes(null, true))); ?>
		<?php echo $form->error($model,'categoria_id'); ?>
		</div><!-- row -->
		<div class="row">
		<?php echo $form->labelEx($model,'usuario_id'); ?>
		<?php echo $form->dropDownList($model, 'usuario_id', GxHtml::listDataEx(Usuario::model()->findAllAttributes(null, true))); ?>
		<?php echo $form->error($model,'usuario_id'); ?>
		</div><!-- row -->
		<div class="row">
            <?php echo $form->labelEx($model,'file'); ?>
            <?php
            $this->widget( 'xupload.XUpload', array(
                'url' => Yii::app( )->createUrl( "/arquivo/upload", array('id'=>$model->id)),
                //our XUploadForm
                'model' => $model,
                //We set this for the widget to be able to target our own form
                'htmlOptions' => array('id'=>'arquivo-form'),
                'attribute' => 'file',
                'multiple' => true,
                //Note that we are using a custom view for our widget
                //Thats becase the default widget includes the 'form' 
                //which we don't want here
                'formView' => 'application.views.arquivo._upload',
				
                )    
            );
            ?>
            <?php echo $form->error($model,'file'); ?>
        </div>


<div class="form-actions">
		<?php $this->widget('bootstrap.widgets.TbButton', array(
			'buttonType'=>'submit',
			'type'=>'primary',
			'label'=>$model->isNewRecord ? 'Criar' : 'Salvar',
		)); ?>
	</div>

<?php $this->endWidget(); ?>
</div><!-- form -->


///UPLOAD FORM

<!-- The file upload form used as target for the file upload widget -->
<div class="row fileupload-buttonbar">
	<div class="span7">
		<!-- The fileinput-button span is used to style the file input field as button -->
		<span class="btn btn-success fileinput-button"> <i class="icon-plus icon-white"></i> <span>Add files...</span>
			<?php
            if ($this -> hasModel()) :
                echo CHtml::activeFileField($this -> model, $this -> attribute, $htmlOptions) . "\n";
            else :
                echo CHtml::fileField($name, $this -> value, $htmlOptions) . "\n";
            endif;
            ?>
		</span>
		<button type="submit" class="btn btn-primary start">
			<i class="icon-upload icon-white"></i>
			<span>Start upload</span>
		</button>
		<button type="reset" class="btn btn-warning cancel">
			<i class="icon-ban-circle icon-white"></i>
			<span>Cancel upload</span>
		</button>
		<button type="button" class="btn btn-danger delete">
			<i class="icon-trash icon-white"></i>
			<span>Delete</span>
		</button>
		<input type="checkbox" class="toggle">
	</div>
	<div class="span5">
		<!-- The global progress bar -->
		<div class="progress progress-success progress-striped active fade">
			<div class="bar" style="width:0%;"></div>
		</div>
	</div>
</div>
<!-- The loading indicator is shown during image processing -->
<div class="fileupload-loading"></div>
<br>
<!-- The table listing the files available for upload/download -->
<table class="table table-striped">
	<tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody>
</table>


///CONTROLLER

<?php

class ArquivoController extends GxController {


	
	
	public function actionView($id) {
		$this->render('view', array(
			'model' => $this->loadModel($id, 'Arquivo'),
		));
	}


	public function actionUpdate($id) {
		$model = $this->loadModel($id, 'Arquivo');


		if (isset($_POST['Arquivo'])) {
			$model->setAttributes($_POST['Arquivo']);

			if ($model->save()) {
				$this->redirect(array('view', 'id' => $model->id));
			}
		}

		$this->render('update', array(
				'model' => $model,
				));
	}

	public function actionDelete($id) {
		if (Yii::app()->getRequest()->getIsPostRequest()) {
			$this->loadModel($id, 'Arquivo')->delete();

			if (!Yii::app()->getRequest()->getIsAjaxRequest())
				$this->redirect(array('admin'));
		} else
			throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
	}

	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('Arquivo');
		$this->render('index', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionAdmin() {
		$model = new Arquivo('search');
		$model->unsetAttributes();

		if (isset($_GET['Arquivo']))
			$model->setAttributes($_GET['Arquivo']);

		$this->render('admin', array(
			'model' => $model,
		));
	}
	
	////////////XUPLOAD///////////
	
	public function actionCreate() {
	$model = new Arquivo;
    Yii::import( "xupload.models.XUploadForm" );
    //Check if the form has been submitted
    if( isset( $_POST['Arquivo'] ) ) {
        //Assign our safe attributes
        $model->attributes = $_POST['Arquivo'];
        //Start a transaction in case something goes wrong
        $transaction = Yii::app( )->db->beginTransaction( );
        try {
            //Save the model to the database
            if($model->save()){
                $transaction->commit();
            }
        } catch(Exception $e) {
            $transaction->rollback( );
            Yii::app( )->handleException( $e );
        }
    }
    $this->render( 'create', array(
        'model' => $model,
    ));
	}
	
	////////////XUPLOAD///////////
	
	public function actionUpload( ) {
    Yii::import( "xupload.models.XUploadForm" );
    //Here we define the paths where the files will be stored temporarily
    $path = realpath( Yii::app( )->getBasePath( )."/../images/uploads/tmp/" )."/";
    $publicPath = Yii::app( )->getBaseUrl( )."/images/uploads/tmp/";
 
    //This is for IE which doens't handle 'Content-type: application/json' correctly
    header( 'Vary: Accept' );
    if( isset( $_SERVER['HTTP_ACCEPT'] ) 
        && (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) ) {
        header( 'Content-type: application/json' );
    } else {
        header( 'Content-type: text/plain' );
    }
 
    //Here we check if we are deleting and uploaded file
    if( isset( $_GET["_method"] ) ) {
        if( $_GET["_method"] == "delete" ) {
            if( $_GET["file"][0] !== '.' ) {
                $file = $path.$_GET["file"];
                if( is_file( $file ) ) {
                    unlink( $file );
                }
            }
            echo json_encode( true );
        }
    } else {
        $model = new Arquivo;
        $model->file = CUploadedFile::getInstance( $model, 'file' );
        //We check that the file was successfully uploaded
        if( $model->file !== null ) {
            //Grab some data
            $model->mime_type = $model->file->getType( );
            $model->size = $model->file->getSize( );
            $model->name = $model->file->getName( );
            //(optional) Generate a random name for our file
            $filename = md5( Yii::app( )->user->id.microtime( ).$model->name);
            $filename .= ".".$model->file->getExtensionName( );
            if( $model->validate( ) ) {
                //Move our file to our temporary dir
                $model->file->saveAs( $path.$filename );
                chmod( $path.$filename, 0777 );
                //here you can also generate the image versions you need 
                //using something like PHPThumb
 
 
                //Now we need to save this path to the user's session
                if( Yii::app( )->user->hasState( 'images' ) ) {
                    $userImages = Yii::app( )->user->getState( 'images' );
                } else {
                    $userImages = array();
                }
                 $userImages[] = array(
                    "path" => $path.$filename,
                    //the same file or a thumb version that you generated
                    "thumb" => $path.$filename,
                    "filename" => $filename,
                    'size' => $model->size,
                    'mime' => $model->mime_type,
                    'name' => $model->name,
                );
                Yii::app( )->user->setState( 'images', $userImages );
 
                //Now we need to tell our widget that the upload was succesfull
                //We do so, using the json structure defined in
                echo json_encode( array( array(
                        "name" => $model->name,
                        "type" => $model->mime_type,
                        "size" => $model->size,
                        "url" => $publicPath.$filename,
                        "thumbnail_url" => $publicPath."thumbs/$filename",
                        "delete_url" => $this->createUrl( "upload", array(
                            "_method" => "delete",
                            "file" => $filename
                        ) ),
                        "delete_type" => "POST"
                    ) ) );
            } else {
                //If the upload failed for some reason we log some data and let the widget know
                echo json_encode( array( 
                    array( "error" => $model->getErrors( 'file' ),
                ) ) );
                Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ),
                    CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction" 
                );
            }
        } else {
            throw new CHttpException( 500, "Could not upload file" );
        }
    }}
	}


///MODEL

<?php

/**
 * This is the model base class for the table "Arquivo".
 * DO NOT MODIFY THIS FILE! It is automatically generated by giix.
 * If any changes are necessary, you must set or override the required
 * property or method in class "Arquivo".
 *
 * Columns in table "Arquivo" available as properties of the model,
 * followed by relations of table "Arquivo" available as properties of the model.
 *
 * @property string $id
 * @property string $nome
 * @property string $categoria_id
 * @property string $usuario_id
 * @property string $file
 * @property string $photos
 * @property string $arquivo
 * @property string $name
 * @property string $type
 * @property string $size
 * @property string $url
 * @property string $thumbnail_url
 * @property string $delete_url
 *
 * @property Categoria $categoria
 * @property Usuario $usuario
 */
abstract class BaseArquivo extends GxActiveRecord {

	public static function model($className=__CLASS__) {
		return parent::model($className);
	}

	public function tableName() {
		return 'Arquivo';
	}

	public static function label($n = 1) {
		return Yii::t('app', 'Arquivo|Arquivos', $n);
	}

	public static function representingColumn() {
		return 'nome';
	}

	public function rules() {
		return array(
			array('nome, file, photos, arquivo, name, type, size, url, thumbnail_url, delete_url', 'length', 'max'=>255),
			array('categoria_id, usuario_id', 'length', 'max'=>11),
			array('nome, categoria_id, usuario_id, file, photos, arquivo, name, type, size, url, thumbnail_url, delete_url', 'default', 'setOnEmpty' => true, 'value' => null),
			array('id, nome, categoria_id, usuario_id, file, photos, arquivo, name, type, size, url, thumbnail_url, delete_url', 'safe', 'on'=>'search'),
		);
	}

	public function relations() {
		return array(
			'categoria' => array(self::BELONGS_TO, 'Categoria', 'categoria_id'),
			'usuario' => array(self::BELONGS_TO, 'Usuario', 'usuario_id'),
		);
	}

	public function pivotModels() {
		return array(
		);
	}

	public function attributeLabels() {
		return array(
			'id' => Yii::t('app', 'ID'),
			'nome' => Yii::t('app', 'Nome'),
			'categoria_id' => null,
			'usuario_id' => null,
			'file' => Yii::t('app', 'File'),
			'photos' => Yii::t('app', 'Photos'),
			'arquivo' => Yii::t('app', 'Arquivo'),
			'name' => Yii::t('app', 'Name'),
			'type' => Yii::t('app', 'Type'),
			'size' => Yii::t('app', 'Size'),
			'url' => Yii::t('app', 'Url'),
			'thumbnail_url' => Yii::t('app', 'Thumbnail Url'),
			'delete_url' => Yii::t('app', 'Delete Url'),
			'categoria' => null,
			'usuario' => null,
		);
	}
    
    public function behaviors()
	{
    return array('datetimeI18NBehavior' => array('class' => 'ext.DateTimeI18NBehavior')); // 'ext' is in Yii 1.0.8 version. For early versions, use 'application.extensions' instead.
	}

	public function search() {
		$criteria = new CDbCriteria;

		$criteria->compare('id', $this->id, true);
		$criteria->compare('nome', $this->nome, true);
		$criteria->compare('categoria_id', $this->categoria_id);
		$criteria->compare('usuario_id', $this->usuario_id);
		$criteria->compare('file', $this->file, true);
		$criteria->compare('photos', $this->photos, true);
		$criteria->compare('arquivo', $this->arquivo, true);
		$criteria->compare('name', $this->name, true);
		$criteria->compare('type', $this->type, true);
		$criteria->compare('size', $this->size, true);
		$criteria->compare('url', $this->url, true);
		$criteria->compare('thumbnail_url', $this->thumbnail_url, true);
		$criteria->compare('delete_url', $this->delete_url, true);

		return new CActiveDataProvider($this, array(
			'criteria' => $criteria,
		));
	}
	
	
	//in protected/models/SomeModel.php
public function afterSave( ) {
    $this->addImages( );
    parent::afterSave( );
}
 
public function addImages( ) {
    //If we have pending images
    if( Yii::app( )->user->hasState( 'images' ) ) {
        $userImages = Yii::app( )->user->getState( 'images' );
        //Resolve the final path for our images
        $path = Yii::app( )->getBasePath( )."/../images/uploads/{$this->id}/";
        //Create the folder and give permissions if it doesnt exists
        if( !is_dir( $path ) ) {
            mkdir( $path );
            chmod( $path, 0777 );
        }
 
        //Now lets create the corresponding models and move the files
        foreach( $userImages as $image ) {
            if( is_file( $image["path"] ) ) {
                if( rename( $image["path"], $path.$image["filename"] ) ) {
                    chmod( $path.$image["filename"], 0777 );
                    $img = new Image( );
                    $img->size = $image["size"];
                    $img->mime = $image["mime"];
                    $img->name = $image["name"];
                    $img->source = "/images/uploads/{$this->id}/".$image["filename"];
                    $img->arquivo_id = $this->id;
                    if( !$img->save( ) ) {
                        //Its always good to log something
                        Yii::log( "Could not save Image:\n".CVarDumper::dumpAsString( 
                            $img->getErrors( ) ), CLogger::LEVEL_ERROR );
                        //this exception will rollback the transaction
                        throw new Exception( 'Could not save Image');
                    }
                }
            } else {
                //You can also throw an execption here to rollback the transaction
                Yii::log( $image["path"]." is not a file", CLogger::LEVEL_WARNING );
            }
        }
        //Clear the user's session
        Yii::app( )->user->setState( 'images', null );
    }
}
}

0

#193 User is offline   Asgaroth 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 371
  • Joined: 17-July 09
  • Location:Bogota, Colombia

Posted 20 September 2012 - 11:56 AM

have you tried uploading other files? I mean without using the extension? do you have display_errors and error_reporting in PHP?
- Extension: Dynamic DataProvider Behavior
- Extension: XUpload - jQuery File Upload Extension
- Extension: PhpQuickProfiler - A Web Log Router that will help you profile your application
- Extension: XDateView - A Date grouped Grid View
- Extension: Foundation - An easy to use, powerful, and flexible framework for building prototypes and production code on any kind of device.



- Wiki: How to generate Yii like Documentation
- Wiki: How to re enable logging during unit testing
0

#194 User is offline   Thiago Prado 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 27-August 12

Posted 20 September 2012 - 12:18 PM

View PostAsgaroth, on 20 September 2012 - 11:56 AM, said:

have you tried uploading other files? I mean without using the extension? do you have display_errors and error_reporting in PHP?


Worked when I copied the xupload/model/XUploadForm inside the 'Arquivo' model!!
Is that right?
0

#195 User is offline   Thiago Prado 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 27-August 12

Posted 20 September 2012 - 12:22 PM

View PostThiago Prado, on 20 September 2012 - 12:18 PM, said:

Worked when I copied the xupload/model/XUploadForm inside the 'Arquivo' model!!
Is that right?


False alarme...

Fatal error: Class 'Image' not found in /Users/thiagoprado/Documents/yii/thiago/protected/models/_base/BaseArquivo.php on line 177

if( rename( $image["path"], $path.$image["filename"] ) ) {
                    chmod( $path.$image["filename"], 0777 );
                    $img = new Image( );  //// THE LINE 177 ////
                    $img->size = $image["size"];
                    $img->mime = $image["mime"];
                    $img->name = $image["name"];
                    $img->source = "/images/uploads/{$this->id}/".$image["filename"];
                    $img->arquivo_id = $this->id;
                    if( !$img->save( ) ) {

0

#196 User is offline   Asgaroth 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 371
  • Joined: 17-July 09
  • Location:Bogota, Colombia

Posted 20 September 2012 - 12:22 PM

View PostThiago Prado, on 20 September 2012 - 12:18 PM, said:

Worked when I copied the xupload/model/XUploadForm inside the 'Arquivo' model!!
Is that right?


Depends on what you are doing, and if you are using giix, you shouldn't be modifying the basemodel

/**
 * This is the model base class for the table "Arquivo".
 * DO NOT MODIFY THIS FILE! It is automatically generated by giix.


If it worked with the default XUploadForm, then you have something wrong with your code.
- Extension: Dynamic DataProvider Behavior
- Extension: XUpload - jQuery File Upload Extension
- Extension: PhpQuickProfiler - A Web Log Router that will help you profile your application
- Extension: XDateView - A Date grouped Grid View
- Extension: Foundation - An easy to use, powerful, and flexible framework for building prototypes and production code on any kind of device.



- Wiki: How to generate Yii like Documentation
- Wiki: How to re enable logging during unit testing
0

#197 User is offline   Thiago Prado 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 18
  • Joined: 27-August 12

Posted 21 September 2012 - 05:13 PM

View PostAsgaroth, on 20 September 2012 - 12:22 PM, said:

Depends on what you are doing, and if you are using giix, you shouldn't be modifying the basemodel

/**
 * This is the model base class for the table "Arquivo".
 * DO NOT MODIFY THIS FILE! It is automatically generated by giix.


If it worked with the default XUploadForm, then you have something wrong with your code.



Worked!!!!

Now that I can create how to configure an update?

Model 1 - User
Model 2 - Archive with user_id as parent

Thanks
0

#198 User is offline   Hesam K 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 231
  • Joined: 14-August 11

Posted 27 September 2012 - 08:07 AM

hi!
the extension is great and works well, thank you for your nice work. but I had to expand it to fit my project's needs, so I have some issues now.
first of all, is there any way to have two or more widgets in a form, each sending their requests to their respective action?
I have tried it but there are major conflicts when two widgets are loaded on the screen.

I actually want to have different actions for different scenarios, for example one for files, one for images, and one for gallery, all related to a news article.
so even if it is possible to have one widget on the screen, but somehow change the action it is sending requests in the runtime, my problem is solved! is there anyway?
thank you in advance.

(\ /)
(O.o)
(> <)

This is Bunny. Copy Bunny into your signature to help him on his way to world domination.
0

#199 User is offline   Asgaroth 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 371
  • Joined: 17-July 09
  • Location:Bogota, Colombia

Posted 27 September 2012 - 08:15 AM

View PostHesam Khaki, on 27 September 2012 - 08:07 AM, said:

hi!
the extension is great and works well, thank you for your nice work. but I had to expand it to fit my project's needs, so I have some issues now.
first of all, is there any way to have two or more widgets in a form, each sending their requests to their respective action?
I have tried it but there are major conflicts when two widgets are loaded on the screen.

I actually want to have different actions for different scenarios, for example one for files, one for images, and one for gallery, all related to a news article.
so even if it is possible to have one widget on the screen, but somehow change the action it is sending requests in the runtime, my problem is solved! is there anyway?
thank you in advance.


This should be something related to the javascript I believe, I have never used 2 widgets in the same page so I can't really tell, but you can check this wiki and see if you can workout something, if you do, maybe you can also contribute your code in the git repo
- Extension: Dynamic DataProvider Behavior
- Extension: XUpload - jQuery File Upload Extension
- Extension: PhpQuickProfiler - A Web Log Router that will help you profile your application
- Extension: XDateView - A Date grouped Grid View
- Extension: Foundation - An easy to use, powerful, and flexible framework for building prototypes and production code on any kind of device.



- Wiki: How to generate Yii like Documentation
- Wiki: How to re enable logging during unit testing
0

#200 User is offline   Hesam K 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 231
  • Joined: 14-August 11

Posted 27 September 2012 - 09:02 AM

thanks for your fast response!
I had a look, as you've probably noticed, it has duplicated the whole form, and then used the same class for those two. in my case, the widgets are embedded in one form, beside other model attributes, and it doesn't feel good to have multiple forms in one view for one model! :-? and even if I do so, I'll had to edit your code in XUpload.php, where you have registered the starter JS for this plugin.

what about the second way? is there any DOM attribute anywhere holding the destination action, so wen can change it in client side? like by checking a checkbox, that attribute would change from 'uploadImage' to 'uploadFile' ?

alternatively, I'll try to solve this problem using bootstrap tabs, having different form in each tab, and hoping that no conflicts would happen :)

(\ /)
(O.o)
(> <)

This is Bunny. Copy Bunny into your signature to help him on his way to world domination.
0

Share this topic:


  • (20 Pages)
  • +
  • « First
  • 8
  • 9
  • 10
  • 11
  • 12
  • Last »
  • You cannot start a new topic
  • You cannot reply to this topic

2 User(s) are reading this topic
0 members, 2 guests, 0 anonymous users