get template variable value on each page modx revolution - php

I use modx and, to be honest, I am new to this CMS. I want to show corresponding Template Variable's value on each page. Here is my code written in the snippet:
<?php
if ( isset($modx->documentObject['PDF-Resource-Url'][1]) && !empty($modx->documentObject['PDF-Resource-Url'][1]) ) {
echo '<li class="related-link slide expanded">Pdf</li>';
}
?>
But it returns empty output. I use the latest version of modx revolution. I think that maybe this is the reason why I see empty output.
Thanks for helping!

It looks like you're using methods from MODX Evolution. Revolution is different so it would be a good idea to familiarise yourself with the documentation. I've provided some links below.
To get a template variable value using the API is simple:
$value = $modx->resource->getTVValue('tv-name');
$modx->resource always contains the object for the current resource.
Your example would become:
$output = '';
$url = $modx->resource->getTVValue('PDF-Resource-Url');
if (!empty($url)) {
$output = '<li class="related-link slide expanded">Pdf</li>';
}
// always return output rather than echoing to page
return $output;
How to get the current resource object:
http://rtfm.modx.com/revolution/2.x/making-sites-with-modx/structuring-your-site/resources
How to retrieve template variables:
http://rtfm.modx.com/revolution/2.x/making-sites-with-modx/customizing-content/template-variables/accessing-template-variable-values-via-the-api
Basic snippet development:
http://rtfm.modx.com/revolution/2.x/developing-in-modx/basic-development/snippets

Related

Loading a Search and Retrieve via URL (SRU) in php with simplexml_load_string returns an empty object

Im trying to load search result from an library api using Search and Retrieve via URL (SRU) at : https://data.norge.no/data/bibsys/bibsys-bibliotekbase-bibliografiske-data-sru
If you see the search result links there, its looks pretty much like XML but when i try like i have before with xml using the code below, it just returns a empty object,
SimpleXMLElement {#546}
whats going on here?
My php function in my laravel project:
public function bokId($bokid) {
$apiUrl = "http://sru.bibsys.no/search/biblio?version=1.2&operation=searchRetrieve&startRecord=1&maximumRecords=10&query=ibsen&recordSchema=marcxchange";
$filename = "bok.xml";
$xmlfile = file_get_contents($apiUrl);
file_put_contents($filename, $xmlfile); // xml file is saved.
$fileXml = simplexml_load_string($xmlfile);
dd($fileXml);
}
If i do:
dd($xmlfile);
instead, it echoes out like this:
Making me very confused that i cannot get an object to work with. Code i present have worked fine before.
It may be that the data your being provided ha changed format, but the data is still there and you can still use it. The main problem with using something like dd() is that it doesn't work well with SimpleXMLElements, it tends to have it's own idea of what you want to see of what data there is.
In this case the namespaces are the usual problem. But if you look at the following code you can see a quick way of getting the data from a specific namespace, which you can then easily access as normal. In this code I use ->children("srw", true) to say fetch all child elements that are in the namespace srw (the second argument indicates that this is the prefix and not the URL)...
$apiUrl = "http://sru.bibsys.no/search/biblio?version=1.2&operation=searchRetrieve&startRecord=1&maximumRecords=10&query=ibsen&recordSchema=marcxchange";
$filename = "bok.xml";
$xmlfile = file_get_contents($apiUrl);
file_put_contents($filename, $xmlfile); // xml file is saved.
$fileXml = simplexml_load_string($xmlfile);
foreach ( $fileXml->children("srw", true)->records->record as $record) {
echo "recordIdentifier=".$record->recordIdentifier.PHP_EOL;
}
This outputs...
recordIdentifier=792012771
recordIdentifier=941956423
recordIdentifier=941956466
recordIdentifier=950546232
recordIdentifier=802109055
recordIdentifier=910941041
recordIdentifier=940589451
recordIdentifier=951721941
recordIdentifier=080703852
recordIdentifier=011800283
As I'm not sure which data you want to retrieve as the title, I just wanted to show the idea of how to fetch data when you have a list of possibilities. In this example I'm using XPath to look in each <srw:record> element and find the <marc:datafield tag="100"...> element and in that the <marc:subfield code="a"> element. This is done using //marc:datafield[#tag='100']/marc:subfield[#code='a']. You may need to adjust the #tag= bit to the datafield your after and the #code= to point to the subfield your after.
$fileXml = simplexml_load_string($xmlfile);
$fileXml->registerXPathNamespace("marc","info:lc/xmlns/marcxchange-v1");
foreach ( $fileXml->children("srw", true)->records->record as $record) {
echo "recordIdentifier=".$record->recordIdentifier.PHP_EOL;
$data = $record->xpath("//marc:datafield[#tag='100']/marc:subfield[#code='a']");
$subData=$data[0]->children("marc", true);
echo "Data=".(string)$data[0].PHP_EOL;
}

Get all HTML list element using Simple HTML Dom

Currently I am working on a project which requires me to parse some data from an alternative website, and I'm having some issues (note I am very new to PHP coding.)
Here's the code I am using below + the content it returns.
$dl = $html2->find('ol.tracklist',0);
print $dl = $dl->outertext;
The above code returns the data for what we're trying to get, it's below but extremely messy provided you would like to see click here.
However, when I put this in a foreach, it only returns one of the a href attributes at a time.
foreach($html2->find('ol.tracklist') as $li)
{
$title = $li->find('a',0);
print $title;
}
What can I do so that it returns all of the a href elements from the example code above?
NOTE: I am using simple_html_dom.php for this.
Based on the markup, just point directly to it, just get it list then point to its anchor:
foreach ($html2->find('ol.tracklist li') as $li) {
$anchor = $li->find('ul li a', 0);
echo $anchor->href; // and other attributes
}

Get hard-coded values from component into plugin in Joomla 3.x

I have a custom component, in fact several. Each will have raw and hard-coded html at the beginning and end of their /view/default.php
I have a system plugin that needs to get this html and in some cases change it to something else, that can be managed in the back end. As a content plugin this works fine on all com_content articles, but it is ignored by components, my understanding is system plugins can do this but i can't get the data into the plugin and return it
example of component text ($text1, $text2 are defined at the top of the document)
JPluginHelper::importPlugin( 'system' );
JPluginHelper::importPlugin('plgSystemMyplugin');
$dispatcher =& JDispatcher::getInstance();
$data = array($text1, $text2); // any number of arguments you want
$data = $dispatcher->trigger('onBeforeRender', $data);
<article>
<div class="spacer" style="height:25px;"></div>
<div class="page_title_text">
<h1>title</h1>
<?php var_dump($data); ?>
</div>
<section>
my plugin:
jimport( 'joomla.plugin.plugin' );
class plgSystemMyplugin extends JPlugin {
function onBeforeRender() {
if (JFactory::getDocument()->getType() != 'html') {
return;
}
else {
$document=JFactory::getDocument();
$document->addCustomTag('<!-- System Plugin has been included (for testing) -->');
$document=JResponse::getBody();
$bob=JResponse::getBody();
$db = &JFactory::getDbo();
$db->setQuery('SELECT 1, 2 FROM #__table');
$results = $db->loadRowList();
$numrows=count($results);
if($numrows >0) {
foreach($results as $regexes) {
$document = str_replace($regexes[0],$regexes[1],$document);
}
return $document;
}
else {
$document = 'error with plugin';
}
JResponse::setBody($document);
return $document;
}
}
}
at the moment $data returns an array with a key 1 and value (string) of "" (blank/empty).
but not the data from the database I am expecting.
in simple terms I have {sometext} in my file and my database and it should return <p>my other text</p>
can you help?
thanks
Ok. Well looking at this deeper there is a couple of issues that jump out. The biggest being that you save getBody into a variable named $bob but then switch everywhere to using $document which is the object form above, not the content.
Also, you had a return $document hanging out in the middle of the code that prevented you from seeing that you were going to set $document as the new body. Probably should be more like below:
$bob=JResponse::getBody();
$db = &JFactory::getDbo();
$db->setQuery('SELECT 1, 2 FROM #__table');
$results = $db->loadRowList();
$numrows=count($results);
if($numrows >0) {
foreach($results as $regexes) {
$bob = str_replace($regexes[0],$regexes[1],$bob);
}
}
else {
$bob = 'error with plugin';
}
JResponse::setBody($bob);
return $document;
}
Original Thoughts:
Two thoughts to get you started. I'm not sure that this will actually fully answer the question, but should get you moving in the right direction.
First, you should not have to trigger the system plugin. They are system plugins, so the system will take care of that for you. If you wanted to use content plugins in your component (which you can definitely do!) then you would have to trigger them like your first set of code. In this case, don't bother with the entire dispatch section.
Second, your plugin looks set up to grab the body from the JDocument correctly, so that should work.
The likely issue is that the entire system plugin is just not being triggered. Make sure that it is installed and everything is named correctly. It has to be at plugins/system/myplugin/myplugin.php based on this name and make sure that the xml file with this also references myplugin as the plugin name. If not, the system won't find the class but likely won't throw an error. It will just skip it. This gives me trouble every time.
To do some checking just to make sure it gets called, I usually throw an echo or var_dump near the top of the file and just inside the function. Confirm that the function is at least getting called first and you should be most of the way to getting this to work.

How can I use node_load and render contextual links

I have an array of node IDs with which loop through and run node_load($nid) to retrieve the data for each of those nodes. Take for example the below code- that's roughly how it works at the moment.
foreach( $node->field_flights['und'] as $flight ):
$flightNode = node_load($flight['nid']);
echo $flightNode->title;
What I want to achieve is to load the node, then be able to do something along the lines of echo render($flightNode); so that it loads the template file for that node and I can render the $title_suffix variable in the node template which has been loaded.
I've tried the following to no avail. Nothing is output at all.
$flightNode = node_load($flight['nid']);
$builtFlightNode = node_build_content( $flightNode );
echo render( $builtFlightNode );
Would anyone provide some insight?
You can use node_view() to prepare the render array. For performance it might be wise to consider using node_load_multiple() (and it's counterpart node_view_multiple()) like this:
$nids = array();
foreach($node->field_flights['und'] as $flight):
$nids[] = $flight['nid'];
endforeach;
$flight_nodes = node_load_multiple($nids);
$view_mode = 'teaser'; // could also be 'full'
$views = node_view_multiple($flight_nodes, $view_mode);
// Renders all nodes in one go
echo render($views);
If that doesn't fit in with what you're doing though this should work on a node by node basis:
foreach($node->field_flights['und'] as $flight):
$flight_node = node_load($flight['nid']);
$view = node_view($flight_node, $view_mode);
echo render($view);
endforeach;
If you need to modify the content before it's rendered, you can just step through the $views or $view arrays and change what you need to before running it through render(). If you just want a particular part of the node content rendered, again just step through the array and apply render to the particular sub-array you're interested in.

PHP Wordpress gallery not finding the XMLl file

The code is below - it uses a wordpress shortcode which is [my_hmg=widget.xml] but if you try change the xml file like this [my_hmg=example_gallery.xml] it just always reverts to the default widget.xml
The problem is in the function my_hmg_filter_Callback in particular these 2 lines;
#$my_hmg_file = #$output['filename'];
if($my_hmg_file==""){$my_hmg_file = "widget.xml";}
For some reason it always thinks the file name is blank so always reverts to widget.xml.
The files can be downloaded from here - http://www.gopiplus.com/work/2010/07/18/horizontal-motion-gallery/
function my_hmg_show_filter($content){
return preg_replace_callback('/\[my_hmg=(.*?)\]/sim','my_hmg_filter_Callback',$content);
}
function my_hmg_filter_Callback($matches)
{
$my_hmg_package = "";
$var = $matches[1];
parse_str($var, $output);
#$my_hmg_file = #$output['filename'];
if($my_hmg_file==""){$my_hmg_file = "widget.xml";
}
Firstly change the short code to [my_hmg file='file.xml']
Then if you have a quick read of Wordpress's short code API you'll see that the first argument in the callback function are the attributes of the short code.
This way you can the reference the attribute 'file' in the array and get the proper url.

Categories