dd / evolutioncms-snippets-ddgetmultiplefield
A snippet for processing, manipulations and custom output structured data (JSON or separated by delimiters strings).
Installs: 2
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 3
Open Issues: 0
Type:modxevo-snippet
pkg:composer/dd/evolutioncms-snippets-ddgetmultiplefield
Requires
- php: >=5.6.0
- dd/evolutioncms-libraries-ddtools: >=0.62.0
- dd/evolutioncms-snippets-ddtypograph: >=2.5.0
README
A snippet for processing, manipulations and custom output structured data (JSON or separated by delimiters strings). The fields formed by the mm_ddMultipleFields widget values output gets more convinient with the snippet.
Features:
- Field value getting of a required document (TV) by its ID. The
inputString_docFieldandinputString_docIdparameters. - Return of a required values number by values and row number. The
startRow,totalRowsandfilterparameters. - Return of a required value by columns number. The
columnsparameter. - Rows sorting (including multiple sorting) by columns values before returning (
'ASC','DESC','RAND','REVERSE'). ThesortDirandsortByparameters. - Output of data being separated by rows and columns delimeters. The
rowGlueandcolGlueparameters. - Empty values remove before output. The
removeEmptyRowsandremoveEmptyColsparameters. - Values typography before output (the snippet ddTypograph is used). The
typographyparameter. - Result URL encode. The
urlencodeparameter. - Result JSON encode. The
outputFormatparameter. - Values returning by the given templates (chunks) of rows and columns (also the
[+rowNumber+]and[+rowNumber.zeroBased+]placeholders with a row number is available in the row and column templates). TherowTplandcolTplparameters. - Return of results in a chunk (the
outerTplparameter) sending additional data through placeholders. Theplaceholdersparameter.
Requires
- PHP >= 5.6
- (MODX)EvolutionCMS >= 1.1
- (MODX)EvolutionCMS.libraries.ddTools >= 0.62
- (MODX)EvolutionCMS.snippets.ddTypograph >= 2.5 (if typography is required)
Installation
Using (MODX)EvolutionCMS.libraries.ddInstaller
Just run the following PHP code in your sources or Console:
// Include (MODX)EvolutionCMS.libraries.ddInstaller require_once( $modx->getConfig('base_path') . 'assets/libs/ddInstaller/require.php' ); // Install (MODX)EvolutionCMS.snippets.ddGetMultipleField \DDInstaller::install([ 'url' => 'https://github.com/DivanDesign/EvolutionCMS.snippets.ddGetMultipleField', 'type' => 'snippet' ]);
- If
ddGetMultipleFieldis not exist on your site,ddInstallerwill just install it. - If
ddGetMultipleFieldis already exist on your site,ddInstallerwill check it version and update it if needed.
Manually
1. Elements → Snippets: Create a new snippet with the following data
- Snippet name:
ddGetMultipleField. - Description:
<b>3.10</b> A snippet for processing, manipulations and custom output structured data (JSON or separated by delimiters strings).. - Category:
Core. - Parse DocBlock:
no. - Snippet code (php): Insert content of the
ddGetMultipleField_snippet.phpfile from the archive.
2. Elements → Manage Files
- Create a new folder
assets/snippets/ddGetMultipleField/. - Extract the archive to the folder (except
ddGetMultipleField_snippet.php).
Parameters description
From the pair of inputString / inputString_docField parameters one is required.
-
inputString- Description: The input string containing values.
- Also supports JSON with any nesting level.
- Valid values:
stringJsonArray— JSON arraystringJsonObject— JSON objectstringHjsonObject— HJSON objectstringHjsonArray— HJSON arraystringQueryFormatted— Query stringstringSeparated— separated byinputString_rowDelimiterandinputString_colDelimiter
- Required
- Description: The input string containing values.
-
inputString_docField- Description: The name of the document field/TV which value is required to get.
- If the parameter is passed then the input string will be taken from the field / TV and
inputStringwill be ignored.
- If the parameter is passed then the input string will be taken from the field / TV and
- Valid values:
string - Default value: —
- Description: The name of the document field/TV which value is required to get.
-
inputString_docId- Description: ID of the document which field/TV value is required to get.
- Valid values:
integer - Default value:
$modx->documentIdentifier(the current document ID)
-
inputString_rowDelimiter- Description: The input string row delimiter (when
inputStringis not JSON). - Valid values:
stringregexp
- Default value:
'||'
- Description: The input string row delimiter (when
-
inputString_colDelimiter- Description: The input string column delimiter (when
inputStringis not JSON). - Valid values:
stringregexp
- Default value:
'::'
- Description: The input string column delimiter (when
-
startRow- Description: The index of the initial row (indexes start at
0). - Valid values:
integer - Default value:
0
- Description: The index of the initial row (indexes start at
-
totalRows- Description: The maximum number of rows to return.
- Valid values:
integer'all'— all rows will be returned
- Default value:
'all'
-
columns- Description: The indexes of columns to return (indexes start at
0). - Valid values:
stringCommaSeparatedarray'all'— all columns will be returned
- Default value:
'all'
- Description: The indexes of columns to return (indexes start at
-
filter- Description: Filter clause for columns.
- Thus,
returns the rows where:0 == 'a' || 0 =='b' && 1 == 'some' && 2 != ''0column is equal to'a'or0column is equal to'b'and1column is equal tosomeand2column is not equal to''.
- Quoted values are optional, this is valid too:
0 == a || 0 == b && 1 == some && 2 != - Double quotes are also supported as single quotes:
0 == "a" || 0 == "b" && 1 == "some" && 2 != "" - Spaces, tabs and line breaks are optional, this is valid too:
0==a||0==b&&1==some&&2!=.
- Thus,
- Valid values:
stringSeparated - Default value: —
- Description: Filter clause for columns.
-
removeEmptyRows- Description: Is it required to remove empty rows?
- Valid values:
01
- Default value:
1
-
removeEmptyCols- Description: Is it required to remove empty columns?
- Valid values:
01
- Default value:
1
-
sortBy- Description: The index of the column to sort by (indexes start at
0).- The parameter also takes comma-separated values for multiple sort, e.g.
'0,1'.
- The parameter also takes comma-separated values for multiple sort, e.g.
- Valid values:
stringCommaSeparatedarray
- Default value:
'0'
- Description: The index of the column to sort by (indexes start at
-
sortDir- Description: Rows sorting direction (case insensitive).
- Valid values:
'ASC'— the rows will be returned in ascending order'DESC'— the rows will be returned in descending order'RAND'— the rows will be returned in random order'REVERSE'— the rows will be returned in reversed order''— the rows will be returned without sorting (as set)
- Default value:
''
-
typography- Description: The comma separated indexes of the columns which values have to be corrected (indexes start at
0).- If unset, there will be no correction.
- Valid values:
stringCommaSeparatedarray
- Default value: —
- Description: The comma separated indexes of the columns which values have to be corrected (indexes start at
-
outputFormat- Description: Result output format (case insensitive).
- Valid values:
'html''json''array''htmlarray'
- Default value:
'html'
-
rowGlue- Description: The string that combines rows while rendering.
- It can be used along with
rowTpl.
- It can be used along with
- Valid values:
string - Default value:
''
- Description: The string that combines rows while rendering.
-
colGlue- Description: The string that combines columns while rendering.
- It can be used along with
colTplandrowTpl.
- It can be used along with
- Valid values:
string - Default value:
''
- Description: The string that combines columns while rendering.
-
rowTpl- Description: The template for row rendering (
outputFormathas to be =='html').- Available placeholders:
[+rowNumber+]— index of current row, starts at1[+rowNumber.zeroBased+]— index of current row, starts at0[+rowKey+]— key of current row, it is usefull for objects or associative arrays ininputString, for indexed arrays the placeholder is equal to[+rowNumber.zeroBased+][+total+]— total number of rows[+resultTotal+]— total number of returned rows[+colcolumnNumber+](e. g.[+col0+],[+col1+], etc) — column values, when columnNumber is zero-based column number[+columnKey+]— column values, when columnKey is original column key (see examples below)[+columnKey.nestedProperty+],[+colcolumnNumber.nestedProperty+]— values of a nested properties, if a column value is an object[+allColumnValues+]— values of all columns combined bycolGlue[+allColumnValuesObjectJson+]— values of all columns as a JSON object, where keys are original column keys, values are values
- Available placeholders:
- Valid values:
stringChunkNamestring— use inline templates starting with@CODE:
- Default value: —
- Description: The template for row rendering (
-
colTpl- Description: The comma-separated list of templates for column rendering (
outputFormathas to be =='html').- If the number of templates is lesser than the number of columns then the last passed template will be used to render the rest of the columns.
- Valid values:
stringCommaSeparatedarray
- Default value: —
- Description: The comma-separated list of templates for column rendering (
-
colTpl[$i]- Description: The template for column rendering.
- Available placeholders:
[+val+]— value of the column[+columnIndex+]— index of the column, starts at0[+columnKey+]— key of the column, it is usefull for objects or associative arrays ininputString, for indexed arrays the placeholder is equal to[+columnIndex+][+rowNumber+]— index of current row, starts at1[+rowNumber.zeroBased+]— index of current row, starts at0[+rowKey+]— key of current row, it is usefull for objects or associative arrays ininputString, for indexed arrays the placeholder is equal to[+rowNumber.zeroBased+][+total+]— total number of rows[+resultTotal+]— total number of returned rows
- Available placeholders:
- Valid values:
stringChunkNamestring— use inline templates starting with@CODE:'null'— specifies rendering without a template
- Default value:
'null'
- Description: The template for column rendering.
-
outerTpl- Description: Wrapper template (
outputFormathas to be !='array').- Available placeholders:
[+result+]— snippet result[+total+]— total number of rows[+resultTotal+]— total number of returned rows[+rowY.colX+]— value (Y— row number,X— column number)[+rowKey.colX+]— value (Key— row key,X— column number)
- Available placeholders:
- Valid values:
stringChunkNamestring— use inline templates starting with@CODE:
- Default value: —
- Description: Wrapper template (
-
placeholders- Description: Additional data has to be passed into the
outerTpl,rowTplandcolTpltemplates.- Nested objects and arrays are supported too:
{"someOne": "1", "someTwo": "test" }=>[+someOne+], [+someTwo+].{"some": {"a": "one", "b": "two"} }=>[+some.a+],[+some.b+].{"some": ["one", "two"] }=>[+some.0+],[+some.1+].
- Nested objects and arrays are supported too:
- Valid values:
stringJsonObject— as JSONstringHjsonObject— as HJSONstringQueryFormatted— as Query string- It can also be set as a native PHP object or array (e. g. for calls through
$modx->runSnippet):arrayAssociativeobject
- Default value: —
- Description: Additional data has to be passed into the
-
urlencode- Description: Is it required to URL encode the result?
outputFormathas to be !='array'.- URL encoding is used according to RFC 3986.
- Valid values:
01
- Default value:
0
- Description: Is it required to URL encode the result?
-
totalRowsToPlaceholder- Description: The name of the global (MODX)Evolution placeholder that holds the total number of rows.
- The placeholder won't be set if
totalRowsToPlaceholderis empty.
- The placeholder won't be set if
- Valid values:
string - Default value: —
- Description: The name of the global (MODX)Evolution placeholder that holds the total number of rows.
-
resultToPlaceholder- Description: The name of the global (MODX)Evolution placeholder that holds the snippet result.
- The result will be returned in a regular manner if the parameter is empty.
- Valid values:
string - Default value: —
- Description: The name of the global (MODX)Evolution placeholder that holds the snippet result.
Examples
Output images with description
The initial string (locates in images TV):
assets/images/some_img1.jpg::Image 1||assets/images/some_img2.jpg::Image 2
The snippet call in the template of a document:
[[ddGetMultipleField?
&inputString=`[*images*]`
&rowTpl=`images_item`
]]
The images_item chunk code:
[+col1+]: <img src="[+col0+]" alt="[+col1+]" />
Returns:
Image 1: <img src="assets/images/some_img1.jpg" alt="Image 1" /> Image 2: <img src="assets/images/some_img2.jpg" alt="Image 2" />
Output images from JSON using original column keys in row template
[[ddGetMultipleField?
&inputString=`[
{
"src": "assets/images/some_img1.jpg",
"alt": "Image 1"
},
{
"src": "assets/images/some_img2.jpg",
"alt": "Image 2"
}
]`
&rowTpl=`@CODE:<img src="[+src+]" alt="[+alt+]" />`
]]
Returns:
<img src="assets/images/some_img1.jpg" alt="Image 1" /> <img src="assets/images/some_img2.jpg" alt="Image 2" />
Output rows with dynamic number of columns using the [+allColumnValues+] placeholder and the rowTpl, colGlue parameters
Let the first row contains 2 columns, the second — 3, the third — 1:
[[ddGetMultipleField?
&inputString=`{
"First prices": [
"$100",
"$120"
],
"Second prices": [
"$300",
"$320",
"$350"
],
"Third prices": [
"$50"
]
}`
&outerTpl=`@CODE:<ul>[+result+]</ul>`
&rowTpl=`@CODE:<li>[+rowKey+]: [+allColumnValues+]</li>`
&colGlue=`, `
]]
Returns:
<ul> <li>First prices: $100, $120</li> <li>Second prices: $300, $320, $350</li> <li>Third prices: $50</li> </ul>
The data getting and output from prices TV of the document with ID = 25 in table format if the data is not empty
The initial field value:
Tasty apples::100::kg||Usual nails::5 000::centner||Cats::865::pieces
The snippet call (wherever):
[[ddGetMultipleField?
&inputString_docField=`prices`
&inputString_docId=`25`
&outerTpl=`prices`
&rowTpl=`prices_item`
]]
The prices_item chunk code:
<tr> <td>[+rowNumber+]</td> <td>[+col0+]</td> <td>[+col1+]/[+col2+]</td> </tr>
The prices chunk code:
<h1>Price table</h1> <table> [+result+] </table>
Returns:
<h1>Price table</h1> <table> <tr> <td>1</td> <td>Tasty apples</td> <td>100/kg</td> </tr> <tr> <td>2</td> <td>Usual nails</td> <td>5 000/centner</td> </tr> <tr> <td>3</td> <td>Cats</td> <td>865/pieces</td> </tr> </table>
Return document tags separated by commas using a regular expression in inputString_rowDelimiter
(MODX)EvolutionCMS.plugins.ManagerManager.mm_widget_tags is applied to tags TV where document tags are stored in tags.
User fills in the tags separated by commas, while the field may be filled both with spaces on the sides and without them.
tags TV value:
Cats, Dogs,Whales , Bears , Elephants
The snippet call:
[[ddGetMultipleField?
&inputString=`[*tags*]`
&inputString_rowDelimiter=`/\s*,\s*/`
&rowGlue=`, `
&rowTpl=`tags_item`
]]
The tags_item chunk contents:
<a href="[~16~]?tags=[+col0+]">[+col0+]</a>
Returns:
<a href="[~16~]?tags=Cats">Cats</a>, <a href="[~16~]?tags=Dogs">Dogs</a>, <a href="[~16~]?tags=Whales">Whales</a>, <a href="[~16~]?tags=Bears">Bears</a>, <a href="[~16~]?tags=Elephants">Elephants</a>
Passing additional data into templates via placeholders
[[ddGetMultipleField?
&inputString=`Grey::8 kg::loves meat||Red::6 kg::vegetarian`
&outerTpl=`cats`
&rowTpl=`cats_item`
&colTpl=`cats_item_color,null,null`
&placeholders=`{
"kind": "cats",
"price": "not for sale",
"colorTitle": "He has a nice thick coat."
}`
]]
The cats chunk code ([+kind+] will be replaced to cats):
<h1>Our [+resultTotal+] favorite [+kind+].</h1> <div> [+result+] </div>
The cats_item chunk code ([+price+] will be replaced to not for sale):
<p>[+rowNumber+]. [+col0+], [+col1+], [+col2+] — <i>[+price+]</i>.</p>
The cats_item_color chunk code ([+colorTitle+] will be replaced to He has a nice thick coat.):
<span title="[+colorTitle+]">[+val+]</span>
Returns:
<h1>Our 2 favorite cats.</h1> <div> <p>1. <span title="He has a nice thick coat.">Grey</span>, 8 kg, loves meat — <i>not for sale</i>.</p> <p>2. <span title="He has a nice thick coat.">Red</span>, 6 kg, vegetarian — <i>not for sale</i>.</p> </div>
Filter by column value (the filter parameter)
[[ddGetMultipleField?
&inputString=`[
[
"John Bon Jovi",
"musician",
"Bon Jovi"
],
[
"Steve Jobs",
"businessman",
"Apple"
],
[
"Roger Waters",
"musician",
"Pink Floyd"
],
[
"Robbie Williams",
"musician",
""
],
[
"Hugh Laurie",
"actor",
""
]
]`
&filter=`
1 == 'musician' &&
2 != '' ||
0 == 'Hugh Laurie'
`
&outputFormat=`json`
]]
Returns:
[ [ "John Bon Jovi", "musician", "Bon Jovi" ], [ "Roger Waters", "musician", "Pink Floyd" ], [ "Hugh Laurie", "actor", "" ] ]
Sort a JSON object by multiple columns (parameters → sortBy, sortDir)
[[ddGetMultipleField?
&inputString=`{
"Albert Einstein": {
"number": "18",
"born": "1879.03.14",
"died": "1955.04.18"
},
"Alan Turing": {
"number": "42",
"born": "1912.06.23",
"died": "1954.06.07"
},
"Nikola Tesla": {
"number": "7",
"born": "1856.07.10",
"died": "1943.01.07"
},
"Marie Curie": {
"number": "42",
"born": "1867.11.07",
"died": "1934.07.04"
},
"Dmitri Mendeleev": {
"number": "7",
"born": "1834.02.08",
"died": "1907.02.02"
}
}`
&sortDir=`ASC`
&sortBy=`number,born`
&outputFormat=`json`
]]
Returns:
{
"Dmitri Mendeleev": {
"number": "7",
"born": "1834.02.08",
"died": "1907.02.02"
},
"Nikola Tesla": {
"number": "7",
"born": "1856.07.10",
"died": "1943.01.07"
},
"Albert Einstein": {
"number": "18",
"born": "1879.03.14",
"died": "1955.04.18"
},
"Marie Curie": {
"number": "42",
"born": "1867.11.07",
"died": "1934.07.04"
},
"Alan Turing": {
"number": "42",
"born": "1912.06.23",
"died": "1954.06.07"
}
}
Run the snippet through \DDTools\Snippet::runSnippet without DB and eval
// Include (MODX)EvolutionCMS.libraries.ddTools require_once( $modx->getConfig('base_path') . 'assets/libs/ddTools/modx.ddtools.class.php' ); // Run (MODX)EvolutionCMS.snippets.ddGetMultipleField \DDTools\Snippet::runSnippet([ 'name' => 'ddGetMultipleField', 'params' => [ 'inputString' => '[ [ "assets/images/example1.png", "Example image 1" ], [ "assets/images/example2.png", "Example image 2" ] ]', 'rowTpl' => '@CODE:<img src="[+col0+]" alt="[+col1+]" />', ], ]);
It is hard to write here all possible examples so if here is something that you do not completely understand, please ask us.