Attaching file in a web form portlet - liferay

I am trying to add a field in web form portlet of liferay to upload a file. Currently I am able to add this field in my form but unable to get the attached file on server/ mentioned location. I am getting a null pointer exception. Below are the changes I have done in 4 files of web form portlet.
edit_field.jsp
<aui:option selected='<%= fieldType.equals("file") %>' value="file">
<liferay-ui:message key="file" /></aui:option>
view.jsp
<c:when test='<%= fieldType.equals("file") %>'>
<tr>
<td class="order-table-label">
<label><%= HtmlUtil.escape(fieldLabel) %></label>
</td>
<td>
<aui:input cssClass='<%= fieldOptional ? "optional" : StringPool.BLANK
%>' label="" name="<%= fieldName %>" type="file" value="
<%=HtmlUtil.escape(fieldValue) %>"/>
</td>
</tr>
</c:when>
ConfigurationActionImpl.java
boolean isFileUpload = false;
if("file".equals(fieldType))
{
isFileUpload = true;
}
preferences.setValue("isFileUpload" + i, String.valueOf(isFileUpload));
WebFormPortlet.java
UploadPortletRequest uploadRequest =
Portalutil.getUploadPortletRequest(actionRequest);
File uploadedFile = uploadRequest.getFile("file");
String sourcefileName = uploadRequest.getFileName(uploadedFile.getName());
(Throws NULL pointer exception on this line)
File folder = new File("\tmp\uploadedfile");
File filepath = new File(folder.getAbsolutePath() + File.seperator +
sourcefileName);
FileUtils.copyFile(uploadedFile ,filepath);

I would store the file in the document library instead of the tmp path, wich is actually complettly out of scope from the portal itself.
do you need the mailing feature of the portlet ? i don't think that your customizations will work with this use-case
looks like the npe states that there is no file in the request, or not with that name, have you already looked into that request ?

Related

How can I hide whmcs buttons?

Hi I hope someone can help on the client details page I need to hide the Email forwarding button and the DNS management button if the client has selected custom nameservers. I just can't work it out son any help is much welcomed ..Here is the code that takes the input;
<form method="post" action="{$smarty.server.PHP_SELF}?action=domaindetails">
<input type="hidden" name="sub" value="savens">
<input type="hidden" name="id" value="{$domainid}">
<p><input type="radio" name="nschoice" value="default" id="nschoicedefault" onclick="usedefaultns()"{if $defaultns} checked{/if} /> <label for="nschoicedefault">{$LANG.nschoicedefault}</label><br />
<input type="radio" name="nschoice" value="custom" id="nschoicecustom" onclick="usecustomns()"{if !$defaultns} checked{/if} /> <label for="nschoicecustom">{$LANG.nschoicecustom}</label></p>
And here is the code for the buttons;
{if $emailforwarding}
<td><form method="post" action="{$smarty.server.PHP_SELF}?action=domainemailforwarding">
<input type="hidden" name="domainid" value="{$domainid}">
<p align="center">
<input type="submit" value="{$LANG.domainemailforwarding}" class="button">}
</p>
</form></td>
{/if}
{if $dnsmanagement}
<td><form method="post" action="{$smarty.server.PHP_SELF}?action=domaindns">
<input type="hidden" name="domainid" value="{$domainid}">
<p align="center">
{<input type="submit" value="{$LANG.domaindnsmanagement}" class="button">}
</p>
</form></td>
{/if}
I suggest writing a helper function and calling it at the top of the tpl file
and passing the domain id to it.
You can then use the WHMCS internal API function Domain Nameservers to get the domains nameservers then compare them against the default nameservers in the tblconfiguration in the WHMCS database.
Something like this
{php}
// include our helper php file
require_once(dirname(__FILE__).'/Helper.php');
//get domain id from our template variables
$domainid = $this->get_template_vars('domainid');
//call to our helper function passing the domain ID
$hasCustomeNameServers = Helper::hasCustomNameServers($domainid);
//Once we've compared the nameservers agains the default ones we write
//our binary check to the template
if($hasCustomeNameServers >0){
$this->assign('hasCustomeNameServers',true);}
{/php}
Then in side our Helper.php we have something like the following
<?php
class Helper {
public static function hasCustomNameServers($domainid) {
$isCustom = 0;
//Interal API call to get the domains nameservers
$command = "domaingetnameservers";
$adminuser = "admin";
$values["domainid"] = $domainid;
$results = localAPI($command,$values,$adminuser);
//get default nameservers
$defautName1 ='';
$sql = mysql_query('SELECT value FROM tblconfiguration '.
' WHERE setting = "DefaultNameserver1"');
if ($res = mysql_fetch_assoc($sql)) {
$defautName1 = $res["value"];}
$defautName2 ='';
$sql = mysql_query('SELECT value FROM tblconfiguration '.
' WHERE setting = "DefaultNameserver2"');
if ($res = mysql_fetch_assoc($sql)) {
$defautName2 = $res["value"];}
//compare results
foreach ($results as &$value) {
if($value == $defautName1 || $value == $defautName2){
$isCustom++;
}
}
return $isCustom;
}
}
Now it's simply a matter on the template to wrap the {if $emailforwarding} and the {if $dnsmanagement} blocks around our check {if !hasCustomeNameServers}
I hope this helps you in the right direction this is by no means a comprehensive answer but is a guide towards the approach I think you should take in implementing your solution.

Search on specific Liferay private page

For search i use liferay-ui:search in the dockbar. User should be able to define search scope (specific private page) by choosing it from dropdown list.
How can i implement search on specific private page?
And 1 more question. Seems it's a bug, but user is able to search only while he is on specific private page. If he move to another page - search button is "disabled" - nothing happens when he clic it. For admin account everything works fine - i am able to search being on any page.
Thanks!
OK. 1st step was to place hook on [b]html/taglib/search/start.jsp[/b]. I passed an extra id parameter to define on which private page i gonna search.
<input name="<%= namespace %>keywords" size="30" title="<liferay-ui:message key="search" />" type="text" value="<%= HtmlUtil.escapeAttribute(keywords) %>" />
<input name="<%= namespace %>groupid" value="0" type="hidden" />
<select name="<%= namespace %>scopeId" title="<liferay-ui:message key="scope" /> ">
<option value="0" <%= selected == 0 ? "selected" : ""%>><liferay-ui:message key="everything" /></option>
<option value="1" <%= selected == 1 ? "selected" : ""%>>Новости</option>
<option value="2" <%= selected == 2 ? "selected" : ""%>>Сотрудники</option>
<option value="3" <%= selected == 3 ? "selected" : ""%>>Новому сотруднику</option>
<option value="4" <%= selected == 4 ? "selected" : ""%>>Корпоративные правила</option>
<option value="5" <%= selected == 5 ? "selected" : ""%>>Продукты</option>
<option value="6" <%= selected == 6 ? "selected" : ""%>>Wiki</option>
<option value="7" <%= selected == 7 ? "selected" : ""%>>События</option>
<option value="8" <%= selected == 8 ? "selected" : ""%>>Форум</option>
</select>
2nd step was to hook on [b]html/portlet/search/main_search.jsp[/b]. There i was going to filter [b]ALL[/b] search results and display only those which needed by request from [b]select field[/b]. It's OK for non instanceble custom portlets with have different id, i just filter by portletId and display result.
Hits hits = indexer.search(searchContext);
List<Document> documents = new ArrayList<Document>();
documents = hits.toList();
...
if (documents.size() != 0) {
List<Document> toDelete = new ArrayList<Document>();
for (Document document : documents) {
String id = document.getPortletId();
id = document.get(Field.PORTLET_ID);
switch (scopeId) {
case 0:
break;
case 1:
if (!id.equals(NEWS_PORTLET_ID)) {
toDelete.add(document);
}
break;
....
if (toDelete.size() != 0) {
documents.removeAll(toDelete);
hits.setDocs(documents.toArray(new Document[documents.size()]));
if (documents.size() == 0) {
hits.setLength(0);
}
}
All fine. But 3 of my pages all have asset publisher portlet (portletId = 15), so if i filter by portlet id - i will get results from all 3 pages. Maybe i can get instance id of portlet which document belongs to. Or maybe there is some other way to do search.
Atm i try to implement my CustomJournalArticleIndexer. The idea is Indexer adds field containing portlet's instance id. So later in main_search.jsp i can do something like document.getPortletInstanceId and compare it with a constant paired with scopeId of my request.
Any suggestions here?
Thanks and... from Russia with love!

MODX - user profile photo upload

I am trying to allow users to upload photos to their profiles. I am sure I am doing something wrong...
What I currently have configured:
Update Profile Form
[[!UpdateProfile? &useExtended=`1` &preHooks=`user_profile_image` &postHooks=`redirect_profile_update`]]
<div class="update-profile">
<div class="updprof-error">[[+error.message]]</div>
[[+login.update_success:if=`[[+login.update_success]]`:is=`1`:then=`[[%login.profile_updated? &namespace=`login` &topic=`updateprofile`]]`]]
<form class="form" enctype="multipart/form-data" action="[[~[[*id]]]]" method="post">
<input type="hidden" name="nospam:blank" value="" />
<label for="fullname"><i class="icon-user"></i> <strong>[[!%login.fullname? &namespace=`login` &topic=`updateprofile`]]</strong>
<span class="error">[[+error.fullname]]</span>
</label>
<input type="text" name="fullname" id="fullname" value="[[+fullname]]" />
<label for="email"><i class="icon-envelope"></i> <strong>[[!%login.email]]</strong>
<span class="error">[[+error.email]]</span>
</label>
<input type="text" name="email:required:email" id="email" value="[[+email]]" />
<label for="test_field">Test Field
<span class="error">[[+error.custom_field]]</span>
</label>
<input type="text" name="test_field" id="test_field" value="[[+test_field]]" /><br/>
<div class="row clearfix">
<div class="label">Photo<span class="error">[[+fi.error.nomination_file]]</span></div>
<div class="input"><input id="nomination_file" name="nomination_file:required" type="file" value="[[+fi.nomination_file]]" maxlength="100000" /></div>
</div>
<br class="clear" />
<button class="btn-info btn btn-large" type="submit" name="login-updprof-btn">Update Profile</button>
</form>
</div>
User_profile_image snippet
<?php
// initialize output;
$output = true;
// get the current user name to create the file name as
$userName = $modx->user->get('username');
// valid extensions
$ext_array = array(`jpg', 'jpeg', 'gif', 'png');
// create unique path for this form submission
$uploadpath = 'assets/uploads/';
// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.
// EXAMPLE:
// this would put all file uploads into a new,
// unique folder every day.
// $uploadpath = 'assets/'uploads/'.date('Y-m-d').'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );
// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive
// is the file name empty (no file uploaded)
if($filename != '') {
// is this the right type of file?
if(in_array($ext, $ext_array)) {
//create file called the user name + pic
$filename = $userName . "pic".'.'.$ext ;
// full path to new file
$myTarget = $target_path . $filename;
// create directory to move file into if it doesn't exist
mkdir($target_path, 0755, true);
// is the file moved to the proper folder successfully?
if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
// set a new placeholder with the new full path (if you need it in subsequent hooks)
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
// set the permissions on the file
if (!chmod($myTarget, 0644)) { /*some debug function*/ }
} else {
// File not uploaded
$errorMsg = 'There was a problem uploading the file.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
} else {
// File type not allowed
$errorMsg = 'Type of file not allowed.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
// if no file, don't error, but return blank
} else {
$hook->setValue($sf, '');
}
}
return $output;
1) fix quote in this line
$ext_array = array(`jpg', 'jpeg', 'gif', 'png');
2) remove all :required in name fields.
3) instead
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
type
$hook->setValue($sf, $uploadpath . $filename);
4) after mkdir($target_path, 0755, true); add
if(file_exists($myTarget) {
chmod($myTarget,0755); //Change the file permissions if allowed
unlink($myTarget); //remove the file
}
For anyone who references this post:
move user_profile_image back to the prehooks like this:
&preHooks=`user_profile_image`
and at line 59 add the missing ")" like this:
if(file_exists($myTarget)) {

c# fill something on html page

how can I fill "MyUserName" on
<td width="18%" class="more"><div align="right">¿¿¿¿¿¿ </div></td>
<td width="82%">
<font color="#FFFFFF" face="MS Sans Serif, Tahoma, sans-serif">
<input type=text name="QTitle" size=51 maxlength=100 class=violet>
</font>
</td>
i try in c# but it not work please help
private void webBrowser2_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
}
private void LoadProfileInformation()
{
DataSet dsNew = new DataSet();
//Some code to fetch information if you store it in a DB
//else you can put in static info if you may want.
//so you will nto need the dataset.
QTitle.Text = "MyUserName";
}
You can store it in the class then access it with code behinds like <%= myVar %> in your front end.
if you want to modify the values of divs on the front end then you need to use asp tags like
<asp:label runat="server" name="Qtitle"> </asp:label>
First of all you really need to think about moving to newer versions of XHTML/HTML! (I suggest you that because of your markup code).
In the other hand, in order to get your "QTitle" text set from server, you'll need to set "runat" attribute to "server" in your input, but, if you're using standard (X)HTML elements, you won't have such property "Text".
I suggest you to use a server control like TextBox which has the whole "Text" property:
<asp:TextBox ID="QTitle" runat="server" CssClass="Violet" />
Some server code-behind:
QTitle.Text = "Hello world";
Another suggestion is you won't be setting any property after PreRender ASP.NET Page life-cycle event.
Is the mark-up at the top of your question the resulting html or the source code for the form you are working with? If this is in-fact your asp.net form, try replacing the input tag with the following...
<asp:TextBox id="QTitle" runat="server" />
If the form is properly linked to the C# codebehind file you are using, QTitle.Text should now be accessible.

ASP.NET MVC - What is the best way to build a search form that works properly with SEO and users without JS?

I'm working on building a search engine in my application, and because I don't want to have a Querystring in my URL, I'm currently using Javascript to submit the searchTerms for me.
Basically I am NOT using a "form", but rather just an input
<input id="searchBox" class="search" name="searchTerm" tabindex="1" onfocus=" this.className = 'search-alt'; if (this.value=='search...') this.value = ''" type="text" onkeypress="searchKeyPress(event,this.form)" maxlength="80" size="28" value="search...">
<script type="text/javascript">
function searchKeyPress(e, form) {
var key = e.keyCode || e.which;
if (key == 13) {window.location.href = '<%: url.Content("~/search") %>/' + $('#searchBox').val();}}
</script>
The problem with this method is "two fold"
If the user doesn't have Javascript, the form will not submit
I'm not sure if a search engine will be able to use this search form either
So my question is
Can I use a Form element on my page that can submit " http://example.com/search/{searchTerms} " instead of " http://example.com/search/?q={searchTerms} " while NOT using Javascript?
I'm using ASP.NET MVC 2
Ok, I think I've found my solution. Basically I am using RedirectToAction if there is a querystring item.
View
<form action="/search/" id="searchForm" method="get">
<input id="searchBox" class="search-gray" name="searchTerms" tabindex="1" onblur=" if (this.value==''){this.value = 'search...'; this.className = 'search-gray'}" onfocus=" this.className = ''; if (this.value=='search...') {this.value = ''}" type="text" maxlength="80" size="28" value="search...">
</form>
Controller
Function Index(Optional ByVal searchTerms As String = "") As ActionResult
If Not Request.QueryString("searchTerms") = "" Then
Return RedirectToAction("Index", "Search", New With {.searchTerms = searchTerms})
End If
ViewData("searchTerms") = searchTerms
Return View()
End Function
No more javascript.

Resources