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;
Related
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.
The goal is to activate an existent topic in a Blog Entry page. Normally a user does this in the Pages Attributes section like so:
Now my goal is to do this programmaticaly. I won't post all my trials (since 2 days) here because it's just crap, but here's what I've done so far.
First I add a Blog Page to a chosen parent Page (ID 157):
use Concrete\Core\Page;
$parentPage = Page\Page::getByID(157);
$template = \PageTemplate::getByHandle('blog_entry');
$entry = $parentPage->add($type, array(
'cName' => 'My title',
'cDescription' => 'description',
'cHandle' => 'my_title',
'cvIsApproved' => true,
'cDatePublic' => $publishDate->format('Y-m-d H:i:s')
), $template);
As the newly created page is a blog_entry template the Blog Entry Topics is already assigned.
Then I create a Topic and add it to its Topic Tree (Blog Entry Topics) like so:
use \Concrete\Core\Tree\Type\Topic as TopicTree;
use \Concrete\Core\Tree\Node\Type\Topic as TopicTreeNode;
use \Concrete\Core\Tree\Node\Node as TreeNode;
$topicTree = TopicTree::getByName('Blog Entries');
$parentTopic = TreeNode::getByID($topicTree->getRootTreeNodeObject()->treeNodeID);
$item0 = TopicTreeNode::add('udland', $parentTopic);
How to activate/assign this Topic(Udland) to my page ($entry)? (As shown in the image)
I know it must be related to the DB-tables CollectionAttributeValues and atSelectedTopics. Also the Classes CollectionValue and CollectionKey must be involved.
I could add those entries manually in the DB but this isn't a good idea because I don't know what data is necessary to make this work correctly. The topics are used to filter Blog entries so I'm quite sure that there are other tables involved and as a Core developer said: "These are fragile little things" ;-).
As this version of concrete5 is a complete new launch, the developer docs aren't complete and after 2 days of digging inside the core code I'm just desperate.
Update (after a week of digging...)
I managed to do a hack taken out of a Controller method: (/concrete/controllers/panel/page/attributes.php -> submit()).
I know this isn't the way to go at all but it's my best trial so far:
(I just include the NameSpaces here to make clear what Classes I'm calling)
use Concrete\Core\Page;
use Concrete\Core\Page\Collection\Version\Version;
use Concrete\Core\Workflow\Request\ApprovePageRequest;
use CollectionAttributeKey;
use \Concrete\Core\Tree\Node\Type\Topic as TopicTreeNode;
Get the Attributes ID by handle:
$ak = CollectionAttributeKey::getByHandle('blog_entry_topics');
$attributekID = $ak->getAttributeKeyID();
get the topic
$item_one = TopicTreeNode::getNodeByName('Udland');
then simulate a posted form by:
$_POST = array(
'topics_' . $attributekID => array($item_one->treeNodeID)
);
I know this is so ugly and a big hack & not reliable at all but as said it's taken out of a Controller...
Then I do a slimmed version of the submit() method:
$c = Page\Page::getByID(157);
$published = new \DateTime();
$nvc = $c->getVersionToModify();
$nvcObj = $nvc->getVersionObject();
$data = array();
$data['cName'] = $nvcObj->cvName;
$data['cDescription'] = $nvcObj->cvDescription;
$data['cDatePublic'] = $published->format('Y-m-d H:i:s');
$data['uID'] = '1';
$nvc->update($data);
$setAttribs = $nvc->getSetCollectionAttributes();
$processedAttributes = array();
$selectedAKIDs = $attributekID;
if (!is_array($selectedAKIDs)) {
$selectedAKIDs = array();
}
$selected = is_array(array($attributekID)) ? array($attributekID) : array();
foreach ($setAttribs as $ak) {
if (in_array($ak->getAttributeKeyID(), $selected)) {
$ak->saveAttributeForm($nvc);
} else {
$nvc->clearAttribute($ak);
}
$processedAttributes[] = $ak->getAttributeKeyID();
}
$newAttributes = array_diff($selectedAKIDs, $processedAttributes);
foreach ($newAttributes as $akID) {
$ak = CollectionAttributeKey::getByID($akID);
$ak->saveAttributeForm($nvc);
}
So as said before this is really ugly but it's the best trial so far and somehow it works.
Then approve the Request by doing:
$pkr = new ApprovePageRequest();
$u = new User();
$pkr->setRequestedPage($c);
$v = Version::get($c, "RECENT");
$pkr->setRequestedVersionID($v->getVersionID());
$pkr->setRequesterUserID($u->getUserID());
$pkr->trigger();
$u->unloadCollectionEdit();
But what really makes me wonder is that method inside of /concrete/src/Attribute/Key/Key.php where finally the thing should happen (in my humble opinion):
/**
* Calls the functions necessary to save this attribute to the database. If no passed value is passed, then we save it via the stock form.
* NOTE: this code is screwy because all code ever written that EXTENDS this code creates an attribute value object and passes it in, like
* this code implies. But if you call this code directly it passes the object that you're messing with (Page, User, etc...) in as the $attributeValue
* object, which is obviously not right. So we're going to do a little procedural if/then checks in this to ensure we're passing the right
* stuff
*
* #param CollectionValue|mixed $mixed
* #param mixed $passedValue
*/
protected function saveAttribute($mixed, $passedValue = false)
{
/** #var \Concrete\Core\Attribute\Type $at */
$at = $this->getAttributeType();
$at->getController()->setAttributeKey($this);
if ($mixed instanceof AttributeValue) {
$attributeValue = $mixed;
} else {
// $mixed is ACTUALLY the object that we're setting the attribute against
//todo: figure out what $nvc should really be since it doesn't exist in this scope
$attributeValue = $nvc->getAttributeValueObject($mixed, true);
}
$at->getController()->setAttributeValue($attributeValue);
if ($passedValue) {
$at->getController()->saveValue($passedValue);
} else {
$at->getController()->saveForm($at->getController()->post());
}
$at->__destruct();
unset($at);
}
So I'm really curios to see what the reliable and system-suitable way is to resolve this.
Here's what I came up with that does work. You were pretty close.
use \Concrete\Core\Tree\Type\Topic as TopicTree;
use \Concrete\Core\Tree\Node\Type\Topic as TopicTreeNode;
use \Concrete\Core\Tree\Node\Node as TreeNode;
$parentPage = \Page::getbyPath('/blog');
$template = \PageTemplate::getByHandle('blog_entry');
$entry = $parentPage->add($type, array(
'cName' => 'ooops',
'cDescription' => 'hmmmm',
'cHandle' => 'yay',
'cvIsApproved' => true,
'cDatePublic' => '2015-12-21 00:00:00'
), $template);
$item0 = TopicTreeNode::getNodeByName('udland');
if (!$item0) {
$topicTree = TopicTree::getByName('Blog Entries');
$parentTopic = TreeNode::getByID($topicTree->getRootTreeNodeObject()->treeNodeID);
$item0 = TopicTreeNode::add('udland', $parentTopic);
}
$entry->setAttribute('blog_entry_topics', array($item0->getTreeNodeDisplayPath()));
It looks like the attribute takes in an array of node display paths and that is how it sets the selection. Additionally, you have to use the \Page alias, and not the fully qualified namespace as you were doing, otherwise you get an error about it being unable to clear the cache.
I have the below function to create active trail functionality. So if I were to have /blog as a "parent" and a post of /blog/mypost, when on mypost the blog link would show as highlighted. I don't want to have to make menu items for all the blog posts. The problem is when caching is turned on (not using settings.local.php and debug turned off) the getRequestUri isn't changing on some pages. It seems to be cached depending on the page. It works fine with page caching turned off but I'd like to get this working with caching. Is there a better way to check for the current path and apply the active class?
function mytheme_preprocess_menu(&$variables, $hook) {
if($variables['theme_hook_original'] == 'menu__main'){
$node = \Drupal::routeMatch()->getParameter('node');
if($node){
$current_path = \Drupal::request()->getRequestUri();
$items = $variables['items'];
foreach ($items as $key => $item) {
// If current path starts with a part of another path i.e. a parent, set active to li.
if (0 === strpos($current_path, $item['url']->toString())) {
// Add active link.
$variables['items'][$key]['attributes']['class'] .= ' menu-item--active-trail';
}
}
}
}
}
I've also tried putting this into a module to try and see if I can get the current path to then do the twig logic in the menu--main.twig.html template but I have the same problem.
function highlight_menu_sections_template_preprocess_default_variables_alter(&$variables) {
$variables['current_path'] = $_SERVER['REQUEST_URI'];
}
After a very long time trying all sorts of things, I found an excellent module which addresses exactly this problem. Install and go, not configuration, it just works:
https://www.drupal.org/project/menu_trail_by_path
Stable versions for D7 and D8.
I tried declaring an active path as part of a custom menu block, and even then my declared trail gets cached. Assuming it's related to the "There is no way to set the active link - override the service if you need more control." statement in this changelog, though why MenuTreeParameters->setActiveTrail() exists is anybody's guess.
For the curious (and for me when I search for this later!), here's my block's build() function:
public function build() {
$menu_tree = \Drupal::menuTree();
$parameters = new MenuTreeParameters();
$parameters->setRoot('menu_link_content:700c69e6-785b-4db7-be49-73188b47b5a3')->setMinDepth(1)->setMaxDepth(1)->onlyEnabledLinks();
// An array of routes and menu_link_content ids to set as active
$define_active_mlid = array(
'view.press_releases.page_1' => 385
);
$route_name = \Drupal::request()->get(RouteObjectInterface::ROUTE_NAME);
if (array_key_exists($route_name, $define_active_mlid)) {
$menu_link = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(array('id' => $define_active_mlid[$route_name]));
$link = array_shift($menu_link);
$parameters->setActiveTrail(array('menu_link_content:' . $link->uuid()));
}
$footer_tree = $menu_tree->load('footer', $parameters);
$manipulators = array(
array('callable' => 'menu.default_tree_manipulators:checkAccess'),
array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
);
$tree = $menu_tree->transform($footer_tree, $manipulators);
$menu = $menu_tree->build($tree);
return array(
'menu' => $menu,
);
}
[adding a new answer since this is a completely different approach than my earlier one]
If a CSS-based solution is acceptable, this seems to work okay:
.page-node-type-press-release {
a[data-drupal-link-system-path="press-room/press-releases"] {
// active CSS styles here
}
}
So this is the problem I am running into. If I have a comment object, I want to create a renderable array that is using the display settings of that comment. As of now this is what I have:
$commentNew = comment_load($var);
$reply[] = field_view_value('comment', $commentNew, 'comment_body', $commentNew->comment_body['und'][0]);
Which works fine because I dont have any specific settings setup for the body. But I also have image fields and video embed fields that I need to have rendered the way they are setup in the system. How would I go about doing that?
Drupal core does it with the comment_view() function:
$comment = comment_load($var);
$node = node_load($comment->nid);
$view_mode = 'full'; // Or whatever view mode is appropriate
$build = comment_view($comment, $node, $view_mode);
If you need to change a particular field from the default, use hook_comment_view():
function MYMODULE_comment_view($comment, $view_mode, $langcode) {
$comment->content['body'] = array('#markup' => 'something');
}
or just edit the $build array received from comment_view() as you need to if implementing the hook won't work for your use case.
I have created a Link DataObject to automatically let users create a reference to a different page in the Frontend. I use two languages in the frontend, German and English. In the popup I create a dropdown to select the pages
public function getCMSFields_forPopup()
{
return new FieldSet(
new TextField('Titel'),
new TextField('URL', 'Externer Link'),
new SimpleTreeDropdownField('PageLinkID', 'Interner Link', 'SiteTree')
);
}
But I only get the German pages in the dropdown. Tried to change the admin language to English but no change. The database seems to only return the German pages...
Any clue?
Edit: I did some more digging and found out how to do this. You need to call "disable_locale_filter" before you get your SiteTree objects:
Translatable::disable_locale_filter();
Then call "enable_locale_filter" once you've retrieved them:
Translatable::enable_locale_filter();
These are other approaches which I'll leave here as I think they are still useful...
I believe you may have to do this using Translatable::get_by_locale() - I assume you only want people to be able to select a page to link to within their language??
Perhaps something like this?
public function getCMSFields_forPopup()
{
$member = Member::currentUser();
if($member && $member->Locale) {
$pagesByLocale = Translatable::get_by_locale('SiteTree', $member->Locale);
$pagesByLocale = $pagesByLocale->map('ID', 'Title', '(Select one)', true);
return new FieldSet(
new TextField('Title'),
new TextField('URL', 'Externer Link'),
new DropdownField('PageLinkID', 'Interner Link', $pagesByLocale);
);
} else {
// Handle non-member
}
}
Edit: see comments below but another option is to use the Translatable::get_current_locale() function to find all pages in the Site Tree for that locale... if the user is viewing an english page then the locale should be set to english etc...
public function getCMSFields_forPopup()
{
$pagesByLocale = Translatable::get_by_locale('SiteTree', Translatable::get_current_locale());
$pagesByLocale = $pagesByLocale->map('ID', 'Title', '(Select one)', true);
return new FieldSet(
new TextField('Title'),
new TextField('URL', 'Externer Link'),
new DropdownField('PageLinkID', 'Interner Link', $pagesByLocale);
);
}
You can also get the locale from the current page e.g.
$this->Locale; // From within the model
$this->dataRecord->Locale; // from within the controller
Director::get_current_page()->Locale; // If you're outside the context of the page altogether i.e. code inside your DataObject.