Problem With Importing Csv File


(Anthony Gough) #1

RE:Importing CSV file to mysql table using "LOAD DATA" command. I cannot post links into this post as this is my first post - link is in file attached

I am having trouble implementing this. I created a file UserImportForm.php file with the form model code in the models directory. The code for the form I placed into importcsv.php into views\site. Finally I placed the function actionImportCSV into the SiteController. When I try to use the importcsv function index.php?r=user/importcsv

I get an error Alias "bootstrap.widgets.BootActiveForm" is invalid. Make sure it points to an existing directory or file.

I am fairly new to YII so I am sure I have done something wrong. I have followed suggestions such as autoloading extensions in the config\main.php file however I cannot get this to work. I have a requirement to load a csv file into a MySQL table and I could do this with a php script however I was trying to stick to YII conventions.

Any help appreciated


(Traprajith) #2

post your controller codes…

and if view rendering in user/importcsv, then that code too…


(Anthony Gough) #3

Codes are as per below

UserImportForm.php - In Models directory

<?php

class UserImportForm extends CFormModel

{

public &#036;file;


/**


 * @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('file', 'file', 


                                        'types'=&gt;'csv',


                                        'maxSize'=&gt;1024 * 1024 * 10, // 10MB


                                        'tooLarge'=&gt;'The file was larger than 10MB. Please upload a smaller file.',


                                        'allowEmpty' =&gt; false


                          ),


               );


}





/**


 * @return array customized attribute labels (name=&gt;label)


 */


public function attributeLabels()


{


    return array(


        'file' =&gt; 'Select file',


    );


}

}

?>

UserController.php

<?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 &#036;layout='//layouts/column2';





/**


 * @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


	);


}





/**


 * 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'=&gt;array('index','view', 'importcsv'),


			'users'=&gt;array('*'),


		),


		array('allow', // allow authenticated user to perform 'create' and 'update' actions


			'actions'=&gt;array('create','update'),


			'users'=&gt;array('@'),


		),


		array('allow', // allow admin user to perform 'admin' and 'delete' actions


			'actions'=&gt;array('admin','delete'),


			'users'=&gt;array('admin'),


		),


		array('deny',  // deny all users


			'users'=&gt;array('*'),


		),


	);


}

public function actionImportCSV()

    {


       &#036;model=new UserImportForm;





       if(isset(&#036;_POST['UserImportForm']))


         {





           &#036;model-&gt;attributes=&#036;_POST['UserImportForm'];





           if(&#036;model-&gt;validate())


             {





              &#036;csvFile=CUploadedFile::getInstance(&#036;model,'file');  


              &#036;tempLoc=&#036;csvFile-&gt;getTempName();





                &#036;sql=&quot;LOAD DATA LOCAL INFILE '&quot;.&#036;tempLoc.&quot;'


				INTO TABLE `tbl_user`


				FIELDS TERMINATED BY ','


				ENCLOSED BY '&#092;&quot;' LINES TERMINATED BY '&#092;n'


				IGNORE 1 LINES


				(`name`, `age`, `location`)&quot;;





                &#036;connection=Yii::app()-&gt;db;


                &#036;transaction=&#036;connection-&gt;beginTransaction();


                    try


                        {





                            &#036;connection-&gt;createCommand(&#036;sql)-&gt;execute();


                            &#036;transaction-&gt;commit();


                        }


                        catch(Exception &#036;e) // an exception is raised if a query fails


                         {


                            print_r(&#036;e);


                            exit;


                            &#036;transaction-&gt;rollBack();





                         }


                  &#036;this-&gt;redirect(array(&quot;user/index&quot;));


             }


         }  





       &#036;this-&gt;render(&quot;importcsv&quot;,array('model'=&gt;&#036;model));


    }


 


/**


 * Displays a particular model.


 * @param integer &#036;id the ID of the model to be displayed


 */


public function actionView(&#036;id)


{


	&#036;this-&gt;render('view',array(


		'model'=&gt;&#036;this-&gt;loadModel(&#036;id),


	));


}





/**


 * Creates a new model.


 * If creation is successful, the browser will be redirected to the 'view' page.


 */


public function actionCreate()


{


	&#036;model=new User;





	// Uncomment the following line if AJAX validation is needed


	// &#036;this-&gt;performAjaxValidation(&#036;model);





	if(isset(&#036;_POST['User']))


	{


		&#036;model-&gt;attributes=&#036;_POST['User'];


		if(&#036;model-&gt;save())


			&#036;this-&gt;redirect(array('view','id'=&gt;&#036;model-&gt;id));


	}





	&#036;this-&gt;render('create',array(


		'model'=&gt;&#036;model,


	));


}





/**


 * Updates a particular model.


 * If update is successful, the browser will be redirected to the 'view' page.


 * @param integer &#036;id the ID of the model to be updated


 */


public function actionUpdate(&#036;id)


{


	&#036;model=&#036;this-&gt;loadModel(&#036;id);





	// Uncomment the following line if AJAX validation is needed


	// &#036;this-&gt;performAjaxValidation(&#036;model);





	if(isset(&#036;_POST['User']))


	{


		&#036;model-&gt;attributes=&#036;_POST['User'];


		if(&#036;model-&gt;save())


			&#036;this-&gt;redirect(array('view','id'=&gt;&#036;model-&gt;id));


	}





	&#036;this-&gt;render('update',array(


		'model'=&gt;&#036;model,


	));


}





/**


 * Deletes a particular model.


 * If deletion is successful, the browser will be redirected to the 'admin' page.


 * @param integer &#036;id the ID of the model to be deleted


 */


public function actionDelete(&#036;id)


{


	&#036;this-&gt;loadModel(&#036;id)-&gt;delete();





	// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser


	if(&#33;isset(&#036;_GET['ajax']))


		&#036;this-&gt;redirect(isset(&#036;_POST['returnUrl']) ? &#036;_POST['returnUrl'] : array('admin'));


}





/**


 * Lists all models.


 */


public function actionIndex()


{


	&#036;dataProvider=new CActiveDataProvider('User');


	&#036;this-&gt;render('index',array(


		'dataProvider'=&gt;&#036;dataProvider,


	));


}





/**


 * Manages all models.


 */


public function actionAdmin()


{


	&#036;model=new User('search');


	&#036;model-&gt;unsetAttributes();  // clear any default values


	if(isset(&#036;_GET['User']))


		&#036;model-&gt;attributes=&#036;_GET['User'];





	&#036;this-&gt;render('admin',array(


		'model'=&gt;&#036;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 the ID of the model to be loaded


 */


public function loadModel(&#036;id)


{


	&#036;model=User::model()-&gt;findByPk(&#036;id);


	if(&#036;model===null)


		throw new CHttpException(404,'The requested page does not exist.');


	return &#036;model;


}





/**


 * Performs the AJAX validation.


 * @param CModel the model to be validated


 */


protected function performAjaxValidation(&#036;model)


{


	if(isset(&#036;_POST['ajax']) &amp;&amp; &#036;_POST['ajax']==='user-form')


	{


		echo CActiveForm::validate(&#036;model);


		Yii::app()-&gt;end();


	}


}

}

importcsv.php in views\user

<div class="form">

<?php

$form = $this->beginWidget(‘bootstrap.widgets.BootActiveForm’, array(

'id'=&gt;'service-form',


'enableAjaxValidation'=&gt;false,


'method'=&gt;'post',


'type'=&gt;'horizontal',


'htmlOptions'=&gt;array(


    'enctype'=&gt;'multipart/form-data'


)

)); ?>

&lt;fieldset&gt;


    &lt;legend&gt;


        &lt;p class=&quot;note&quot;&gt;Fields with &lt;span class=&quot;required&quot;&gt;*&lt;/span&gt; are required.&lt;/p&gt;


    &lt;/legend&gt;





    &lt;?php echo &#036;form-&gt;errorSummary(&#036;model, 'Opps&#33;&#33;&#33;', null, array('class'=&gt;'alert alert-error span12')); ?&gt;





    &lt;div class=&quot;control-group&quot;&gt;     


        &lt;div class=&quot;span4&quot;&gt;


                            &lt;div class=&quot;control-group &lt;?php if (&#036;model-&gt;hasErrors('postcode')) echo &quot;error&quot;; ?&gt;&quot;&gt;


    &lt;?php echo &#036;form-&gt;labelEx(&#036;model,'file'); ?&gt;


    &lt;?php echo &#036;form-&gt;fileField(&#036;model,'file'); ?&gt;


    &lt;?php echo &#036;form-&gt;error(&#036;model,'file'); ?&gt;


                        &lt;/div&gt;








        &lt;/div&gt;


    &lt;/div&gt;





    &lt;div class=&quot;form-actions&quot;&gt;


        &lt;?php &#036;this-&gt;widget('bootstrap.widgets.BootButton', array('buttonType'=&gt;'submit', 'type'=&gt;'primary', 'icon'=&gt;'ok white', 'label'=&gt;'UPLOAD')); ?&gt;


        &lt;?php &#036;this-&gt;widget('bootstrap.widgets.BootButton', array('buttonType'=&gt;'reset', 'icon'=&gt;'remove', 'label'=&gt;'Reset')); ?&gt;


    &lt;/div&gt;





&lt;/fieldset&gt;

<?php $this->endWidget(); ?>

</div><!-- form -->


(Traprajith) #4

the problem is with the path

‘bootstrap.widgets.BootButton’,‘bootstrap.widgets.BootActiveForm’,


(Anthony Gough) #5

I get what you mean now - path does not exist. Thanks


(Jordan Sipahutar) #6

so how you fix it?