Xpages File Download Control sort column - file

I would like to have a File Download control display the attachments with the newest (latest) Created On date at the top. The default is to display the newest last.
<xp:fileDownload rows="30" id="FD"
displayLastModified="false" value="#{document1.files}"
style="width:98%" hideWhen="false"
displayType="true" allowDelete="false" displayCreated="true">
</xp:fileDownload>

As there's currently no better answer, I'll post one here.
Actually, the <xp:fileDownload> component lists file attachments in order they appear in document's Rich Text field, not the newest last:
You can't change this behavior with any of the properties, so the one possible way is to obtain the list of attachments, sort it like you need, and then feed the sorted list to <xp:repeat> component, where you can draw the attachment table that will just slightly or even not differ from that displayed by <xp:fileDownload>. It's not that hard, just look at created HTML markup in your browser debug tool and recreate that inside your <xp:repeat>.
Suppose you have dominoData declared on your page:
<xp:this.data>
<xp:dominoDocument var="document1"
documentId="9CAA72D47AEA7C8D462582FB005AB525"
action="openDocument" />
</xp:this.data>
Then create the <xp:panel> where your <xp:repeat> will reside. Create the dataContext for your panel:
<xp:panel>
<xp:this.dataContexts>
<xp:dataContext var="attachments">
<xp:this.value><![CDATA[
#{javascript:
var sourceList:java.util.List = document1.getAttachmentList('files');
if (sourceList.size() == 0) {
return sourceList;
}
java.util.Collections.sort(sourceList, createdComparator);
return sourceList;
}
]]></xp:this.value>
</xp:dataContext>
</xp:this.dataContexts>
</xp:panel>
There you get a list of com.ibm.xsp.model.domino.wrapped.DominoDocument.AttachmentValueHolder objects, then sort the list with declared Comparator (see update below) using the created file attribute, and return the sorted list as attachments variable.
Then you create <xp:repeat> and nest it inside your <xp:panel> after <xp:dataContexts>. Give it the dataContext's variable name as a value:
<xp:repeat value="#{attachments}" var="attachment">
<xp:text value="#{attachment.type}" />
<xp:label value=" - " />
<xp:text>
<xp:this.value><![CDATA[
#{javascript:
var rawSize = attachment.getLength();
return (rawSize < 1024 ? 1 : (rawSize / 1024).toFixed(0)) + " KB";
}
]]></xp:this.value>
</xp:text>
<xp:label value = " - " />
<xp:link text="#{attachment.name}" value="#{attachment.href}" />
<xp:label value = " - " />
<xp:text>
<xp:this.value>
#{javascript:
return new java.util.Date(attachment.getCreated());
}
</xp:this.value>
<xp:this.converter>
<xp:convertDateTime type="both" timeStyle="short" />
</xp:this.converter>
</xp:text>
<xp:br />
</xp:repeat>
Here's the result of <xp:repeat> output compared to <xp:fileDownload>:
Just create the markup that looks like fileDownload's table, and you're done.
Update
It's worth the effort to create a request scoped Managed Bean that will serve as the Comparator instead of implementing some good sorting algorithm right inside SSJS code block.
Create a Java class inside Code/Java folder under some existing or new package. If the package name is e.g. com.benway.util and the class name is CreatedComparator:
package com.benway.util;
import java.util.Comparator;
import com.ibm.xsp.model.FileRowData;
public class CreatedComparator implements Comparator<FileRowData> {
public int compare(FileRowData file1, FileRowData file2) {
if (file1 == null || file2 == null) return 0;
return (int)(file2.getCreated() - file1.getCreated());
}
}
Register your new class as a managed bean in your faces-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config>
<managed-bean>
<managed-bean-name>createdComparator</managed-bean-name>
<managed-bean-class>
com.benway.util.CreatedComparator
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
...etc...
</faces-config>
Now you're really done :)

Related

Inserting image into visualforce email template (without hard-coding IDs)

The "official" solution for including images in visualforce email templates suggests hard coding IDs in your template to reference an image file stored as a document.
https://help.salesforce.com/HTViewHelpDoc?id=email_template_images.htm&language=en_US
Is there a better way that avoids hard coding instance ID and OID? I tried using the partner URL to grab the instance ID, but I got the following error
Error Error: The reference to entity "oid" must end with the ';' delimiter.
Using:
{!LEFT($Api.Partner_Server_URL_140,FIND(".com/",$Api.Partner_Server_URL_140)+3)/
to replace "https://na2.salesforce.com/"
in
"na2.salesforce.com/servlet/servlet.ImageServer?id=01540000000RVOe&oid=00Dxxxxxxxxx&lastMod=1233217920"
Should I use a static resource instead?
I've arrived here looking for an answer for this question related to hardcoded ID and OID in Visualforce e-mail templates. Well, I found a workaround for that.
First I needed to create a Visualforce Component:
<apex:component access="global" controller="LogomarcaController">
<apex:image url="{!LogoUrl}" />
</apex:component>
In the respective controller class, I've created a SFInstance property to get the correct URL Salesforce Instance, LogoUrl property to concatenate SFInstance and IDs... And Finally I've used Custom Settings (Config_Gerais__c.getInstance().ID_Documento_Logomarca__c) to configurate the ID of Image (in my case, Document Object) on Sandbox or Production:
public class LogomarcaController {
public String LogoUrl {
get {
id orgId = UserInfo.getOrganizationId();
String idDocumentoLogomarca = Config_Gerais__c.getInstance().ID_Documento_Logomarca__c;
return this.SfInstance + '/servlet/servlet.ImageServer?id=' + idDocumentoLogomarca + '&oid=' + orgId ;
}
}
public String SfInstance
{
get{
string SFInstance = URL.getSalesforceBaseUrl().toExternalForm();
list<string> Dividido = SFInstance.split('.visual', 0);//retira o restante a partir de .visual
SFInstance = dividido[0];
dividido = SFInstance.split('://',0);//retira o https://
SFInstance = dividido[1];
if(!SFInstance.contains('sybf')) //managed package prefix, if you need
{
SFInstance = 'sybf.'+ SFInstance;
}
return 'https://'+SFInstance;
}
}
}
And finally, I've added the component in Visualforce template:
<messaging:emailTemplate subject="Novo Ofício - {!relatedTo.name}" recipientType="User" relatedToType="Oficio__c" >
<messaging:htmlEmailBody >
<c:Logomarca />
</messaging:htmlEmailBody>
<messaging:plainTextEmailBody >
</messaging:plainTextEmailBody>
</messaging:emailTemplate>
PS: Some of my variables, properties and comments are in my native language (portuguese). If you have some problems understanding them, please ask me!
We ran into a similar problem and after trying various solutions, the following worked for us. In our case the image is uploaded as a content asset(https://help.salesforce.com/articleView?id=000320130&type=1&language=en_US&mode=1)
Solution:
<img src="{!LEFT($Api.Partner_Server_URL_260,FIND('/services',$Api.Partner_Server_URL_260))}/file-asset-public/<Image_Name_Here>?oid={!$Organization.Id}&height=50&width=50"/>

XPages: File Download control link url

I have a file download control that lists attachments from some documents in my database.
I want to display an icon next to each row and make it a link to the attachment of the row.
If not sure how to do it for each row, let's assume that i have only 1 row. How can i get the link of the attachment so as to declare it as href in a link control?
As i already mentioned in my Comment if you are using a <xp:fileDownload> you can add a Icon if you set displayType="true" and because you didnt add code to your question i guess your code could look something like this:
//..your code
<xp:panel id="row">
<xp:this.data>
<xp:dominoDocument
var="document1"
action="openDocument"
documentId="#{javascript://example... viewEntry.getDocument().getUniversalId()}">
</xp:dominoDocument>
</xp:this.data>
<xp:fileDownload
rows="30"
id="fileDownload1"
displayLastModified="false"
value="#{document1.Body}"
displayType="true">
</xp:fileDownload>
</xp:panel>
//..your code
or if you dont use a <xp:fileDownload> and maby just Display rows with the attachment Name you could use something like this:
//... your code
<xp:panel id="row">
<xp:repeat
id="repeat1"
rows="30"
value="#{javascript:#AttachmentNames()}"
indexVar="attachmentIndex"
var="attachment">
<xp:link
escape="true"
text="#{javascript:attachment;}"
id="link1"
target="_blank">
<xp:this.value><![CDATA[#{javascript:
var url = facesContext.getExternalContext().getRequest().getContextPath() + "/0/" +
/*in my case: viewEntry.getDocument().getUniversalID()*/
+ "/$File/"+ AttachmentName;
return url;}]]></xp:this.value>
<xp:image id="image1">
<xp:this.url><![CDATA[#{javascript://
var pdfImage = 'pdf.gif';
if(attachment.indexOf("pdf")> 0)
return pdfImage;
}]]></xp:this.url>
</xp:image> 
</xp:link>
<br></br>
</xp:repeat>
</xp:panel>//...your code
The <xp:repeat> inside your row will create a link for each attachment inside of your document you can remove it if you only have one attachment per document.

Styling/Theming Drupal 7 Content Type Record

I developed a Content type of "Car Sales" with following fields:
Manufacturer
Model
Make
Fuel Type
Transmission (Manual/Automatic)
Color
Registered? (Yes/No)
Mileage
Engine Power
Condition (New/Reconditioned/Used)
Price
Pictures (Multiple uploads)
I have developed View of this Content Type to display list of cars. Now I want to develop a screen/view for individual Car Sale Record like this:
Apart from arranging fields, please note that I want to embed a Picture Gallery in between. Can this be achieved through Drupal 7 Admin UI or do I need to create custom CSS and template files? If I need to edit certain template files/css, what are those? I'm using Zen Sub Theme.
I would accomplish this by creating a page, and then creating a node template to accompany it. Start by creating a new node, and then record the NID for the name of the template.
Then, in your template, create a new file, and name it in the following manner: node--[node id].tpl.php
Then, in that file, paste in the following helper function (or you can put it in template.php if you're going to use it elsewhere in your site):
/**
* Gets the resulting output of a view as an array of rows,
* each containing the rendered fields of the view
*/
function views_get_rendered_fields($name, $display_id = NULL) {
$args = func_get_args();
array_shift($args); // remove $name
if (count($args)) {
array_shift($args); // remove $display_id
}
$view = views_get_view($name);
if (is_object($view)) {
if (is_array($args)) {
$view->set_arguments($args);
}
if (is_string($display_id)) {
$view->set_display($display_id);
}
else {
$view->init_display();
}
$view->pre_execute();
$view->execute();
$view->render();
//dd($view->style_plugin);
return $view->style_plugin->rendered_fields;
} else {
return array();
}
}
Then add the following code to your template:
<?php
$cars = views_get_rendered_fields('view name', 'default', [...any arguments to be passed to the view]);
foreach ($cars as $car): ?>
<div>Put your mockup in here. It might be helpful to run <?php die('<pre>'.print_r($car, 1).'</pre>'); ?> to see what the $car array looks like.</div>
<?php endforeach;
?>
Just change the placeholders in the code to whatever you want the markup to be, and you should be set!
As I mentioned above, it's always helpful to do <?php die('<pre>'.print_r($car,1).'</pre>'); ?> to have a visual representation of what the array looks like printed.
I use views_get_rendered_fields all the time in my code because it allows me to completely customize the output of the view.
As a Reminder: Always clear your caches every time you create a new template.
Best of luck!

Adding a 1 to many file upload to CRUD

My app has sales listing functionality that will allow the user to add 1 or more photos for the product that they want to sell.
I'm attempting to use the upload/filestore_image of ATK with a Join table to create the relationship - my models:
class Model_Listing extends Model_Table {
public $entity_code='listing';
function init(){
parent::init();
$this->addField('name');
$this->addField('body')->type('text');
$this->addField('status');
$this->addField('showStatus')->calculated(true);
}
function calculate_showStatus(){
return ($this->status == 1) ? "Sold" : "For Sale" ;
}
}
class Model_listingimages extends Model_Table {
public $entity_code='listing_images';
function init(){
parent::init();
$this->addField('listing_id')->refModel('Model_Listing');
$this->addField('filestore_image_id')->refModel('Model_Filestore_Image');
}
}
In my page manager class I have added the file upload to the crud:
class page_manager extends Page {
function init(){
parent::init();
$tabs=$this->add('Tabs');
$s = $tabs->addTab('Sales')->add('CRUD');
$s->setModel('Listing',array('name','body','status'),array('name','status'));
if ($s->form) {
$f = $s->form;
$f->addField('upload','Add Photos')->setModel('Filestore_Image');
$f->add('FileGrid')->setModel('Filestore_Image');
}
}
}
My questions:
I am getting a "Unable to include FileGrid.php" error - I want the user to be able to see the images that they have uploaded and hoped that this would be the best way to do so - by adding the file grid to bottom of the form. - EDIT - ignore this question, I created a FileGrid class based on the code in the example link below - that fixed the issue.
How do I make the association between the CRUD form so that a submit will save the uploaded files and create entries in the join table?
I have installed the latest release of ATK4, added the 4 filestore tables to the db and referenced the following page in the documentation http://codepad.agiletoolkit.org/image
TIA
PG
By creating model based on Filestore_File
You need to specify a proper model. By proper I mean:
It must be extending Model_Filestore_File
It must have MasterField set to link it with your entry
In this case, however you must know the referenced ID when the images are being uploaded, so it won't work if you upload image before creating record. Just to give you idea the code would look
$mymodel=$this->add('Model_listingimages');
$mymodel->setMasterField('listing_id',$listing_id);
$upload_field->setModel($mymodel);
$upload_field->allowMultiple();
This way all the images uploaded through the field will automatically be associated with your listing. You will need to inherit model from Model_Filestore_File. The Model_Filestore_Image is a really great example which you can use. You should add related entity (join) and define fields in that table.
There is other way too:
By doing some extra work in linking images
When form is submitted, you can retrieve list of file IDs by simply getting them.
$form->get('add_photos')
Inside form submission handler you can perform some manual insertion into listingimages.
$form->onSubmit(function($form) uses($listing_id){
$photos = explode(',',$form->get('add_photos'));
$m=$form->add('Model_listingimages');
foreach($photos as $photo_id){
$m->unloadDdata()->set('listing_id',$listing_id)
->set('filestore_image_id',$photo_id)->update();
}
}); // I'm not sure if this will be called by CRUD, which has
// it's own form submit handler, but give it a try.
You must be careful, through, if you use global model inside the upload field without restrictions, then user can access or delete images uploaded by other users. If you use file model with MVCGrid you should see what files they can theoretically get access to. That's normal and that's why I recommend using the first method described above.
NOTE: you should not use spaces in file name, 2nd argument to addField, it breaks javascript.

Unable to find view for viewmodel?

I'm trying to make a composition UI for a small website.
My building tree looks like this:
Shell (Conductor.Collection.AllActive)
Contains multiple IPod's (you can view them as small widgets)
1 Pod is a PagePod.
This last one is of sort IPodConductor, so a combination of a Screen ( the pagepod ) containing IPage (like MainPage, ContactPage .. )
My whole construction can find all my viewmodels and views following Caliburns convention, but not my MainPage.
The error is as following:
"Cannot find view for Gymsport.Client.Pages.Main.MainPageViewModel"
My structure to the view is as following:
Gymsport.Client.Pages.Main.MainPageView
Following the convention, caliburn should be able to locate my view... but it doens't.
Anybody any tips on to figure out or pointers for debugging this error.
Thanks in advance.
In C.M, there is additional logic for finding Views concerning words like Page, etc. (see here).
So you can either change your views to match the rules in C.M, remove word Page from your view models, or you can enforce custom simple view location with something like that:
ViewLocator.LocateTypeForModelType = (modelType, displayLocation, context) =>
{
var viewTypeName = modelType.FullName.Substring(
0,
modelType.FullName.IndexOf("`") < 0
? modelType.FullName.Length
: modelType.FullName.IndexOf("`")
);
viewTypeName = viewTypeName.Replace("Model", string.Empty);
if (context != null)
{
viewTypeName = Regex.Replace(viewTypeName, "View$", string.Empty);
viewTypeName += "." + context;
}
var viewType = (from assembly in AssemblySource.Instance
from type in assembly.GetExportedTypes()
where type.FullName == viewTypeName
select type).FirstOrDefault();
return viewType;
};

Resources