Tuesday, 26 May 2015

Create a link in UBUNTU to a app or module or extension -- how to install fpdf in ubuntu

1. Please login as "root" or admin privilege as root equivalent in terminal and give the following command
    # sudo apt-get install php-fpdf
2. Internet connection should be there, after successful installation there will be a file in the following location
   # ls -l /usr/share/php/fpdf
3. Please create a symbolic link and direct the link to make available on your webserver ( the default location of apache web server is " /var/www/ " ) using the following command
    # ln -s /usr/share/php/fpdf  /var/www/fpdf
4. Reload your webserver
  #/etc/init.d/apache2 restart
  (or)
   #/etc/init.d/apache2 force-reload
   (or)
   #service apache2 restart
5. Make sure PHP commands on web page associated with the conversion to PDF function like this
   <?php
          require('fpdf/fpdf.php');
    ?>
6. Finish.

For further reference ,
https://kokikode.wordpress.com/2010/03/28/how-to-install-php-fpdf-in-ubuntu/

  

Friday, 1 May 2015

Multiple Multi File Upload Handling in YII

Before proceeding create folder names 'uploads' in the application directory that is the folder protected and uploads should be at same location. And give all permissions to the folder in case of linux machine.

First To Handle Multiple files upload there should be a dynamic table entries for each record.

Say, We are handling a File Tracking System. In this case each entry or File may consists of 'N' number of papers or sometimes images, The File moved to concerned then to next concerned and so on finally it closes.

For each movement a new response file is appended to the existing E-File. In this case we need a multi file upload, That is for each file number there are many E-Files associated and each e-file should be stored.

Now Coming to Implementation, Lets have a parent table name 'FTS' in which fileno is the primary key. The child table name 'uploads' in which id is the primary key and a field 'fileno' is a foreign key referencing the Parent table 'FTS' primary key i.e., `FTS`.`fileno`.

Now, The parent table `FTS` have a feild name image or upload any of it as you like. This is just a check field whether the fileno having a attachment or not? so we can say `image varchar(20)` is a field name in FTS.

coming to implementation,

MODEL:
There is nothing to do with the MODEL here, Just we should have the parent and child models thats it.

VIEW:
lets suppose our view name is `createform.php` and we are using the upload functionality while creating a entry in `FTS`

simply add the below widget to the view (createform.php)

 <?php
echo "<font color='red'><b>Scan and upload the E-Files</b></font> <br/>";
echo " (max 3 files can be uploaded)<br/>";

$this->widget('CMultiFileUpload', array(
                'name' => 'images',   // name to the control
                        'max'=>'3',    // Max number of uploads fixed to 3
                'accept' => 'jpeg|jpg|gif|png|pdf', // useful for verifying files
                'duplicate' => 'Duplicate file!', // useful, i think
                'denied' => 'Invalid file type', // useful, i think
/*'options'=>array(
       'onFileSelect'=>'function(e, v, m){ alert("onFileSelect - "+v) }',
         'afterFileSelect'=>'function(e, v, m){ alert("afterFileSelect - "+v) }',
         'onFileAppend'=>'function(e, v, m){ alert("onFileAppend - "+v) }',
         'afterFileAppend'=>'function(e, v, m){ alert("afterFileAppend - "+v) }',
         'onFileRemove'=>'function(e, v, m){ alert("onFileRemove - "+v) }',
 'afterFileRemove'=>'function(e, v, m){ alert("afterFileRemove - "+v) }',
    ), */ // handle to javascript to the events if necessary
));  echo "jpeg/jpg/gif/png/pdf accepted";
?>

and Don't forget (I always forget) to define the HTML Options to the form  in the view, i.e., at the beginning of our view we declare a html <form> equivalent in php language, add the below bold text
line to the form.

<?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'fts-form',
        'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'), // ADD THIS
)); ?>

 or this way, before your use of CMultiFileUpload
<?php echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>
That's it!!! View Part is completed. The user can upload the files here I restricted to 3 files, but we have to handle the upload files so, we need to do some coding in controller.

CONTROLLER:

As said earlier, we have taken example while creation of entry in FTS we need to handle the uploaded files in create action of controller.

public function actionCreate()
{
$model=new Fts;

// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);

$baseUrl = Yii::app()->baseUrl;
$cs = Yii::app()->getClientScript();

$cs->registerScriptFile($baseUrl.'/js/utility.js');         // Java Script files registration
$cs->registerScriptFile($baseUrl.'/js/validations.js');


if(isset($_POST['Fts']))
{
$model->attributes=$_POST['Fts'];
if($model->validate()){
                    $model->insertFields();      //calling a model function from controller

///////////////////////////////**** UPLOAD FILES HANDLING BEGINNING *****////////////////////////////

$images = CUploadedFile::getInstancesByName('images');
                                               // The control name given is images
            // proceed if the images have been set
$uname=Yii::app()->user->name;   // Getting login username
$username='';
if(strpos($uname,'.')!==false)
$username=substr($str,0,strrpos($str,'.'));
                      /* gets the part before search character i.e., dot(.)  if username is xxx.fts we need only the name xxx so getting that part */
else
$username=$uname;

                        $tosection='';
if(strpos($model->section,'-')!==false)
$tosection=trim(substr($model->section,0,strrpos($model->section,'-')));
                        // gets the part before search character i.e., Hyphen (-)
else
$tosection=$model->section;

$tosection = preg_replace('/\s+/', '', $tosection);  // removing spaces in the string

$fno= $model->fileno;
            if (isset($images) && count($images) > 0) {   // if upload images exists
            $fileno=1;
               foreach ($images as $image => $pic) {
              /* $dt=date("d-m-y H:i:s");
$strdt = preg_replace('/[^0-9]/','',$dt);     // to generate unique filename
$strdt = uniqid();
$strdt = rand(1, 999999);
$strdt = sha1(md5(time()));
$strdt =                       substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyz"), 0, 6); */

$url=$pic->name;
$onlyname=trim(substr($url,0,strrpos($url,'.')));  // gets only name of file excluding extension
$strdt= preg_replace('/[^0-9a-zA-Z]/','',$onlyname);  // taking only characters and numbers from filename
               $filetype = substr($url, strrpos($url, '.') + 1);  // gets the extension of uploaded file i.e., last part after search character

if(!empty($url)){

                    $app_path = Yii::app()->basePath.'/../uploads/';
                    $filename=$fno.'_'.$fileno.'_'.$username.'_to_'.$tosection.'_'.$strdt.'.'.$filetype;
                    if ($pic->saveAs($app_path.$filename)) {
                        $img_add = new Uploads();    // child table object
    $img_add->fileno = $fno;
                        $img_add->image = $filename;
                $img_add->file_year = $model->file_year;
                    $img_add->section = $model->section;
                   // Dialog::message('INFO', "$img_add->section");
 $img_add->save(); // DONE
                    }
                    $fileno= $fileno + 1;
                    }
                 }
$model->image='YES';     // i.e., the model having uploads
}else{
$model->image='NIL';
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if($model->save())
$this->redirect(array('view','id'=>$model->id));
else
Dialog::message('ERROR', "unable to save ");
}else
Dialog::message('ERROR', "unable to save please enter required(red) color fields");
}

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

The images are saved successfully to the database. The same can be applied to Update action.

check how to display a single upload file in CGRID View : http://hemamca.blogspot.in/2015/02/display-urls-of-image-in-cgridview-of.html

********************* DISPLAYING THE FILES IN VIEW ************************

Now , In view we can display the Uploads as hyper links by the below way:

VIEW.PHP : Our view file,

<div>
<center>
<?php
//if(($model->image!='NIL')and($model->image!=null)){
   $fileno=$model->fileno;
   $imgcnt=Uploads::model()->count("fileno='$fileno'");
   if($imgcnt > 1){
              $app_url=Yii::app()->baseUrl.'/uploads/';
              $imgs=Uploads::model()->findAll("fileno='$fileno'");
              echo "<br/>";
              echo "<table id='withborder' border=1 cellspacing=0 cellpadding=0 bgcolor=\"#45E1D5\">";
              echo "<tr> <td  bgcolor=\"#1D5C57\" colspan=4'><font color=\"white\"><b><center>
              The E-Files details for this Inward Entry </center></b></font></td></tr>";
              echo "<tr>";
              echo "<td bgcolor=\"#1D5C57\"><font color=\"white\"><b><center>S.No</center></b></font></td>";
              echo "<td bgcolor=\"#1D5C57\"><font color=\"white\"><b><center>File No</center></b></font></td>";
              echo "<td bgcolor=\"#1D5C57\"><font color=\"white\"><b><center>File Year</center></b></font></td>";
              echo "<td bgcolor=\"#1D5C57\"><font color=\"white\"><b><center>Filename</center></b></font></td>";
              echo "</tr>";
              $fno=1;
              foreach($imgs as $img){
                       $inwno=$img->fileno;
                       $inwyr=$img->file_year;
                       $fname=$img->image;
                       $filepath=$app_url.$fname;
                       echo "<tr>";
                       echo "<td><font color=\"black\"><center>$fileno</center></font></td>";
                       echo "<td><font color=\"black\"><center>$inwno</center></font></td>";
                       echo "<td><font color=\"black\"><center>$inwyr</center></font></td>";
                       echo "<td><font color=\"black\"><b><a href='$filepath' target='_blank'>$fname </a></b></font></td>";
                echo "</tr>";
                $fno=$fno+1;
              }
              echo "</table>";
echo "<br/>";
}
//}
?>
  </center>
</div>

NOTE: 
Database used is Mysql, Development Language is PHP, framework is PHP.

cross reference site:
http://www.yiiframework.com/wiki/176/uploading-multiple-images-with-cmultifileupload/

UPLOAD a File in yii

THE MODEL

First declare an attribute to store the file name in the model class (either a form model or an active record model). Also declare a file validation rule for this attribute to ensure a file is uploaded with specific extension name.
class Item extends CActiveRecord
{
    public $image;
    // ... other attributes
 
    public function rules()
    {
        return array(
            array('image', 'file', 'types'=>'jpg, gif, png'),
        );
    }
}
You can add others validation parameters as described in CFileValidator. For instance, one can add a “maxSize” restriction (the PHP ini settings will of course prevail).

THE CONTROLLER

Then, in the controller class define an action method to render the form and collect user-submitted data.
class ItemController extends CController
{
    public function actionCreate()
    {
        $model=new Item;
        if(isset($_POST['Item']))
        {
            $model->attributes=$_POST['Item'];
            $model->image=CUploadedFile::getInstance($model,'image');
            if($model->save())
            {
                $model->image->saveAs('path/to/localFile');
                // redirect to success page
            }
        }
        $this->render('create', array('model'=>$model));
    }
}
CUploadedFile::saveAs() in one of the methods of CUploadedFile. You can also access directly to the file through its “tempName” property.

THE VIEW

Finally, create the action view and generate a file upload field.
$form = $this->beginWidget(
    'CActiveForm',
    array(
        'id' => 'upload-form',
        'enableAjaxValidation' => false,
        'htmlOptions' => array('enctype' => 'multipart/form-data'),
    )
);
// ...
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
// ...
echo CHtml::submitButton('Submit');
$this->endWidget();
Another syntax is to use static calls in CHtml instead of CActiveForm. The result is the same as above.
<?php echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>
...
<?php echo CHtml::activeFileField($model, 'image'); ?>
...
<?php echo CHtml::submitButton('Submit'); ?>
<?php echo CHtml::endForm(); ?>