Joomla custom fields inside template - php

I would like to customize my template for Joomla 3.7 so that I can use the new feature of Joomla 3.7, Custom fields (com_fields), and display and format them via CSS in my template where I need to display them.
Can someone suggest me the PHP code I should use in the template to display field(s), some example please.
Thanks in advance.

For everyone getting late to the party. In case you want to use your custom form fields in a Module-Override (which really are the only way to modify j!-templates, so google 'joomla template override') you can use this handy snippet:
<?php
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
$jcFields = FieldsHelper::getFields('com_content.article', $item, true);
$itemCustomFields = array();
foreach($jcFields as $field) {
$itemCustomFields[$field->name] = $field->rawvalue;
}
?>
Now you cna use your customfields like so: itemCustomFields['customFieldName1']
Haven't tested in article overrides. May soon, if so, this will get updated.

certainly not the right way to do it but I had the same need and I found a work around based on https://www.giudansky.com/news/12-coding/146-joomla-custom-fields
Copie default.php from /components/com_content/views/article/tmpl/default.php to
templates/YOUR_THEME/html/com_content/article/default.php
Add following code line 25 :
$myCustomFields = array();
foreach($this->item->jcfields as $field) {
$myCustomFields[$field->name] = $field->value;
}
$GLOBALS['myCustomFields'] = $myCustomFields;
Typically you put on a global var the content of fields attached to your article.
On your template page you can know retrieved value of your field.
just print_r($GLOBALS['myCustomFields']); to view the content of your array.
That will do the trick waiting for a better answer..

This is absolutely the wrong way to do this I think but I was tearing my hair out so i came up with this quick db query to return custom field values in the template. surely this violates some kind of joomla protocol?
obviously this assumes you can get $articleid into your template already which is the Current ID of your article.
I too am waiting on a better solution but hope this helps
$db =& JFactory::getDBO();
$sql = "select * from #__fields_values where `item_id` = $articleid";
$db->setQuery($sql);
$fieldslist = $db->loadObjectList();
echo $fieldslist[0]->value;
echo $fieldslist[1]->value;
echo $fieldslist[your field ID here]->value;

I found it was easiest to follow how com_fields does it in its rendering code. In Joomla!3.7+, you'll find it in [joomla_root]/components/com_fields/layouts/fields/render.php .
Here are the main parts you need to reproduce the formatting that Joomla has:
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
<dl class="fields-container">
<?php foreach ($this->item->jcfields as $field) : ?>
<?php // If the value is empty do nothing ?>
<?php if (!isset($field->value) || $field->value == '') : ?>
<?php continue; ?>
<?php endif; ?>
<?php $class = $field->params->get('render_class'); ?>
<dd class="field-entry <?php echo $class; ?>">
<?php echo FieldsHelper::render($context, 'field.render', array('field' => $field)); ?>
</dd>
<?php endforeach; ?>
</dl>
This loops through all available tags for the component or article. The nice thing about this method is it still applies the render classes you include with the fields.
Make sure to set Automatic Display to Do not automatically display on your fields; otherwise you will see them twice on your page view.
If you want to just target specific fields to show, you can use the name of the field to target it. (The label and value pair is underneath.) See the field Joomla docs for more info.

I implemented this small function to get specific custom field values:
function getCustomFieldValue($field_name, $article_id, $default_value = '') {
// Load custom field list
$fields = FieldsHelper::getFields('com_content.article', $article_id, true);
$field_ids = array_column($fields, 'id', 'name');
$model = JModelLegacy::getInstance('Field', 'FieldsModel', array('ignore_request' => true));
// Return the value if the field exists, otherwise the default
return array_key_exists($field_name, $field_ids)
? $model->getFieldValue($field_ids[$field_name] , $article_id)
: $default_value;
}
Usage:
$some_field_value = getCustomFieldValue('some-field-name', $some_article_id);
Optimization: I placed the function into a helper class, implemented the variables $fields, $field_ids and $model static and checked if they are already loaded to prevent redundant loading of the same data.

Related

Reduxframework: can't get values from a post selected by a select field

I have a dropdown select field to select a custom posttype within the woocommerce product edit screen and need to output the ID of this selected post.
This code works on my frontend but having issues to get it working with other plugins (here wplister).If i hardcode the selected post ID all works fine.
function psg_table_frontend_shortcode($atts, $content = null) {
global $psg_global;
/* START creating HTML Object */
ob_start();
?>
<p>
<?php
echo "The ID of the selected sizing Guide (cpt) inside the Product : " .$psg_global['psg-selected-sizing-guide-on-productpage'];
?>
</p>
$output = ob_get_clean();
/* END creating HTML Object */
return $output;
}
add_shortcode('psg_frontend', 'psg_table_frontend_shortcode');
Spoke to the support of wplister but they said it is probably an issue with the reduxframwork and the global variable.
Any idea?
if you are in a function, who knows if your psg_global is even in scope yet... so try this:
$psg_global= get_option( 'psg_global'); // or whatever your opt name is
$productpage = $psg_global['psg-selected-sizing-guide-on-productpage'];
echo $productpage;
also, might want to use 'psg_selected_sizing_guide_on_productpage' with underscores instead of 'psg-selected-sizing-guide-on-productpage' because that way you can do this:
extract($psg_global)
and all your vars would be in scope.
for example:
echo $psg_selected_sizing_guide_on_productpage

Joomla render full article by id with "JModelLegacy getInstance article"

I'm stuck trying to get joomla full article to render in a tab. The tab is working. I just can´t render the article content. This is where I am now.
This is helper.php
public static function getArticle($articleId)
{
JModelLegacy::addIncludePath(JPATH_SITE.'/components/com_content/models', 'ContentModel');
$model = JModelLegacy::getInstance('Article', 'ContentModel', array('ignore_request' => true));
$article = $model->getItem((int) $articleId);
$fullarticle = $item->fulltext;
$itemsHtml = '<div>'. $fullarticle .'</div>';
return $itemsHtml;
}
And this is in default.php
...code...
else if ($list_of_tabs['use'][$i][0] == 'article'){
echo '<div class="tab-pane '.$active.'" id="'.$i.$rid.'">'.
modJpTabsHelper::getArticle($list_of_tabs['article'][$i], $params) .
'</div>';
}
...code...
If you need more info. Don't hesitate to ask.
What are you trying to achieve: to write your own Joomla! extension which displays articles in a tab or you just need to display your J! articles in a tab?
If it's a latter, then there are already some nice and free (as in a "free bear") add-ons written just for that.
You are trying to use the model part of an MVC as a thing to render.
You should use the MVC system - using a controller to gathering the model and the view, and then you can render the model with the attached view, via the controller.
So you use something like (I've not tested this - you will need to correct it).
$filter=array('id' => $i->query['id']);
$options=array('filter_fields' => $filter,'ignore_request' => true);
$ctl = new ContentModelController();
$view = $ctl->getView( 'Article');
$model = $ctl->getModel( 'Article','',$options);
you may need to set params from application, eg..
$model->setState('params', JApplication::getInstance('site')->getParams());
then continue
$view->setModel( $model, true );
$result = $view->display();
Make sure that you have JLoader::import'ed any classes/classpaths - j. tends to fail silently if they aren't found, which can be difficult to trace.
Sorry, it's only a partial solution - but hopefully it may put you on the right track.
Here was the problem:
$fullarticle = $item->fulltext;
Article object from model was in variable $article not $item:
$article = $model->getItem((int) $articleId);
So getting property fulltext from article object should be:
$fullarticle = $article->fulltext;

Joomla get content by ajax

How to get joomla content using ajax? (I want to show content of specyfic page in popup), this is my code: (called by ajax)
$option = JRequest::getCmd('option');
$view = JRequest::getCmd('view');
if ($option=="com_content" && $view=="article") {
$ids = explode(':',JRequest::getString('id'));
$article_id = $ids[0];
$article =& JTable::getInstance("content");
$article->load($article_id);
echo '<h2>'.$article->get("title").'</h2>';
echo $article->get("introtext"); // and/or fulltext
}
This works fine only for artilces, but the problem is when for example I want to show category, or component
Please see your if condition it checks if option is equal to com_content & view is equal to article only. If view contains category it won't work. So add the conditions in if statement so that your code gets executed.
for category you need to add view=category & like for other components as well.

Drupal: How to display part of an author's profile in a node

I have been trying to do display a custom field I created in the manage fields section of user accounts for nodes in addition to the profile page. The problem I am having with this code is that it will display the first field it finds and display that for every user, not the field for that particular user.
And ideas? I believe it's finding the first value in the array and not the value for the particular user in the array.
Here is m setup so far:
Added this to my template.php of my theme:
function mythemename_preprocess_node(&$vars) {
global $user;
$user = user_load($user->uid); // Make sure the user object is fully loaded
$team = field_get_items('user', $user, 'field_team');
if ($team) {
$vars['field_team'] = $team[0]['value'];
}
}
Then, added this to my node.tpl.php in order to display it on nodes.
if (isset($field_team) && !empty($field_team)) :
echo '$field_team.'</div>';
endif;
UPDATE:
Found my own aswer here:
http://drupal.org/node/1194506
Code used:
<?php
$node_author = user_load($node->uid);
print ($node_author->roles[3]);
print ($node_author->field_biography['und'][0]['value']);
?>
You can use drupal's 'Author Pane' module for that. Try this:
http://drupal.org/project/author_pane

Search a specific database field with CakePHP post method

I’m trying to implement a simple search into an application, but not sure of the best way to handle this. My database contains a Listings object which includes City field. I want to create a search form where the user inputs a city into a text field and gets all of the Listings for that city on the next page. I don’t want to perform a full-text search, just the query on that City field.
Also, on the results page, I’d like to store the query in POST and can’t figure out the best way to do this.
What is the best way to approach this in the controller?
Well your view would look something like this
$this->Form->Create('Listing', array('action'=>'search'));
$this->Form->input('city', array('default'=>$city));
$this->Form->end();
if (isset($listings)) {
//code to display listings
}
This view would create the correct form. And your controller needs to get that value
function search() {
$city = '';
if (!empty($this->data)) {
$city = $this->data['Listing']['city'];
$opts = array(
'conditions' => array('Listing.city' => $city)
);
$listings = $this->Listing->find('all', $opts);
$this->set('listings', $listings);
}
$this->set('city', $city); // so the keyword is saved. Can also get it via $this->data
}
This code should give you an idea on how to do this.
This is a great tutorial with a CakePHP search plugin tutorial. You can download the full working code as well from github (w/ MySQL dump).
View:
<?php echo $this->Form->create()
echo $this->Form->input('search');
?>
<input name="data[Product][word]" />
controller:
<?php
$result = $this->Product->find('all',array(
'conditions'=>array(
'OR'=>array(
array('name LIKE'=>'%'.$word.'%'),
array('description LIKE'=>'%'.$word.'%')))));
$this->set(compact('result'));
?>

Categories