We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 13428 ☆ A M B ☆
    • 1,031 Posts
    mod_security could cause those issues.
      • 11121
      • 79 Posts
      Hi, I use two snippets (resource2formit and formit2resource) to give user the ability to create and edit resources.

      The Formit call to create resource is this:

      [[!FormIt? 
          &preHooks=`resource2formit, Formit2AjaxUpload`
          &hooks=`AjaxUpload2Formit, formit2resource, redirect` 
          &resource2formitfields=`template,resource_id,parent,Paratiriseis,Name,Sex,Race,Age,Weight,Pedigree,Microchip,Passport,Area,Phone,Email,pagetitle,photo`
          &redirectTo=`106`
          &ajaxuploadUid=`image`
          &ajaxuploadFieldname=`photo`
          &ajaxuploadTarget=`images/uploads/`
          &validate=`
           pagetitle:required,
           Sex:required,
           Race:required,
           Age:required,
           Phone:required,
           Email:required,
           Pedigree:required,
           Area:required`
          &vTextRequired=`*Απαραίτητο πεδίο`
          &submitVar=`dog_input`
      ]]


      The Formit call to EDIT resource is this:

      [[!FormIt? 
          &preHooks=`resource2formit,Formit2AjaxUpload`
          &hooks=`AjaxUpload2Formit,formit2resource,redirect` 
          &resource2formitfields=`template,resource_id,Active,pagetitle,Paratiriseis,Sex,Race,Age,Weight,Pedigree,Microchip,Passport,Area,Phone,Email,content,photo`
          &resId=`[[~[[*id]]]]`
          &redirectTo=`106`
          &ajaxuploadUid=`image`
          &ajaxuploadFieldname=`photo`
          &ajaxuploadTarget=`images/uploads/`
          &validate=`
           pagetitle:required,
           Sex:required,
           Race:required,
           Age:required,
           Phone:required,
           Email:required,
           Pedigree:required,
           Area:required`
          &vTextRequired=`*Απαραίτητο πεδίο`
          &submitVar=`dog_input`
      ]]


      AjaxUpload works when I create the resource. Files are getting uploaded to specific path, and a tv field with given name at formit call is filled with files paths, comma seperated.

      The problem is when I EDIT the resource, the AjaxUpload queue shows empty. Any suggestion?

      Formit2Resource
      <?php
      $doc = $modx->getObject('modResource',array('id'=>$hook->getValue('resource_id')));
        
      if (empty($doc)){
          $doc = $modx->newObject('modResource');
          $doc->set('createdby', $modx->user->get('id'));
      }
      else{
          $doc->set('editedby', $modx->user->get('id'));
      }
        
      $allFormFields = $hook->getValues(); 
      foreach ($allFormFields as $field=>$value)
      {
        
         if ($field !== 'spam' && $field !== 'resource_id'){
               $doc->set($field, $value);
          }
       
         //we need to parse the title into the alias
         if($field == 'pagetitle'){
            //replace spaces with -
            $alias = preg_replace('/[\' \']/' , '-' , $value);
       
            //remove non alpha and a common injection string 
            $alias = preg_replace('/[^a-z0-9\.\x0B\-]/i' , '' , $alias);
       
                                         //this is the standard revo regexp
                                         // \0\x0B\t\n\r\f\a&=+%#<>"~:`@\?\[\]\{\}\|\^'\
         }
      }
       // now set the alias
       $doc->set('alias', $alias);
        
      $doc->set('template', $template);
      $isnew = $doc->isNew();
       
      if ($doc->save()) {
          if ($isnew) {
              $doc->set('alias', $doc->get('alias' . '-' . $doc->get('id')));
              $doc->save();
          }
      }
      
      foreach ($allFormFields as $field=>$value)
      {
          if ($tv = $modx->getObject('modTemplateVar', array ('name'=>$field)))
          {
              /* handles checkboxes & multiple selects elements */
              if (is_array($value)) {
                  $featureInsert = array();
                  while (list($featureValue, $featureItem) = each($value)) {
                      $featureInsert[count($featureInsert)] = $featureItem;
                  }
                  $value = implode('||',$featureInsert);
              }   
              $tv->setValue($doc->get('id'), $value);
              $tv->save();
          }
      }
      
      $url = $modx->makeUrl(84);
      
      ////////////formit2file part ////////////////////////////////////
      
      // initialize output;
      $output = true;
      // valid extensions
      $ext_array = array('jpg', 'jpeg', 'gif', 'png');
        
      // create unique path for this form submission
      //$uploadpath = 'assets/img-annonceurs/';
        
      // you can create some logic to automatically
      // generate some type of folder structure here.
      // the path that you specify will automatically
      // be created by the script if it doesn't already
      // exist.
        
      // EXAMPLE:
      // this would put all file uploads into a new,
      // unique folder every day.
      $uploadpath = 'assets/images/users/'.date('Y-m-d').'/';
        
      // get full path to unique folder
      $target_path = $modx->config['base_path'] . $uploadpath;
        
      // get uploaded file names:
      $submittedfiles = array_keys($_FILES);
        
      // loop through files
      foreach ($submittedfiles as $sf) {
      
          // Get Filename and make sure its good.
          $filename = basename( $_FILES[$sf]['name'] );
        
          // Get file's extension
          $ext = pathinfo($filename, PATHINFO_EXTENSION);
          $ext = mb_strtolower($ext); // case insensitive
        
          // is the file name empty (no file uploaded)
          if($filename != '') {
                
              // is this the right type of file?
              if(in_array($ext, $ext_array)) {
            
                  // change name to: resource_id-input_name.ext
                  $filename = $doc->get('id').'-'.$sf.'.'.$ext;
      
      
                  // full path to new file
                  $myTarget = $target_path . $filename;
      			//URL path
      			$urlPath = $uploadpath . $filename;
                    
                  // create directory to move file into if it doesn't exist
                  if(!is_dir($target_path)) {
                      mkdir($target_path, 0755, true);
                      } else {
                      $modx->log(modX::LOG_LEVEL_ERROR, 'Upload:Path already exists' );    
                      }
      
                  // is the file moved to the proper folder successfully?
                  if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
                    // place file path to tv
                   if (!$doc->setTVValue($sf, $urlPath)) $modx->log(xPDO::LOG_LEVEL_ERROR, 'Upload:Saving TV error');
      
                      // set the permissions on the file
                      if (!chmod($myTarget, 0644)) { /*some debug function*/ }
      
                  } else {
                      // File not uploaded
                      $errorMsg = 'There was a problem uploading the file.';
                      $hook->addError($sf, $errorMsg);
                      $output = false; // generate submission error
                  }
                
              } else {
                  // File type not allowed
                  $errorMsg = 'Type of file not allowed.';
                  $hook->addError($sf, $errorMsg);
                  $output = false; // generate submission error
              }
              
      // if no file, don't error, but return blank
        } else {
            $hook->setValue($sf, '');
        }
       
       
      }
      
      $modx->cacheManager->refresh(); // suggested by gallenkamp
      return $output;



      Resource2formit
      <?php
      if (isset($_GET['resId'])){
          if ($doc=$modx->getObject('modResource',array('id'=>$_GET['resId']))){
              $docarray=$doc->toArray();
              $fields = explode(',',$scriptProperties['resource2formitfields']);
              $fields[] = 'id';
         
              foreach ($fields as $field){
                
                  if ($doc->getFieldName($field) === null) {
                      /* if field isnt defined, look for TV value */
                      $tvValue = $doc->getTVValue($field);
                      if ($tvValue !== null) {
                          $hook->setValue($field,$tvValue);
                      }
                  } else {
                      /* otherwise get field value */
                      $hook->setValue($field,$docarray[$field]);
                  }    
              }
          }
         
          //$errorMsg = '<pre>'.print_r($docarray,true).'</pre>';  
          //$hook->addError('error_message',$errorMsg);  
      }
         
         
      return true;
        • 11121
        • 79 Posts
        Some questions.

        Uid by default it creates a unique queue id in last version of Ajaxupload?
        Where I can see in the database the uid of the uploaded field and how can I retrieve it so I can edit it?
        [ed. note: gordonas last edited this post 10 years, 10 months ago.]
          • 4172
          • 5,888 Posts
          you can try to get the resid, with getReqParam or fastField
            -------------------------------

            you can buy me a beer, if you like MIGX

            http://webcmsolutions.de/migx.html

            Thanks!
            • 11121
            • 79 Posts
            Quote from: Bruno17 at Dec 19, 2015, 04:15 AM
            you can try to get the resid, with getReqParam or fastField

            OK, found it with another way. Thank you for the tip.

            Something last. Do you know where in database Ajaxupload saves the field from ajaxuploadFieldname?

            Ajaxupload creates the name of the field I give or it should be created before by me? [ed. note: gordonas last edited this post 10 years, 10 months ago.]
              • 11121
              • 79 Posts
              Quote from: Jako at Apr 04, 2014, 05:45 AM
              You could generate the AjaxUpload uid on page base i.e. &uid=`image_[[*id]]`. With that the upload queues are separated in the session.


              But [[*id]] is not unique. The page with the form has always the same id.

              Ajaxupload runs before formit2db so it is not possible to retrieve the id of the resource the user is creating.

              I am really stuck.

              From a specific form page (formit with ajaxupload), users have the ability to save resources. How is it possible to give a unique number to every uid?
                • 13428 ☆ A M B ☆
                • 1,031 Posts
                I think you are mixing the use of the fieldname and the uuid. The uuid contains an unique id to separate different upload queues in the user session. The fieldname contains a comma separated list of filenames of the uploaded files. If you don't have multiple forms that are using ajaxupload on one or on different resources, you don't need to change the uuid. Each user has it's own session, they don't get mixed up. Or does a user need to edit multiple resources at the same time in different tabs?

                The AjaxUpload hooks handle all file based actions from upload until moving to the (maybe temporary) target. If you want to use user-based or resource-based filenames, you should handle that in Formit2Resource by moving the files there from ajaxuploadTarget to your targetFolder and vice versa.
                  • 11121
                  • 79 Posts
                  Quote from: Jako at Dec 21, 2015, 07:58 AM
                  I think you are mixing the use of the fieldname and the uuid. The uuid contains an unique id to separate different upload queues in the user session. The fieldname contains a comma separated list of filenames of the uploaded files. If you don't have multiple forms that are using ajaxupload on one or on different resources, you don't need to change the uuid. Each user has it's own session, they don't get mixed up. Or does a user need to edit multiple resources at the same time in different tabs?

                  The AjaxUpload hooks handle all file based actions from upload until moving to the (maybe temporary) target. If you want to use user-based or resource-based filenames, you should handle that in Formit2Resource by moving the files there from ajaxuploadTarget to your targetFolder and vice versa.


                  I will try to explain my project.

                  There is one page with a form (formit) only for users. With that form the user creates a resource (small ad). I use Ajaxupload to upload and manage the photos of the small ad. The upload part works.

                  My problem is when the users is trying to edit the resource and manage the photos. That could propably happen in another session of the user. The problem I have is with the photos part. I want the user to have the ability to remove, add, replace photos from the resource. And offcourse there are many users.

                  Is that possible with Ajaxupload or I can edit the uploaded files only till they are moved to the target?


                  P.S. Sorry for my english. [ed. note: gordonas last edited this post 10 years, 9 months ago.]
                    • 13428 ☆ A M B ☆
                    • 1,031 Posts
                    If the user edits a resource with a form on the resource itself, the &ajaxuploadUid could be set to i.e. `image[[*id]]`. If you edit all ads on one resource with a form, you have to set it to i.e.`image[[+identifier]]` (identifier could contain the same value that is used to identify the edited ad).

                    Maybe one thing is missing a bit in the documentation: You have to set the uid in the AjaxUpload call and in the FormIt call

                    [[!AjaxUpload?
                    &uid=`image[[+identifier]]`
                    …
                    ]]

                    to display the form field with the right upload queue and
                    [[!FormIt?
                    &preHooks=`Formit2AjaxUpload`
                    &hooks=`AjaxUpload2Formit`
                    &ajaxuploadUid=`image[[+identifier]]`
                    ...
                    ]]

                    to work the form fields in FormIt with the right upload queue.
                      • 13428 ☆ A M B ☆
                      • 1,031 Posts
                      Quote from: gordonas at Jan 05, 2016, 10:17 AM
                      Is that possible with AjaxUpload or I can edit the uploaded files only till they are moved to the target?

                      AjaxUpload moves the files in the queue from the targetFolder to a temporary folder and backwards, but they have to be present in the targetFolder when the queue is filled with the existing images.