We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 16899
    • 284 Posts
    Hi Guys

    Is it possible sum numeric values from a MIGX field into a placeholder or TV?

    Many Thanks,
    Nuno
      • 4172
      • 5,888 Posts
      could you post an example, please?
        -------------------------------

        you can buy me a beer, if you like MIGX

        http://webcmsolutions.de/migx.html

        Thanks!
        • 16899
        • 284 Posts
        Quote from: Bruno17 at Dec 13, 2013, 11:06 AM
        could you post an example, please?

        Hi Bruno

        First of all many thanks in advance to reply to my post. As attachment you can see the case in action. It´s a golf score card. The values were added in a diferent MIGX TV. What i need to do is build that panel(on the attachment) with the values previously added. It´s easy if i hadn´t the sum situation in the IN, OUT and TOTAL rows.

        Just to let you know, every colored circle, means a golf category, Pro, Ladies, etc The IN OUT and the TOTAL represent the distance on every category!

        The template i´m using in the other TV is:

        <!-- HOLE [[+idx]] -->
        <div class="hole">
        	<!-- START HOLE IMAGE -->
        	<div class="hole-image">
        		<img src="[[+hole-image]]" alt="[[*pagetitle]] - [[%ogolf.course_hole_n_[[+idx]]]]"/>
        	</div>
        	<!-- END HOLE IMAGE -->
        
        	<!-- START HOLE MAIN DETAILS -->
        	<div class="hole-main-details">
        
        	<!-- START HOLE NUMBER DETAILS -->
        	<div class="hole-number-details">
        		<div class="hole-number">[[%ogolf.course_hole_n_[[+idx]]]]</div>
        		<div class="hole-stroke-par">Stroke Index [[+stroke-index]] / Par [[+hole-par]]</div>
        	</div>
        	<!-- END HOLE NUMBER DETAILS -->
        
        	<!-- START HOLE DETAILS -->
        	<div class="hole-details">
        
        	<table class="score-card-individual">
        	<thead>
        		<tr>
        			<th>[[%ogolf.course_tee]]</th>
        			<th>[[%ogolf.course_meters]]</th>
        		</tr>
        	</thead>
        	<tbody>
        		<tr>
        			<td><img src="assets/images/icons/golf-cat-pros-icon-small.png" alt="[[%ogolf.course_cat_pro]]"></td>
        			<td>[[+cat-pro-distance]]</td>
        		</tr>
        		<tr>
        			<td><img src="assets/images/icons/golf-cat-amateurs-advanced-icon-small.png" alt="[[%ogolf.course_cat_amateurs_adv]]"></td>
        			<td>[[+cat-amateurs-advanced-distance]]</td>
        		</tr>
        		<tr>
        			<td><img src="assets/images/icons/golf-cat-amateurs-icon-small.png" alt="[[%ogolf.course_cat_amateurs]]"></td>
        			<td>[[+cat-amateurs-distance]]</td>
        		</tr>
        		<tr>
        			<td><img src="assets/images/icons/golf-cat-seniors-juniors-icon-small.png" alt="[[%ogolf.course_cat_senior_junior]]"></td>
        			<td>[[+cat-juniors-seniors-distance]]</td>
        		</tr>
        		<tr>
        			<td><img src="assets/images/icons/golf-cat-ladies-icon-small.png" alt="[[%ogolf.course_cat_ladies]]"></td>
        			<td>[[+cat-ladies-distance]]</td>
        		</tr>
        	</tbody>
        
        		<tfoot>
        			<tr>
        				<td colspan="2"></td>
        			</tr>
        		</tfoot>
        
        	</table>
        	
        	</div>
        	<!-- END HOLE DETAILS -->
        
        	<!-- START HOLE PRO TIP -->
        	<div class="hole-pro-tip">
        		<h4>[[%ogolf.course_pro_tip]]</h4>
        		<blockquote>
        		[[+hole-pro-tip]]
        		</blockquote>
        	</div>
        	<!-- END HOLE PRO TIP -->
        
        <div class="clear"></div>
        </div>
        <!-- END HOLE MAIN DETAILS -->
        
        </div>
        <!-- / HOLE 1 -->
        										
        										
        





        Many thanks in advance Bruno!! smiley
          • 4172
          • 5,888 Posts
          I'm still not sure, which values you want to sum up.
          whats your current getImageList - call to generate the table-view
          and whats the raw output of your MIGX - TV

            -------------------------------

            you can buy me a beer, if you like MIGX

            http://webcmsolutions.de/migx.html

            Thanks!
            • 16899
            • 284 Posts
            Quote from: Bruno17 at Dec 13, 2013, 06:15 PM
            I'm still not sure, which values you want to sum up.
            whats your current getImageList - call to generate the table-view
            and whats the raw output of your MIGX - TV


            I need to generate the attached tabbed content (probably with getresources) to get all the values from the first 9 holes(OUT), the last 9 holes (IN) and the TOTAL (IN + OUT) in every category and for the PAR/Meters Rows.

            I need to retain a sum, for the first 9 entries, last entries and the total of [[+cat-pro-distance]],[[+cat-amateurs-advanced-distance]], [[+cat-juniors-seniors-distance]], etc

            The code i´m showing you, will output a golf Hole and the values in meters for every tee (by category). In golf an hole has 5 places were people start playing the hole (tees) and everey tee has a diference distance according the category that you are in. Sorry about my english. So the code i´m showing you will show the hole and the distances for every tee in every hole.

            What i need is get a way to create something like what i´m showing you on the attached image but built from the inserted data in MIGX. I need the sum for IN OUT and PAR on every category and in very hole.

            Did you understaand what i need? Sorry againabout my english and many thanks tyo try to help me with this!!! smiley
              • 4172
              • 5,888 Posts
              with this next version of getImageList, its possible to summarize some fields:

              <?php
              
              /**
               * getImageList
               *
               * Copyright 2009-2011 by Bruno Perner <[email protected]>
               *
               * getImageList is free software; you can redistribute it and/or modify it
               * under the terms of the GNU General Public License as published by the Free
               * Software Foundation; either version 2 of the License, or (at your option) any
               * later version.
               *
               * getImageList is distributed in the hope that it will be useful, but WITHOUT ANY
               * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
               * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
               *
               * You should have received a copy of the GNU General Public License along with
               * getImageList; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
               * Suite 330, Boston, MA 02111-1307 USA
               *
               * @package migx
               */
              /**
               * getImageList
               *
               * display Items from outputvalue of TV with custom-TV-input-type MIGX or from other JSON-string for MODx Revolution 
               *
               * @version 1.4
               * @author Bruno Perner <[email protected]>
               * @copyright Copyright © 2009-2011
               * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU General Public License
               * version 2 or (at your option) any later version.
               * @package migx
               */
              
              /*example: <ul>[[!getImageList? &tvname=`myTV`&tpl=`@CODE:<li>[[+idx]]<img src="[[+imageURL]]"/><p>[[+imageAlt]]</p></li>`]]</ul>*/
              /* get default properties */
              
              
              $tvname = $modx->getOption('tvname', $scriptProperties, '');
              $tpl = $modx->getOption('tpl', $scriptProperties, '');
              $limit = $modx->getOption('limit', $scriptProperties, '0');
              $offset = $modx->getOption('offset', $scriptProperties, 0);
              $totalVar = $modx->getOption('totalVar', $scriptProperties, 'total');
              $randomize = $modx->getOption('randomize', $scriptProperties, false);
              $preselectLimit = $modx->getOption('preselectLimit', $scriptProperties, 0); // when random preselect important images
              $where = $modx->getOption('where', $scriptProperties, '');
              $where = !empty($where) ? $modx->fromJSON($where) : array();
              $sort = $modx->getOption('sort', $scriptProperties, '');
              $sort = !empty($sort) ? $modx->fromJSON($sort) : array();
              $toSeparatePlaceholders = $modx->getOption('toSeparatePlaceholders', $scriptProperties, false);
              $toPlaceholder = $modx->getOption('toPlaceholder', $scriptProperties, false);
              $outputSeparator = $modx->getOption('outputSeparator', $scriptProperties, '');
              $placeholdersKeyField = $modx->getOption('placeholdersKeyField', $scriptProperties, 'MIGX_id');
              $toJsonPlaceholder = $modx->getOption('toJsonPlaceholder', $scriptProperties, false);
              $jsonVarKey = $modx->getOption('jsonVarKey', $scriptProperties, 'migx_outputvalue');
              $outputvalue = $modx->getOption('value', $scriptProperties, '');
              $outputvalue = isset($_REQUEST[$jsonVarKey]) ? $_REQUEST[$jsonVarKey] : $outputvalue;
              $docidVarKey = $modx->getOption('docidVarKey', $scriptProperties, 'migx_docid');
              $docid = $modx->getOption('docid', $scriptProperties, (isset($modx->resource) ? $modx->resource->get('id') : 1));
              $docid = isset($_REQUEST[$docidVarKey]) ? $_REQUEST[$docidVarKey] : $docid;
              $processTVs = $modx->getOption('processTVs', $scriptProperties, '1');
              $reverse = $modx->getOption('reverse', $scriptProperties, '0');
              $sumFields = $modx->getOption('sumFields', $scriptProperties, '');
              $sumPrefix = $modx->getOption('sumPrefix', $scriptProperties, 'summary_');
              
              $modx->setPlaceholder('docid', $docid);
              
              $base_path = $modx->getOption('base_path', null, MODX_BASE_PATH);
              $base_url = $modx->getOption('base_url', null, MODX_BASE_URL);
              
              $migx = $modx->getService('migx', 'Migx', $modx->getOption('migx.core_path', null, $modx->getOption('core_path') . 'components/migx/') . 'model/migx/', $scriptProperties);
              if (!($migx instanceof Migx))
                  return '';
              $migx->working_context = isset($modx->resource) ? $modx->resource->get('context_key') : 'web';
              
              
              if (!empty($tvname)) {
                  if ($tv = $modx->getObject('modTemplateVar', array('name' => $tvname))) {
              
                      /*
                      *   get inputProperties
                      */
              
              
                      $properties = $tv->get('input_properties');
                      $properties = isset($properties['formtabs']) ? $properties : $tv->getProperties();
              
                      $migx->config['configs'] = $modx->getOption('configs', $properties, '');
                      if (!empty($migx->config['configs'])) {
                          $migx->loadConfigs();
                          // get tabs from file or migx-config-table
                          $formtabs = $migx->getTabs();
                      }
                      if (empty($formtabs) && isset($properties['formtabs'])) {
                          //try to get formtabs and its fields from properties
                          $formtabs = $modx->fromJSON($properties['formtabs']);
                      }
              
                      if (!empty($properties['basePath'])) {
                          if ($properties['autoResourceFolders'] == 'true') {
                              $scriptProperties['base_path'] = $base_path . $properties['basePath'] . $docid . '/';
                              $scriptProperties['base_url'] = $base_url . $properties['basePath'] . $docid . '/';
                          } else {
                              $scriptProperties['base_path'] = $base_path . $properties['base_path'];
                              $scriptProperties['base_url'] = $base_url . $properties['basePath'];
                          }
                      }
                      if ($jsonVarKey == 'migx_outputvalue' && !empty($properties['jsonvarkey'])) {
                          $jsonVarKey = $properties['jsonvarkey'];
                          $outputvalue = isset($_REQUEST[$jsonVarKey]) ? $_REQUEST[$jsonVarKey] : $outputvalue;
                      }
                      $outputvalue = empty($outputvalue) ? $tv->renderOutput($docid) : $outputvalue;
                      /*
                      *   get inputTvs 
                      */
                      $inputTvs = array();
                      if (is_array($formtabs)) {
              
                          //multiple different Forms
                          // Note: use same field-names and inputTVs in all forms
                          $inputTvs = $migx->extractInputTvs($formtabs);
                      }
              
                  }
                  $migx->source = $tv->getSource($migx->working_context, false);
              
              }
              
              if (empty($outputvalue)) {
                  return '';
              }
              
              //echo $outputvalue.'<br/><br/>';
              
              
              $items = $modx->fromJSON($outputvalue);
              
              // where filter
              if (is_array($where) && count($where) > 0) {
                  $items = $migx->filterItems($where, $items);
              }
              $modx->setPlaceholder($totalVar, count($items));
              
              
              if (!empty($reverse)) {
                  $items = array_reverse($items);
              }
              
              
              // sort items
              if (is_array($sort) && count($sort) > 0) {
                  $items = $migx->sortDbResult($items, $sort);
              }
              
              
              if (count($items) > 0) {
                  $items = $offset > 0 ? array_slice($items, $offset) : $items;
                  $count = count($items);
                  $limit = $limit == 0 || $limit > $count ? $count : $limit;
                  $preselectLimit = $preselectLimit > $count ? $count : $preselectLimit;
                  //preselect important items
                  $preitems = array();
                  if ($randomize && $preselectLimit > 0) {
                      for ($i = 0; $i < $preselectLimit; $i++) {
                          $preitems[] = $items[$i];
                          unset($items[$i]);
                      }
                      $limit = $limit - count($preitems);
                  }
              
                  //shuffle items
                  if ($randomize) {
                      shuffle($items);
                  }
              
                  //limit items
                  $tempitems = array();
                  for ($i = 0; $i < $limit; $i++) {
                      $tempitems[] = $items[$i];
                  }
                  $items = $tempitems;
              
                  //add preselected items and schuffle again
                  if ($randomize && $preselectLimit > 0) {
                      $items = array_merge($preitems, $items);
                      shuffle($items);
                  }
              
                  $properties = array();
                  foreach ($scriptProperties as $property => $value) {
                      $properties['property.' . $property] = $value;
                  }
              
                  $idx = 0;
                  $output = array();
                  $template = array();
                  $count = count($items);
                  foreach ($items as $key => $item) {
                      $formname = isset($item['MIGX_formname']) ? $item['MIGX_formname'] . '_' : '';
                      $fields = array();
                      foreach ($item as $field => $value) {
                          if (is_array($value)) {
                              if (is_array($value[0])) {
                                  //nested array - convert to json
                                  $value = $modx->toJson($value);
                              } else {
                                  $value = implode('||', $value); //handle arrays (checkboxes, multiselects)
                              }
                          }
              
              
                          $inputTVkey = $formname . $field;
                          if ($processTVs && isset($inputTvs[$inputTVkey])) {
                              if (isset($inputTvs[$inputTVkey]['inputTV']) && $tv = $modx->getObject('modTemplateVar', array('name' => $inputTvs[$inputTVkey]['inputTV']))) {
              
                              } else {
                                  $tv = $modx->newObject('modTemplateVar');
                                  $tv->set('type', $inputTvs[$inputTVkey]['inputTVtype']);
                              }
                              $inputTV = $inputTvs[$inputTVkey];
              
                              $mTypes = $modx->getOption('manipulatable_url_tv_output_types', null, 'image,file');
                              //don't manipulate any urls here
                              $modx->setOption('manipulatable_url_tv_output_types', '');
                              $tv->set('default_text', $value);
                              $value = $tv->renderOutput($docid);
                              //set option back
                              $modx->setOption('manipulatable_url_tv_output_types', $mTypes);
                              //now manipulate urls
                              if ($mediasource = $migx->getFieldSource($inputTV, $tv)) {
                                  $mTypes = explode(',', $mTypes);
                                  if (!empty($value) && in_array($tv->get('type'), $mTypes)) {
                                      //$value = $mediasource->prepareOutputUrl($value);
                                      $value = str_replace('/./', '/', $mediasource->prepareOutputUrl($value));
                                  }
                              }
              
                          }
                          $fields[$field] = $value;
              
                      }
              
                      if (!empty($sumFields)) {
                          $sumFields = is_array($sumFields) ? $sumFields : explode(',', $sumFields);
                          foreach ($sumFields as $sumField) {
                              if (isset($fields[$sumField])){
                                  $summaries[$sumPrefix.$sumField] = $summaries[$sumPrefix.$sumField] + $fields[$sumField];
                                  $fields[$sumPrefix.$sumField] = $summaries[$sumPrefix.$sumField]; 
                              }            
                          }
                      }
              
              
                      if ($toJsonPlaceholder) {
                          $output[] = $fields;
                      } else {
                          $fields['_alt'] = $idx % 2;
                          $idx++;
                          $fields['_first'] = $idx == 1 ? true : '';
                          $fields['_last'] = $idx == $limit ? true : '';
                          $fields['idx'] = $idx;
                          $rowtpl = '';
                          //get changing tpls from field
                          if (substr($tpl, 0, 7) == "@FIELD:") {
                              $tplField = substr($tpl, 7);
                              $rowtpl = $fields[$tplField];
                          }
              
                          if ($fields['_first'] && !empty($tplFirst)) {
                              $rowtpl = $tplFirst;
                          }
                          if ($fields['_last'] && empty($rowtpl) && !empty($tplLast)) {
                              $rowtpl = $tplLast;
                          }
                          $tplidx = 'tpl_' . $idx;
                          if (empty($rowtpl) && !empty($$tplidx)) {
                              $rowtpl = $$tplidx;
                          }
                          if ($idx > 1 && empty($rowtpl)) {
                              $divisors = $migx->getDivisors($idx);
                              if (!empty($divisors)) {
                                  foreach ($divisors as $divisor) {
                                      $tplnth = 'tpl_n' . $divisor;
                                      if (!empty($$tplnth)) {
                                          $rowtpl = $$tplnth;
                                          if (!empty($rowtpl)) {
                                              break;
                                          }
                                      }
                                  }
                              }
                          }
              
                          if ($count == 1 && isset($tpl_oneresult)) {
                              $rowtpl = $tpl_oneresult;
                          }
              
                          $fields = array_merge($fields, $properties);
              
                          if (!empty($rowtpl)) {
                              $template = $migx->getTemplate($tpl, $template);
                              $fields['_tpl'] = $template[$tpl];
                          } else {
                              $rowtpl = $tpl;
              
                          }
                          $template = $migx->getTemplate($rowtpl, $template);
              
              
                          if ($template[$rowtpl]) {
                              $chunk = $modx->newObject('modChunk');
                              $chunk->setCacheable(false);
                              $chunk->setContent($template[$rowtpl]);
              
              
                              if (!empty($placeholdersKeyField) && isset($fields[$placeholdersKeyField])) {
                                  $output[$fields[$placeholdersKeyField]] = $chunk->process($fields);
                              } else {
                                  $output[] = $chunk->process($fields);
                              }
                          } else {
                              if (!empty($placeholdersKeyField)) {
                                  $output[$fields[$placeholdersKeyField]] = '<pre>' . print_r($fields, 1) . '</pre>';
                              } else {
                                  $output[] = '<pre>' . print_r($fields, 1) . '</pre>';
                              }
                          }
                      }
              
              
                  }
              }
              
              if (count($summaries)>0){
                  $modx->toPlaceholders($summaries);    
              }
              
              
              if ($toJsonPlaceholder) {
                  $modx->setPlaceholder($toJsonPlaceholder, $modx->toJson($output));
                  return '';
              }
              
              if (!empty($toSeparatePlaceholders)) {
                  $modx->toPlaceholders($output, $toSeparatePlaceholders);
                  return '';
              }
              /*
              if (!empty($outerTpl))
              $o = parseTpl($outerTpl, array('output'=>implode($outputSeparator, $output)));
              else 
              */
              if (is_array($output)) {
                  $o = implode($outputSeparator, $output);
              } else {
                  $o = $output;
              }
              
              if (!empty($toPlaceholder)) {
                  $modx->setPlaceholder($toPlaceholder, $o);
                  return '';
              }
              
              return $o;
              
              



              you can use it like that (fieldnames of my Test-scenario was title and url):

              [[getImageList? 
              &tvname=`dayli`
              &sumFields=`title,url`
              &sumPrefix=`sumin_`
              &limit=`4`
              ]]
              
              title:[[+sumin_title]]</br>
              url:[[+sumin_url]]</br>
              
              [[getImageList? 
              &tvname=`dayli`
              &sumFields=`title,url`
              &sumPrefix=`sumout_`
              &offset=`4`
              ]]
              
              title:[[+sumout_title]]</br>
              url:[[+sumout_url]]</br>


              To summarize the results together, create a new snippet 'summarize' with this code:

              <?php
              
              $values = explode(',',$modx->getOption('values',$scriptProperties,''));
              
              $sum = 0;
              foreach ($values as $value){
                  $sum += $value;
              }
              
              return $sum;
              

              and use it like that:

              title:[[summarize? &values=`[[+sumin_title]],[[+sumout_title]]`]]</br>
              url:[[summarize? &values=`[[+sumin_url]],[[+sumout_url]]`]]</br>
              


              without a tpl the result is looking like that:
              http://www.revo222.webcmsolutions.de/75/sum-migx.html [ed. note: Bruno17 last edited this post 10 years, 4 months ago.]
                -------------------------------

                you can buy me a beer, if you like MIGX

                http://webcmsolutions.de/migx.html

                Thanks!
                • 16899
                • 284 Posts
                Hi Bruno

                Sorry to reply to early, I have to test yout given code! smiley Many, many thanks, after test i´ll let you know the results!! smiley
                Many thanks!!! You are a code GURU!!! smiley
                  • 36818
                  • 119 Posts
                  Hi Bruno,

                  may I reopen/join this thread?
                  I was looking exactly for the same solution and it works great.

                  But there is an other point I can't figure out.

                  Scenario:
                  A table with amounts in it as like
                  <table id="chart1" class="table" border="1">
                  <tbody>
                  
                  <tr>
                  <th>Anlagen</th>
                  <th>Beträge</th>
                  <th>Aufsummiert</th>
                  <th>Proz. Anteil</th>
                  
                  <tr>
                    <td>anlage 1</td>
                    <td>23943</td>
                    <td>23943</td>
                    <td>%</td>
                  </tr><tr>
                    <td>anlage 2</td>
                    <td>9405</td>
                    <td>33348</td>
                    <td>%</td>
                  </tr><tr>
                    <td>Anlage 3</td>
                    <td>49213</td>
                    <td>82561</td>
                    <td>%</td>
                  </tr>
                  
                  <tr>
                  <td>Total Bilanzsumme</td>
                  <td>82561</td>
                  <td> </td>
                  <td> </td>
                  
                  </tr>
                  </tbody>
                  </table>


                  To sum up is not a problem, but when I want to calculate the fraction (%) of each point I should know the total of amounts in "advance" to calculate it.
                  How can I achieve this?

                  Thanks for your help.
                    • 4172
                    • 5,888 Posts
                    does something like that work?

                    [[getImageList?
                    &tvname=`anlagen`
                    &sumFields=`betrag`
                    &sumPrefix=`presum_`
                    ]]
                     
                    Aufsummiert:[[+presum_betrag]]</br>
                    
                    [[getImageList?
                    &tvname=`anlagen`
                    &sumFields=`betrag`
                    &sumPrefix=`sum_`
                    &tpl=`anlagen`
                    ]]


                    chunk anlagen:
                    <tr><td>[[+betrag]]</td><td>[[+sum_betrag]]</td><td>[[calcFraction? &value=`[[+betrag]]` &total=`[[+presum_betrag]]`]]</td></tr>





                      -------------------------------

                      you can buy me a beer, if you like MIGX

                      http://webcmsolutions.de/migx.html

                      Thanks!
                      • 36818
                      • 119 Posts
                      Great! That worked! You're the wizard!

                      Only one small problem:

                      The first getImageList-Call

                      [[getImageList?
                      &tvname=`anlagen`
                      &sumFields=`betrag`
                      &sumPrefix=`presum_`
                      ]]
                      


                      returns also the debug-Array, like:
                      Array
                      (
                          [MIGX_id] => 1
                          [anlagen] => anlage 1
                          [betrag] => 23943
                          [presum_betrag] => 23943
                          [_alt] => 0
                          [_first] => 1
                          [_last] => 
                          [idx] => 1
                          [property.tvname] => Vermögensanlagen
                          [property.sumFields] => betrag
                          [property.sumPrefix] => presum_
                      )
                      ....
                      


                      Any idea?