In Webcenter Sites how to retrieve values of Page attributes using Template code - webcenter

<assetset:getattributevalues name="sachin" attribute="Date_SV" listvarname="date_sv" typename="Content_Att" />
the above is normally the code to get value of Flex attribute when writing a template code. In fact typename is used for specifying Flex Attribute type.
What is the code for Page attribute? Secondly, what should the "typename" value be to get the value of Page attribute?

Here is an example of use to get a page attribute "article" :
<%
Session ses = SessionFactory.getSession();
AssetDataManager mgr =(AssetDataManager) ses.getManager( AssetDataManager.class.getName() );
AssetId id = new AssetIdImpl( "Page",new Long(ics.GetVar("cid")));
List attrNames = new ArrayList();
attrNames.add( "articles" );
AssetData data = mgr.readAttributes( id, attrNames );
AttributeData articlesData = data.getAttributeData( "articles" );
List<AssetId> relatedArticles = null ;
if (articlesData != null) {
relatedArticles=(List<AssetId>) articlesData.getData();
}
%>
However I don't recommend you to use this method if you are using WCS 12g : it is better to use controllers. The new philosophy is to read all your asset in your groovy controller and then use JSTL to render the values of your asset in your JSP.
Here are some code for the groovy controller :
public Map readAsset(String type, String name) {
Map assetMap = newAssetReader()
.forAssetName(type, name)
.selectAll(true)
.selectImmediateOnlyParents(true)
.includeLinks(true)
.includeLinksForBlobs(true)
.read();
}
Map myPage = readAsset("Page","Home")
models.put("homePage",myPage)
And here is the code in your JSP :
<%# taglib prefix="cs" uri="futuretense_cs/ftcs1_0.tld"%>
<%# taglib prefix="ics" uri="futuretense_cs/ics.tld"%>
<%# taglib prefix="fragment" uri="futuretense_cs/fragment.tld"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<cs:ftcs>
Here is the full page asset : ${homePage} <br/>
Here is just the page name : ${homePage.name} <br/>
</cs:ftcs>
Enjoy the ease of use ...

<assetset:getattributevalues name="sachin" attribute="Date_SV" listvarname="date_sv" typename="PageAttribute"
The typename should be "PageAttribute" without any spaces in between.

Related

Liferay Dynamic Data Lists: How to get image URL?

I am creating a custom template in velocity for a Dynamic Data Lists and I want to get the image URL for the selected image. How can I get it?
The code is:
#set ( $DDLRecordService = $serviceLocator.findService("com.liferay.portlet.dynamicdatalists.service.DDLRecordLocalService") )
#set ( $records = $DDLRecordService.getRecords($mathTool.toNumber($reserved_record_set_id)) )
#foreach ($record in $records)
#set( $fields = $record.getFields() )
#set( $URL = $fields.get("URL").getValue() )
#set( $Link = $fields.get("Linktitle").getValue() )
#set( $Preview = $fields.get("Vorschaubild").getValue() ) ##the image is here
$URL
$Link
$Preview
#end
The $preview output is: {"groupId":"0000000","uuid":"ccdaccec-00a0-4284-a000-589be48‌​99281","version":"1.‌​0"}
Any suggestion?
Itt will work if you replace UUID_HERE to the real UUID.
<a href='${themeDisplay.getPortalURL()}/c/document_library/get_file?uuid=UUID_HERE&groupId=${themeDisplay.getScopeGroupId()}'>MyFile OR Image</a>
I also came across similar situation and after searching on the internet for hour(s), didn't find any useful information apart from LPS-34792 ticket.
Well, you can render image on the UI from a Documents and Media field using:
<#assign hasPicture = cur_record.getFieldValue("picture")?has_content>
<#if hasPicture>
<#assign picture = jsonFactoryUtil.createJSONObject(cur_record.getFieldValue("picture"))>
<img src='/documents/${picture.getString("groupId")}/${picture.getString("uuid")}' />
</#if>
Where picture is the name of field and hasPicture will check if the image was selected.

Select a default value in dropdownlistfor MVC 4

I'm trying to make a dropdownlistfor with a selected value but it doesn't work :/ And I search on the web but I don't find the solution :/
For the moment, I'm doing this :
In C# :
ViewBag.ID_VEH = new SelectList(db.VEHI, "ID_VEH", "COD_VEH", 4); // 4 is an example
In my cshtml :
#Html.DropDownListFor(model => model.ID_VEH, ViewBag.ID_VEH as SelectList)
The dropdownlist is well complete but the default value is not selected :/ do you have an idea please ?
What I like to do is add a list of the items to display in the dropdownlist to my model, so I don't have to pass that list via a viewbag.
Also i like to add a field to my model that contains the SelectedValue, that I fill in the controller
Then you can do
#Html.DropDownListFor(model => model.ID_VEH, new SelectList(Model.listVEH, "ID_VEH", "COD_VEH", Model.SelectedVEH_ID), "--Select VEH--")
just set the initial value of model.ID_VEH to 4:
In the controller:
model.ID_VEH = 4;
Just in case someone has similar problems finding the answer:
I want to have view with the dropdown boxes have focus on the items i give (hardcoded) in the controller:
Controller:
SGLDataRegistration.Models.DataRegistrationModel mdl = rwd.GetData(DateTime.Now.Year, currentWeek, DateTime.Now, 139, 1);
View:
<div id="tempCustomerselect">
#Html.LabelFor(m => m.CustomerName)
#Html.DropDownListFor(m => m.PitchID, new SelectList((new SGLDataRegistration.Models.CustomerModel().GetRoles()).OrderBy(x => x.CustomerName), "PitchID", "CustomerName"), new {id = "ddlCustomer", #class="jsddlCustomer"})
</div>
In this GetData, i setthe desired values hardcoded:
public SGLDataRegistration.Models.DataRegistrationModel GetData(int year, int weekNumber, DateTime datum, int pitchID, int parameter)
{
try
{
DataRegistrationParameters drp = GetParameter(parameter);
//vul een instantie van het dataregistrationmodel
SGLDataRegistration.Models.DataRegistrationModel drm = new Models.DataRegistrationModel();
drm.WeekNumber = weekNumber;
drm.BeginDay = datum;
drm.Parameter = parameter;
drm.Year = year;
drm.PitchID = pitchID;

Get title, nav_title and subtitle

I want to print the fields title, nav_title and subtitle with Typoscript. I saw that there are several possibilities. E.g. data, field, levelfield, leveltitle, ...
Currently I'm using this code (because the only one which works for me so far):
lib.heading = TEXT
lib.heading.dataWrap = <p class="title"> {leveltitle:0} </p>
but I want something with alternatives like this
stdWrap.field = subtitle // nav_title // title
What is the correct way of retrieving these fields?
Edit:
[userFunc = user_isMobile]
page.headerData.10 = TEXT
page.headerData.10.value (
// ...
)
// ...
lib.heading = TEXT
#lib.heading.dataWrap = <p class="title"> {leveltitle:0} </p>
lib.heading {
field = title
wrap = <p class="title"> | </p>
}
lib.subpages = HMENU
lib.subpages {
// ...
}
[global]
The userfunction itself is a function in a php script (user_mobile.php). It makes a user agent detection for mobile devices and returns true or false.
field will get values from the current data which in your context is the data of the current page.
lib.heading = TEXT
lib.heading {
field = subtitle // nav_title // title
wrap = <p class="title">|</p>
}
leveltitle, leveluid, levelmedia, etc. allow you to retrieve some of the data from other pages in the rootline of the current page.
For more information see getText in the documentation.

Filtering results based on a distinct column or field value

I have an MVC 3 application running against an MS SQL 2008 database with a table named Documents. Documents are broken down by paragraph in the database. The Documents table has a DocText column containing the text of each paragraph, a DocTitle column containing the document title. My MVC 3 app has a search function that can search for a word or phrase in the DocText column or in the DocTitle column. Everything works fine except that if a particular document has the search word appearing in multiple paragraphs, my List returns multiple instances of that document. For example, if the user searches the word "Budget" and one of THE documents has the word "budget" in four different paragraphs, my returned list has that document listed four times.
What I want to achieve is to list each document that has the searched word. I only want to list the document by Title once, regardless of the number of times the search word appears in that document. The only column that is truly unique is the RecordID column, a primary key.
My controller:
public class SearchController : Controller
{
private GUICEEntities4 db = new GUICEEntities4();
//
// GET: /Search/
public ActionResult Index(string Keyword)
{
#region Keyword Search
if (!String.IsNullOrEmpty(Keyword)) {
var SearchDoc = db.Documents.Where(r => r.DocText.ToUpper().Contains(Keyword.ToUpper()) || r.Title.ToUpper().Contains(Keyword.ToUpper()) || r.DocNum.ToUpper().Contains(Keyword.ToUpper()));
ViewBag.CurrentKeyword = String.IsNullOrEmpty(Keyword) ? "" : Keyword;
return View(SearchDoc.ToList());
}
else{
return View();
}
#endregion
}
}
My View has the following:
#foreach (var item in Model) {
<tr>
<td>
<strong>AFI #Html.DisplayFor(modelItem => item.DocNum): #Html.DisplayFor(modelItem => item.Title)</strong>
<br />
#Html.DisplayFor(modelItem => item.DocSummary)
<br />
<span class="complianceitems">Number of compliance items:</span> (TBD)
</td>
<td>
<a href="/Documents/Index/#(Html.DisplayFor(modelItem => item.DocNum))">Checklist
Generator</a><br />
<a href="/UploadedDocs/#Html.DisplayFor(modelItem => item.DocFileName)" target="_blank">
Download PDF</a>
</td>
Any suggestions on how I can achieve my goal?
ADDED: Each document can be identified by the DocNum column which has a unique document number for that particular document. I've tried to iterate through the List to pull out each unqiue DocNum and then try to make that DocNum not appear again in the loop...but I was not successful.
The following SQL statement gives me the results I need. The statement assumes that the search word is "budget". I don't know how to get the same results using EF. Any suggestions?
SELECT DISTINCT DocNum, Title FROM Documents
WHERE
DocText LIKE '%budget%'
OR
Documents.Title LIKE '%budget%'
OR
DocNum LIKE '%budget%'
The issue here is in your EF query and not anything related to MVC. It's been a while since I've actively used EF but the simplest way would probably be to return just the RecordIds first.
var recordIds= db.Documents
.Where(r =>
r.DocText.ToUpper().Contains(Keyword.ToUpper()) ||
r.Title.ToUpper().Contains(Keyword.ToUpper()) ||
r.DocNum.ToUpper().Contains(Keyword.ToUpper()))
.Select(d => d.RecordId)
.Distinct();
I'm not exactly sure what you will do with each individual record from then on as there isn't enough information in your question. But this should help.
Update:
var foundDocs = new List<YourType>();
recordIds.ToList().ForEach(r => foundDocs.Add(db.TblDocLists.Single(l => l.TheDocNum == r)));
//I must point out that I'm not familiar with the latest versions of EF so this might be overkill.

Sql/c# Error: Cannot insert explicit value for identity column when IDENTITY_INSERT is set to off

I have a web application which is giving me the following exception:
InnerException {"Cannot insert
explicit value for identity column in
table 'Cover' when IDENTITY_INSERT is
set to OFF."} System.Exception
{System.Data.SqlClient.SqlException}
I'm trying to insert into a database which looks like the following:
dbo.File
FileID int PK
Title nvarchar(50)
ISBN nvarchar(50)
UploadDate datetime
UserName nvarchar(50)
dbo.Cover
CoverID int PK
CoverFileContent varbinary(max)
CoverMimeType nvarchar(50)
CoverFileName nvarchar(50)
FileID int FK
dbo.Cover
CoverID int PK
CoverFileContent varbinary(max)
CoverMimeType nvarchar(50)
CoverFileName nvarchar(50)
FileID int FK
In this database the File table has a one to many relationship with both the Cover, and the Pdf table. In my application, the user first enters a description of the file, and this updates the file table, then they upload a picture associated with the file which updates the Cover table, and then they upload a PDF file (I have not got this far yet).
Right now, my MVC c# code looks like the following:
FileController
//
//GET: /File/CreateFile
public ActionResult CreateFile()
{
File file = new File();
return View(file);
}
//
//POST: /File/CreateFile
[HttpPost]
public ActionResult CreateFile(FormCollection formvalues)
{
File file = new File();
if (TryUpdateModel(file))
{
filerepository.AddFileData(file);
filerepository.Save();
return RedirectToAction("CreateCover", "Cover", new { id = file.FileID });
}
return View(file);
}
Cover Controller
//
//GET: /File/CreateCover
public ActionResult CreateCover(int id)
{
Cover cover = new Cover();
cover.FileID = id;
return View(cover);
}
//
//POST: /File/CreateCover
[HttpPost]
public ActionResult CreateCover(Cover cover)
{
cover.CoverMimeType = Request.Files["CoverUpload"].ContentType;
Stream fileStream = Request.Files["CoverUpload"].InputStream;
cover.CoverFileName = Path.GetFileName(Request.Files["CoverUpload"].FileName);
int fileLength = Request.Files["CoverUpload"].ContentLength;
cover.CoverFileContent = new byte[fileLength];
fileStream.Read(cover.CoverFileContent, 0, fileLength);
cover.FileID = int.Parse(Request.Form["FileID"]);
filerepository.AddCoverData(cover);
filerepository.Save();
return View(cover);
//return View("CreatePdf", "Pdf", new { id = cover.FileID });
}
CreateCover View
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SampleApp.Models.Cover>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
CreateCover
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
runat="server">
<h2>CreateCover</h2>
<% using (Html.BeginForm("CreateCover", "Cover", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>
<%: Html.HiddenFor(model => model.FileID) %>
<asp:Label ID="Label2" runat="server" Text="Please Select your eBook Cover" /><br />
<input type="file" name="CoverUpload" /><br />
<input type="submit" name="submit" id="Submit" value="Upload" />
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
I was able to upload a cover once, however ever since then I've been getting this error. I noticed that in my table I had forgotten to set the PK column as IDENTITY (1, 1), however I changed this and am still getting the error.
I also don't know if it's worth mentioning, but in my database for the one image I was able to upload, the binary content in the database is pretty much "0x00000...."...This seems wrong? :)
Any help or advice would be appreciated, thanks!
Solved this issue for anyone else who is having the same problem. Simply refreshed the model in Visual Studio and it seems to have done the trick.