We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 16430
    • 217 Posts
    Problem is that it doesnt show in wayfinder until I clear cache.
      • 3749
      • 24,544 Posts
      Did you try reloadContext()?

      If you create the resource with the resource/create processor, MODX will clear the resource cache for you -- something like this:

      $fields = array (
          'pagetitle' => 'SomeTitle',
          'alias' => 'some-title',
          /* etc. */
      );
      
      $response = $this->modx->runProcessor('resource/create', $fields);
      
      /* @var $response modProcessorResponse */
      if ($response->isError()) {
           if ($response->hasFieldErrors()) {
                $fieldErrors = $response->getAllErrors();
                $errorMessage = implode("\n", $fieldErrors);
          } else {
               $errorMessage = 'An error occurred: ' . $response->getMessage();
          }
      }
        Did I help you? Buy me a beer
        Get my Book: MODX:The Official Guide
        MODX info for everyone: http://bobsguides.com/modx.html
        My MODX Extras
        Bob's Guides is now hosted at A2 MODX Hosting
        • 16430
        • 217 Posts
        So if I have this code:
        $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(); 
        ....
        ....
        $doc->set('alias', $alias);
        $doc->set('template', '1'); //id šablony
        $doc->save();
        

        Can I simply change it to use your resource/create processor?
          • 3749
          • 24,544 Posts
          Yes, but you'd have to add the createdby, editedby, alias, and template fields to the $allFormFields array and then pass $allFormFields to the processor as the second argument.
            Did I help you? Buy me a beer
            Get my Book: MODX:The Official Guide
            MODX info for everyone: http://bobsguides.com/modx.html
            My MODX Extras
            Bob's Guides is now hosted at A2 MODX Hosting
            • 16430
            • 217 Posts
            Problem is, that I am using $doc value in the rest of the code for ->set, ->get, ->settvvalue, etc (as you can see in complete code below). which would have to be rewritten as well. I could try reloadContext() but cannot find any info about it in rtfm....

            <?php
            $noaccents = array (
            '&'=>'and','%'=>'','\''=>'','.'=>'',
            'À'=>'A','Á'=>'A','Â'=>'A','Ã'=>'A','Ä'=>'A','Å'=>'A','Æ'=>'E','Ā'=>'A','Ą'=>'A','Ă'=>'A',
            'Ç'=>'C','Ć'=>'C','Č'=>'C','Ĉ'=>'C','Ċ'=>'C',
            'Ď'=>'D','Đ'=>'D',
            'È'=>'E','É'=>'E','Ê'=>'E','Ë'=>'E','Ē'=>'E','Ę'=>'E','Ě'=>'E','Ĕ'=>'E','Ė'=>'E',
            'Ĝ'=>'G','Ğ'=>'G','Ġ'=>'G','Ģ'=>'G',
            'Ĥ'=>'H','Ħ'=>'H',
            'Ì'=>'I','Í'=>'I','Î'=>'I','Ï'=>'I','Ī'=>'I','Ĩ'=>'I','Ĭ'=>'I','Į'=>'I','İ'=>'I',
            'IJ'=>'J','Ĵ'=>'J',
            'Ķ'=>'K',
            'Ľ'=>'L','Ĺ'=>'L','Ļ'=>'L','Ŀ'=>'L',
            'Ñ'=>'N','Ń'=>'N','Ň'=>'N','Ņ'=>'N','Ŋ'=>'N',
            'Ò'=>'O','Ó'=>'O','Ô'=>'O','Õ'=>'O','Ö'=>'O','Ø'=>'O','Ō'=>'O','Ő'=>'O','Ŏ'=>'O',
            'Œ'=>'E',
            'Ŕ'=>'R','Ř'=>'R','Ŗ'=>'R',
            'Ś'=>'S','Ş'=>'S','Ŝ'=>'S','Ș'=>'S',
            'Ť'=>'T','Ţ'=>'T','Ŧ'=>'T','Ț'=>'T',
            'Ù'=>'U','Ú'=>'U','Û'=>'U','Ü'=>'U','Ū'=>'U','Ů'=>'U','Ű'=>'U','Ŭ'=>'U','Ũ'=>'U','Ų'=>'U',
            'Ŵ'=>'W',
            'Ŷ'=>'Y','Ÿ'=>'Y',
            'Ź'=>'Z','Ż'=>'Z',
            'à'=>'a','á'=>'a','â'=>'a','ã'=>'a','ä'=>'a','å'=>'a','æ'=>'e','ā'=>'a','ą'=>'a','ă'=>'a',
            'ç'=>'c','ć'=>'c','č'=>'c','ĉ'=>'c','ċ'=>'c',
            'ď'=>'d','đ'=>'d',
            'è'=>'e','é'=>'e','ê'=>'e','ë'=>'e','ē'=>'e','ę'=>'e','ě'=>'e','ĕ'=>'e','ė'=>'e',
            'ƒ'=>'f',
            'ĝ'=>'g','ğ'=>'g','ġ'=>'g','ģ'=>'g',
            'ĥ'=>'h','ħ'=>'h',
            'ì'=>'i','í'=>'i','î'=>'i','ï'=>'i','ī'=>'i','ĩ'=>'i','ĭ'=>'i','į'=>'i','ı'=>'i',
            'ij'=>'j','ĵ'=>'j',
            'ķ'=>'k','ĸ'=>'k',
            'ł'=>'l','ľ'=>'l','ĺ'=>'l','ļ'=>'l','ŀ'=>'l',
            'ñ'=>'n','ń'=>'n','ň'=>'n','ņ'=>'n','ʼn'=>'n','ŋ'=>'n',
            'ò'=>'o','ó'=>'o','ô'=>'o','õ'=>'o','ö'=>'o','ø'=>'o','ō'=>'o','ŏ'=>'o',
            'œ'=>'e',
            'ŕ'=>'r','ř'=>'r','ŗ'=>'r',
            'ù'=>'u','ú'=>'u','û'=>'u','ü'=>'u','ū'=>'u','ů'=>'u','ű'=>'u','ŭ'=>'u','ũ'=>'u','ų'=>'u',
            'ŵ'=>'w',
            'ÿ'=>'y','ŷ'=>'y',
            'ż'=>'z','ź'=>'z',
            'ß'=>'s','ſ'=>'s',
            'Α'=>'A','Ά'=>'A','Β'=>'B','Γ'=>'G','Δ'=>'D','Ε'=>'E','Έ'=>'E','Ζ'=>'Z','Η'=>'I','Ή'=>'I',
            'Θ'=>'TH','Ι'=>'I','Ί'=>'I','Ϊ'=>'I','Κ'=>'K','Λ'=>'L','Μ'=>'M','Ν'=>'N','Ξ'=>'KS','Ο'=>'O',
            'Ό'=>'O','Π'=>'P','Ρ'=>'R','Σ'=>'S','Τ'=>'T','Υ'=>'Y','Ύ'=>'Y','Ϋ'=>'Y','Φ'=>'F','Χ'=>'X',
            'Ψ'=>'PS','Ω'=>'O','Ώ'=>'O','α'=>'a','ά'=>'a','β'=>'b','γ'=>'g','δ'=>'d','ε'=>'e','έ'=>'e',
            'ζ'=>'z','η'=>'i','ή'=>'i','θ'=>'th','ι'=>'i','ί'=>'i','ϊ'=>'i','ΐ'=>'i','κ'=>'k','λ'=>'l',
            'μ'=>'m','ν'=>'n','ξ'=>'ks','ο'=>'o','ό'=>'o','π'=>'p','ρ'=>'r','σ'=>'s','τ'=>'t','υ'=>'y',
            'ύ'=>'y','ϋ'=>'y','ΰ'=>'y','φ'=>'f','χ'=>'x','ψ'=>'ps','ω'=>'o','ώ'=>'o',
            'š'=>'s', 'ž'=>'z', 'ý'=>'y', 'ô'=>'o', 'ť'=>'t',
            'Š'=>'S', 'Ž'=>'Z', 'Ý'=>'Y', 'Ô'=>'O'
            );
            //-----------------------------------------------------------------------------------------------------------------------
            
            $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' && $field !== 'main-img' && $field !== 'unpack-img' && $field !== 'cook-img'){
                     $doc->set($field, $value);
                }
             
               //we need to parse the title into the alias
               if($field == 'pagetitle') {
                 $alias = strtr($value, $noaccents);
            	 preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $alias);
            	 }
               if($field == 'vyrobce') {
                 $vyr_alias = strtr($value, $noaccents);
                 preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $vyr_alias);
            	 }
            
            }
            // now set the alias
            $doc->set('alias', $alias);
            $doc->set('template', '1'); //id šablony
            $doc->save();
            
            // have to repeat because ID is createed after resource save
            //set vyrobce, title and ID into alias
            $alias = $doc->get('id') . '-' . $vyr_alias . '-' . $alias;
            $doc->set('alias', $alias);
            $doc->save();
            
            
            //-----------change parent visibility --------- lze smazat po zaplnění všech kategorií----------
            
            if ($doc->get('parent')) { // pokud má rodiče
                //nastaví hidemenu aktuální rodiče
                $res = $modx->getObject('modResource', $doc->get('parent'));
                            if ($res->get('hidemenu')) {
                                $res->set('hidemenu', 0);
                                $res->save();
            					}
                //nastaví rodič nad ním, tedy hned první id ve stringu
                $ids = $modx->getParentIds($doc->get('parent'));
                if (!empty($ids)) {
                            $res = $modx->getObject('modResource', $ids[0]);
                            if ($res->get('hidemenu')) {
                                $res->set('hidemenu', 0);
                                $res->save();
                            }
                }
            }
            //---------------------------------------------------
            
            
            foreach ($allFormFields as $field=>$value)
            {
                if ($tv = $modx->getObject('modTemplateVar', array ('name'=>$field)))
                { 
                    if ($field !== 'main-img' && $field !== 'unpack-img' && $field !== 'cook-img') {  //ignore images
            
                    // 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 - odstraněná kontrola protože využívá extreního snippetu maxsize
            //$ext_array = array('jpg', 'jpeg', 'gif', 'png');
            
            $save_img_tmp = true; //some minor initialisation
            $uploadpath = 'assets/p-images/';
              
            // 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
                        //unique time stamp for image to prevent image cache on change
            			$cas = new DateTime();
            			$urlPath = $uploadpath . $filename . '?' . $cas->format('His');
            
                        // create directory to move file into if it doesn't exist
                        if(!is_dir($target_path)) {
                            mkdir($target_path, 0755, true);
                            } /*else {   //path is always the same no need for error
                            $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');
                         if ($save_img_tmp) $hook->setValue('tempImg', $urlPath); //save first img temp
            			 $save_img_tmp = false; //no more images into placeholder
                            // set the permissions on the file
                            if (!chmod($myTarget, 0644)) { /*some debug function*/ }
            
            // -------------- resize image ----------------------
            $image = new Imagick($myTarget);
            $watermark = new Imagick("/hosting/www/gvw.cz/www/super/assets/images/watermark.png");
            
            $imageprops = $image->getImageGeometry();
              if ($imageprops['width'] <= 800 && $imageprops['height'] <= 600) { 
                //is smaller, do nothing 
              }
              else {
                // Providing 0 forces thumbnailImage to maintain aspect ratio
                $image->resizeImage(800,600, imagick::FILTER_BOX, 0.8, true);
                 // write orig. images
            	$image->writeImages($myTarget, true);
              }
              // change target for watermarked images
              $myTarget = str_replace("p-images", "w-images", $myTarget);
              $image->compositeImage($watermark, imagick::COMPOSITE_OVER, 0, 0);
              $image->writeImages($myTarget, true);
            // ------ end resize ----
            
            
                        } else {
                            // File not uploaded
                            $errorMsg = 'There was a problem uploading the file.';
                            $hook->addError($sf, $errorMsg);
                            $output = false; // generate submission error
                        }
                      
            
                // if no file, and allowed (checbox delete) rewrite to empty value
                } else {
            	 if  //skip main-img
                     ( ($sf=='unpack-img' and $hook->getValue('obr2del')==1)
                      or
                      ($sf=='cook-img' and $hook->getValue('obr3del')==1)
                     )   
                  
            	   $doc->setTVValue($sf, '');    // insert empty value to TV
            
                }
              
            }
            $modx->reloadContext('web');
            //$modx->cacheManager->refresh(); // suggested by gallenkamp
            $hook->setValue('newId', $doc->get('id')); //return id of new resource
            
            return $output;
              • 38290
              • 712 Posts
              I've submitted a pull request to Articles that adds a Clear Cache check box to Article edit view allowing you to tell it not to clear cache on next save.
              https://github.com/splittingred/Articles/pull/24
                jpdevries
                • 3749
                • 24,544 Posts
                It looks to me like you could just replace all cases of

                $doc->set('X', 'Y'); 


                with

                $allFields['X'] = ['Y'];


                Then call the processor.


                FYI, these lines are doing nothing:

                $alias = strtr($value, $noaccents);
                preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $alias);


                First, strstr() doesn't take an array as the second argument, so it's never going to find anything, and even if it did work, you'd be setting $alias to the accented character (strstr() returns what it finds).

                Second, preg_replace() doesn't change the value of the original string.

                I would just use this line and forget about the $noaccents, since the preg_replace is going to remove them anyway:

                $alias = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $alias);


                Or go with MODX's built-in method:

                $alias = $doc->cleanAlias($alias);



                  Did I help you? Buy me a beer
                  Get my Book: MODX:The Official Guide
                  MODX info for everyone: http://bobsguides.com/modx.html
                  My MODX Extras
                  Bob's Guides is now hosted at A2 MODX Hosting
                  • 16430
                  • 217 Posts
                  Thanks for bug report!
                  I understand how to change first part of code before doc save, but how can I use modx processor for example to:
                  $doc->get('parent')
                  $doc->get('id')
                  $doc->setTVValue($sf, $urlPath)


                  If I leave this part unchanged, cache would be cleared only for first part of the code and new tv values for uploaded images wont be reflected...
                    • 3749
                    • 24,544 Posts
                    I think you could move that code up and then call the resource/update processor.
                      Did I help you? Buy me a beer
                      Get my Book: MODX:The Official Guide
                      MODX info for everyone: http://bobsguides.com/modx.html
                      My MODX Extras
                      Bob's Guides is now hosted at A2 MODX Hosting
                      • 16430
                      • 217 Posts
                      Tried to modify original code into this: (though I think its wrong....)
                      <?php
                      //...template field already added to form field
                      
                      $allFormFields = $hook->getValues(); 
                      foreach ($allFormFields as $field=>$value) { //remove unnecessary fields
                        if ($field !== 'spam' && $field !== 'resource_id' && $field !== 'main-img' && $field !== 'unpack-img' && $field !== 'cook-img'){
                          unset($field);
                        }
                       
                         //we need to parse the title into the alias
                         if($field == 'pagetitle') { 
                           $alias = cleanAlias($value);   //create alias from pagetitle
                      	   array_push($allFormFields, $alias);  //push alias value into array
                      
                      	 }
                         if($field == 'vyrobce') {
                           $vyr_alias = cleanAlias($value);   //create alias prefix
                      	    //do not push into array, we dont need that
                      	 }
                      
                      }
                      if (empty($hook->getValue('resource_id'))) { //resource not yet exists
                         $createdby = $modx->user->get('id');
                         array_push($allFormFields, $createdby);
                         $response = $this->modx->runProcessor('resource/create', $allFormFields);  //create resource
                         }
                      else {
                         $editedby = $modx->user->get('id');
                         array_push($allFormFields, $editedby);
                         $response = $this->modx->runProcessor('resource/update', $allFormFields);  //update resource
                      }   
                      
                      $doc = $modx->getObject('modResource');   //to get id of new resource
                      // have to repeat because ID is createed after resource save
                      //set vyrobce, title and ID into alias
                      $alias = $doc->get('id') . '-' . $vyr_alias . '-' . $alias;
                      $allFormFields['alias'] = $alias;  //update array with new alias
                      
                      foreach ($allFormFields as $field=>$value)
                      {
                          if ($tv = $modx->getObject('modTemplateVar', array ('name'=>$field)))
                          { 
                              if ($field !== 'main-img' && $field !== 'unpack-img' && $field !== 'cook-img') {  //ignore images
                      
                              // 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);
                      
                      //-----------change parent folders visibility --------- 
                      
                      if ($doc->get('parent')) { // if has parents
                          //set hidemenu to actual parent
                          $res = $modx->getObject('modResource', $doc->get('parent'));
                                      if ($res->get('hidemenu')) {
                                          $res->set('hidemenu', 0);
                                          $res->save();
                      					}
                          //set parent of parent
                          $ids = $modx->getParentIds($doc->get('parent'));
                          if (!empty($ids)) {
                                      $res = $modx->getObject('modResource', $ids[0]);
                                      if ($res->get('hidemenu')) {
                                          $res->set('hidemenu', 0);
                                          $res->save();
                                      }
                          }
                      }
                      //---------------------------------------------------
                      
                      
                      
                      //-------formit2file part, upload images and put path into TV --------
                      
                      // initialize output;
                      $output = true;
                      
                      $save_img_tmp = true; //some minor initialisation
                      $uploadpath = 'assets/p-images/';
                        
                      // 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 != '') {
                                  // 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
                                  //unique time stamp for image to prevent image cache on change
                      		      	$cas = new DateTime();
                      		      	$urlPath = $uploadpath . $filename . '?' . $cas->format('His');
                                   // create directory to move file into if it doesn't exist
                                  if(!is_dir($target_path)) {
                                      mkdir($target_path, 0755, true);
                                      } 
                                  // 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');
                                   if ($save_img_tmp) $hook->setValue('tempImg', $urlPath); //save first img temp
                      			       $save_img_tmp = false; //no more images into placeholder
                                      // set the permissions on the file
                                   if (!chmod($myTarget, 0644)) { /*some debug function*/ }
                      
                      // -------------- resize image ----------------------
                      $image = new Imagick($myTarget);
                      $watermark = new Imagick($modx->getOption('base_path') . "assets/images/watermark.png");
                      
                      $imageprops = $image->getImageGeometry();
                        if ($imageprops['width'] <= 800 && $imageprops['height'] <= 600) { 
                          //is smaller, do nothing 
                        }
                        else {
                          // Providing 0 forces thumbnailImage to maintain aspect ratio
                          $image->resizeImage(800,600, imagick::FILTER_BOX, 0.8, true);
                           // write orig. images
                      	$image->writeImages($myTarget, true);
                        }
                        // change target for watermarked images
                        $myTarget = str_replace("p-images", "w-images", $myTarget);
                        $image->compositeImage($watermark, imagick::COMPOSITE_OVER, 0, 0);
                        $image->writeImages($myTarget, true);
                      // ------ end resize ----
                      
                      
                                  } else {
                                      // File not uploaded
                                      $errorMsg = 'There was a problem uploading the file.';
                                      $hook->addError($sf, $errorMsg);
                                      $output = false; // generate submission error
                                  }
                                
                      
                          // if no file, and allowed (checbox delete) rewrite to empty value
                          } else {
                      	 if  //skip main-img
                               ( ($sf=='unpack-img' and $hook->getValue('obr2del')==1)
                                or
                                ($sf=='cook-img' and $hook->getValue('obr3del')==1)
                               )   
                            
                      	   $doc->setTVValue($sf, '');    // insert empty value to TV
                      
                          }
                        
                      }
                      $response = $this->modx->runProcessor('resource/update', $allFormFields);  //update resource
                      $response = $this->modx->runProcessor('resource/update', $submittedfiles);  //update tv for uploaded images
                      //$modx->reloadContext('web');
                      //$modx->cacheManager->refresh(); // suggested by gallenkamp
                      $hook->setValue('newId', $doc->get('id')); //return id of new resource
                      
                      return $output;