So I am doing an edit profile feature with Play! Framework (2.2.0);
I have this code
public static Result doEditProfile(){
final User localUser = getLocalUser(session());
Form<User> formData = editProfileForm.bindFromRequest();
if (formData.hasErrors()) {
return badRequest(views.html.editprofile.render(localUser, editProfileForm));
} else {
localUser.firstName = formData.field("firstName").value();
localUser.lastName = formData.field("lastName").value();
localUser.locale = formData.field("locale").value();
localUser.gender = formData.field("gender").value();
localUser.country = formData.field("country").value();
localUser.save();
}
return redirect("/profile/edit");
}
It works. But I want to know is there a better way of doing this ?
I have tried this things:
1)
public static Result doEditProfile(){
final User localUser = getLocalUser(session());
Form<User> formData = editProfileForm.bindFromRequest();
if (formData.hasErrors()) {
return badRequest(views.html.editprofile.render(localUser, editProfileForm));
} else {
User localUser = formData.get();
localUser.save();
}
return redirect("/profile/edit");
}
but this says that variable localUser is already defined.
2) also, I tried this
public static Result doEditProfile(){
final User localUser = getLocalUser(session());
Form<User> formData = editProfileForm.bindFromRequest();
if (formData.hasErrors()) {
return badRequest(views.html.editprofile.render(localUser, editProfileForm));
} else {
User updatedUser = formData.get();
updatedUser.save();
}
return redirect("/profile/edit");
}
but this code is creating a new user in the database.
I am new to Play so I am waiting for any advice. Thanks and sorry for my english
Does your user have a unique id? If so, you could try the following:
updatedUser.setId(localUser.getId())
updatedUser.save()
Saw this example here:
How to update an existing object in playframework 2.0.2? aka CRUD in 1.2.x
... along the lines of what #mantithetical was saying. Better to have an update method in your User class:
public static Result update(Long id) {
Form<User> userForm = form(User.class).bindFromRequest();
if(userForm.hasErrors()) {
return badRequest(editForm.render(id, userForm));
}
userForm.get().update(id);
...
Just a matter of providing the unique id (note that also, we're relying on the id, rather than the entire user, when handling bad requests). You can do that by adding a parameter to your controller in the routes file:
POST /update/:id controllers.doEditProfile(id: Long)
Then when you direct to your controller method, you have to pass that unique id in.
Related
We are integrating WSO2 ESB with Salesforce. We need to insert image into Salesforce Object(Lead). Images are downloaded in some directory. i want to know efficient ideas to complete this task.i have some ideas like
Convert image to Base64 Encoding, then send request to Salesforce APEX.
Insert Image as BLOB into Database,then fetch that BLOB from DB, stores into byte array and finally push that into Salesforce.
But i don't know best and efficient way to do this. If you have some ideas/possibilities kindly share it to me.
Note: For writing Salesforce related task, separate SF Team is here. what i need here is ways/possibilities to achieve this task. Java Class also possible.
Awaiting for your response!!!
You can save it as content version, Now a days Attachments are deprecated.
public with sharing class ContentVersionUtil {
public ContentVersionUtil() {
}
public static Id createDocument(Id parentId, String fileName, String data, Id contentDocumentId) {
ContentVersion versionData = new ContentVersion();
versionData.ContentLocation = 'S';
versionData.ContentDocumentId = contentDocumentId;
versionData.VersionData = Blob.valueOf(data);
versionData.Title = fileName;
versionData.PathOnClient = filename;
insert versionData;
ContentDocumentLink conDocLink = new ContentDocumentLink();
conDocLink.ContentDocumentId = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id = :versionData.Id].ContentDocumentId;
conDocLink.LinkedEntityId = parentId;
conDocLink.ShareType = 'V';
insert conDocLink;
return conDocLink.Id;
}
public static Id createDocument(Id parentId, String fileName, String data) {
return createDocument(parentId, fileName, data, NULL);
}
public static Id createDocumentafterformat(Id parentId, String fileName, String data) {
return createDocument(parentId, fileName, data, NULL);
}
}
Test class:
#isTest
public with sharing class ContentVersionUtilTest {
#TestSetup
static void makeData(){
Account acc = new Account (Name = 'Test Account');
insert acc;
Contact cont = new Contact (LastName = 'Raj', AccountId = acc.Id);
insert cont;
}
#isTest
static void test_content_version_creation_0 () {
Contact eachContact = [SELECT Id from Contact LIMIT 1];
ContentVersionUtil util = new ContentVersionUtil ();
Id conDocLinkId = ContentVersionUtil.createDocument(eachContact.Id, 'testFile', 'csv', 'Some important Data');
System.assertEquals(eachContact.Id, [SELECT Id, LinkedEntityId from ContentDocumentLink WHERE Id =: conDocLinkId].LinkedEntityId);
}
}
How can show when I am logging in for the first time in the storefront - T&C popup in hybris?
For example I am a new customer and I am loggin in store front for the first time, then I will see a popup with some "T&C of use" that I must check to be able to enter the shop.
Maybe I must have some flag whom I say:
private boolean flag = false;
if user is login for first time
flag = false;
if(flag == false){
show me pop up with T&C
flag = true;
}
But how can I get this last login or maybe have another way to do this?
Why not create a boolean flag acceptedTAC on customer type? If someone requests a page on your storefront who has this flag set to null or false, you can show this popup. When the user clicks the accept button, do an AJAX request to your server and set the acceptedTAC flag to true.
This way you even have an "evidence" that a user accepted the TAC. Additionally you can query your database for users who did not yet accept the TAC.
However the usual way you would force the user to accept the TAC would be during registration. A user can only register when he/she accepts the TAC.
Here are the necessary steps:
myextension-items.xml
<itemtype code="Customer" ...>
<attributes>
<attribute name="acceptedTermsAndConditions" type="java.lang.Boolean">
..
</attribute>
<attributes>
</itemtype>
ShowTermsAndConditionsPopupBeforeViewHandler
public class ShowTermsAndConditionsPopupBeforeViewHandler implements BeforeViewHandler {
#Resource
UserService userService;
#Override
public void beforeView(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView) {
UserModel user = userService.getCurrentUser();
if (user instanceof CustomerModel && !userService.isAnonymousUser(user)) {
CustomerModel customer = (CustomerModel) user;
modelAndView.addObject("showTermsAndConditionsPopup", BooleanUtils.isNotTrue(customer.isTermsAndConditionsAccepted()));
} else {
modelAndView.addObject("showTermsAndConditionsPopup", false);
}
}
}
Register BeforeViewHandler in spring-mvc-config.xml
...
<util:list id="defaultBeforeViewHandlersList">
...
<bean class="my.package.ShowTermsAndConditionsPopupBeforeViewHandler"/>
...
</util:list>
...
Create JavaScript Variable in javaScriptVariables.tag
...
ACC.config.showTermsAndConditionsPopup=${showTermsAndConditionsPopup};
...
Add logic to open popup in JavaScript
...
if(ACC.config.showTermsAndConditionsPopup) {
showPopup();
}
...
Create popup content with form:
<c:url var="url" value="/acceptTermsAndConditions" />
<form action="${url}" method="POST">
<label for="acceptTermsAndConditions">I accept Terms and Conditions</label>
<input type="checkbox" id="acceptTermsAndConditions" name="acceptTermsAndConditions" />
<button type="submit>Submit</button>
</form>
Create TermsAndConditionsController
#Controller
public TermsAndConditionsController {
#Resource
private UserService userService;
#Resource
private ModelService modelService;
#RequestMapping(value = "/acceptTermsAndConditions", method = RequestMethod.POST)
#ResponseBody
#ResponseStatus(value = HttpStatus.OK)
public void acceptTermsAndConditions() {
UserModel user = userService.getCurrentUser();
if (user instanceof CustomerModel && !userService.isAnonymousUser(user)) {
CustomerModel customer = (CustomerModel) user;
customer.setAcceptedTermsAndConditions(true);
modelService.save(customer);
}
}
}
If you really want to show T&C popup only once, I would say show it on Registration time.
Let's assume you want to show T&C on each login you can take help of the cookie.
The idea is, after successful login, check for the cookie(let's say "terms"), if not found then show your popup. Now based on user input you can store that cookie.
Just an example.
Source jsfiddle [ http://jsfiddle.net/9q8jmv3L/2/ ]
$(document).ready(function () {
if(${loggedInUser})
{
var visit = getCookie("terms");
if (visit == null) {
x = confirm("Your Message Goes here and you only get to see it once!");
if (x == true)
{
var expire = new Date();
expire = new Date(expire.getTime() + 7776000000);
document.cookie = "terms=here; expires=" + expire;
}
}
}
});
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
} else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
Commnent:
If you really want to keep flag then you can have a new attribute in your customer model. Now check that attribute/flag inJavaScript on success login. If the flag is false show the popup. based on the user's action on the popup, update the flag using ajax call
I'm trying to do a thing in php that I've learnt in Java.
When a user logs in a website a Controller page saves in a private $userLogged var user infos and redirects him in index.php. Now, if he clicks on "profile" I would like that Controller page had in $userLogged his infos still. How I can do it? I've done this:
controller.php
class ECommerce
{
private $checker;
private $errorManager;
private $userLogged;
[...]
function userLogIn($data) {
$user = new User();
$this->userLogged = $user->getByEmail($data["email"]);
if($this->userLogged) {
if($this->userLogged->checkPassword($data["password"])) {
$_SESSION["ec_code"] = $this->userLogged->getCode();
$_SESSION["ec_name"] = $this->userLogged->getName();
$_SESSION["ec_surname"] = $this->userLogged->getSurname();
$_SESSION["ec_email"] = $this->userLogged->getEmail();
$this->redirect("e-commerce/index.php", null);
}
else {
$data["error_message"] = $this->errorManager->getErrorUserLogIn();
$this->redirect("e-commerce/accedi.php?err=1", $data);
}
}
else {
$data["error_message"] = $this->errorManager->getErrorUserLogIn();
$this->redirect("e-commerce/accedi.php?err=1", $data);
}
}
function seeUserProfile() {
$data["try"] = $this->userLogged->getName();
$this->redirect("e-commerce/profilo_utente.php", $data);
}
user_profile.php
<?php
session_start();
session_regenerate_id();
echo $_SESSION["data"]["try"];
what's wrong?
Thank you before!
Uh this is the error message I receive:
Fatal error: Call to a member function getName() on a non-object in /home/mhd-01/HOST_NAME/htdocs/e-commerce/controller/ECommerce.php on line 110
In user_profile.php you need to include the ECommerce class like Liquidchrome mentioned like so:
require('Controller.php');
and then you'll need to create an instance of your ECommerce Class
if you want to pass the same data to user_profile.php page you'll need to instantiate the user_profileclass and pass the instance of the ECommerce class you were using to it.
I am using suggest box for implementing autocomplete in GWT.
For retrieving data from entity i am using objectify and for mapping data to suggest box i have used MultiWordSuggestOracle.
On form load i am firing a query for retrieving data and passing it to MultiWordSuggestOracle. It is working fine.
For eg if i am loading customer data in suggestion it is working
But for eg if i have 5000 - 50000 customer records in my entity, so to retrieve all data and show it in suggestion could not be successful.
So is there any other technique for using autocomplete in gwt?
Thanks in advance
Instead of loading allt he customer records in on form load, dynamically filter the data on the backend based on what the user types into the SuggestBox. You can do this by implementing a custom SuggestOracle (maybe extending the MultiWordSuggestOracle).
public class ServerSuggestOracle extends SuggestOracle{
protected DataSource datasource;
protected int startQueryLength;
protected ArrayList<T> suggestions = new ArrayList<T>();
protected boolean isMoreSuggestions = false;
protected int previousQueryLength = 0;
public ServerSuggestOracle(DataSource datasource,int startQueryLength)
{
super();
this.datasource = datasource;
this.startQueryLength = startQueryLength;
}
#Override
public void requestSuggestions(final Request request, final Callback callback) {
// start the backend call only if the user types in more than startQueryLength characters.
if (request.getQuery().length() < startQueryLength)
return;
// if the user expands the search or a serach hasn't been carried out, call the backend. Otherwise filte the existing list
if (isMoreSuggestions || previousQueryLength > request.getQuery().length() || suggestions.size() == 0)
{
datasource.fetchDataFromBackend(request.getQuery(), new FetchDataFromBackendCallback() {
#Override
public void onFetchData(ArrayList<T> genes,Integer count,boolean isMore) {
suggestions.clear();
for (int i = 0;i<genes.size();i++) {
Suggestion suggestion = new Suggestion();
suggestions.add(suggestion);
}
SuggestOracle.Response response = new SuggestOracle.Response(suggestions);
isMoreSuggestions = isMore;
if (count != null)
response.setMoreSuggestionsCount(count);
else
response.setMoreSuggestions(isMore);
previousQueryLength = request.getQuery().length();
callback.onSuggestionsReady(request,response);
}
});
}
else
{
super.requestSuggestions(request,cabllack);
}
}
}
I have a problem with JPA in play framework 2.1. Here is my situation:
I have action method which handles sign up for my application (User fills email and password and submits the form). In this method I check if the user exists in my database and if not I create new one. Here is simplified code which shows how it works:
public Result signUpSubmit(String email, String password) {
User existingUser = (User) User.find("SELECT u FROM User u WHERE u.email=?", email).get(0);
if (existingUser != null) {
// code which handles existing user
} else {
User newUser = new User(email, password);
Users.persistUserAsync(newUser); // calls JPA.em().persist(newUser) asynchronously
// but I wait until the save is done
// After this call I have new row in DB with newUser (with assigned id)
System.out.println(newUser.id); // prints id which was assigned to new user in DB
User u = (User)JPA.em().find(User.class, newUser.id)
System.out.println(u.id); // throws NullPointer exception, because u is null
}
return renderJapid();
}
Can you tell me the reason why I get the null from the second find query?
public boolean persistUserAsync(User) {
final ModelCreatingJob modelCreatingJob = new ModelCreatingJob(user);
final Promise<Boolean> promisedSave = modelCreatingJob.now();
final Boolean saved = promisedSave.get(20000L);
return saved;
}
The ModelCreatingJob does only this:
return JPA.withTransaction(new F.Function0<Boolean>() {
#Override
public Boolean apply() throws UserLockedException, UserNotFoundException {
return model.validateAndCreate();
}
});
Strange is that when I remove first find (just leave newUser = null) on second find I get valid user object.