set value in the droplink field - sitecore

How do I assign values in a droplink through coding?
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item PriceBookHome = master.GetItem("/sitecore/content/Administration/Price Books/Clarisonic-us-retail");
string currency = "INR";
string currenySource = PriceBookHome.Fields["Currency"].Source;
Sitecore.Data.Items.Item currenyDictSource = master.GetItem(currenySource);
foreach (Item im in currenyDictSource.GetChildren())
{
if (im.Fields["Key"].Value == currency)
{
PriceBookHome.Editing.BeginEdit();
PriceBookHome.Fields["Currency"].SetValue(im.DisplayName, true);
PriceBookHome.Editing.EndEdit();
}
}
I am getting the following error on the droplink after insertion: "This field contains a value that is not in the selection list"
Error I am getting as follows:
droplink source[Currency path as given source in droplink]

You need to set the ID of the currency item as value, not the name.
PriceBookHome.Fields["Currency"] = im.ID.ToString();

Most likely it's because you're storing a string (the displayname) in the field.
As Ruud says, you can put the ID in, or do something like this:
PriceBookHome.Editing.BeginEdit();
var field = (Sitecore.Data.Fields.ReferenceField)PriceBookHome.Fields["Currency"];
field.TargetItem = im;
PriceBookHome.Editing.EndEdit();

Related

ASP NET MVC Core 2 with entity framework saving primery key Id to column that isnt a relationship column

Please look at this case:
if (product.ProductId == 0)
{
product.CreateDate = DateTime.UtcNow;
product.EditDate = DateTime.UtcNow;
context.Products.Add(product);
if (!string.IsNullOrEmpty(product.ProductValueProduct)) { SaveProductValueProduct(product); }
}
context.SaveChanges();
When I debug code the ProductId is negative, but afer save the ProductId is corect in database (I know this is normal), but when I want to use it here: SaveProductValueProduct(product) after add to context.Products.Add(product); ProductId behaves strangely. (I'm creating List inside SaveProductValueProduct)
List<ProductValueProductHelper> pvpListToSave = new List<ProductValueProductHelper>();
foreach (var item in dProductValueToSave)
{
ProductValueProductHelper pvp = new ProductValueProductHelper();
pvp.ProductId = (item.Value.HasValue ? item.Value : product.ProductId).GetValueOrDefault();
pvp.ValueId = Convert.ToInt32(item.Key.Remove(item.Key.IndexOf(",")));
pvp.ParentProductId = (item.Value.HasValue ? product.ProductId : item.Value);
pvpListToSave.Add(pvp);
}
I want to use ProductId for relationship. Depends on logic I have to save ProductId at ProductId column OR ProductId at ParentProductId column.
The ProductId 45 save corent at ProductId column (3rd row - this is a relationship), BUT not at ParentProductId (2nd row - this is just null able int column for app logic), although while debug I pass the same negative value from product.ProductId there.
QUESTION:
how can I pass correct ProductId to column that it isn't a relationship column
I just use SaveProductValueProduct(product) after SaveChanges (used SaveChanges twice)
if (product.ProductId == 0)
{
product.CreateDate = DateTime.UtcNow;
product.EditDate = DateTime.UtcNow;
context.Products.Add(product);
}
context.SaveChanges();
if (product.ProductId != 0)
{
if (!string.IsNullOrEmpty(product.ProductValueProduct)) { SaveProductValueProduct(product); }
context.SaveChanges();
}
I set this as an answer because it fixes the matter, but I am very curious if there is any other way to solve this problem. I dont like to use context.SaveChanges(); one after another.

How to update item by Composite Primary Key in Dynamodb

I have a table called friends:
Friend 1 | Friend 2 | Status
Friend 1 is my HASH attribute and Friend 2 is my range attribute.
I would like to update an item's staus attribute where friend 1 = 'Bob' and friend 2 = 'Joe'. Reading through the documentation on http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaDocumentAPICRUDExample.html I can only see how to update an item by 1 key, how do I include the other key?
Here you go:
DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>()
.withKeyConditionExpression("Id = :val1 and ReplyDateTime > :val2")
.withExpressionAttributeValues(
...
where Id is the Hash Key and ReplyDateTime is the Range Key.
Reference:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.QueryScanExample.html
I'm writing example where you can make update of multiple item in single table. I have primary key as id and range key as Datetime.
Actually there is no feature available in dynamodb so what i'm doing here is first query all the variable with hash key and range key of which i want to make update. Once all data are stored in List then loading data with it's hash key and rangekey and changing or updating field using set and save it.
Since I'm editing in hash key so, hash key original will be there we need to delete it. If you need to update in next attribute no need. I haven't added deleting code write yourself. You can query if you have confusion your entry with hash key will be still and new entry with new hash key will be added.
Code is below:
public static void main(String[] args) {
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
DynamoDBMapper mapper = new DynamoDBMapper(client);
client.setEndpoint("http://localhost:8000/");
String fromDate = "2016-01-13";
String toDate = "2016-02-05";
User user = new User();
user.setId("YourHashKey");
LocalDate frmdate = LocalDate.parse(fromDate, DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate todate = LocalDate.parse(toDate, DateTimeFormatter.ISO_LOCAL_DATE);
LocalDateTime startfrm = frmdate.atStartOfDay();
LocalDateTime endto = todate.atTime(23, 59, 59);
Condition rangeCondition = new Condition().withComparisonOperator(ComparisonOperator.BETWEEN.toString()).withAttributeValueList(new AttributeValue().withS(startfrm.toString()), new AttributeValue().withS(endto.toString()));
DynamoDBQueryExpression<User> queryExpression = new DynamoDBQueryExpression<User>().withHashKeyValues(user).withRangeKeyCondition("DATETIME", rangeCondition);
List<User> latestReplies = mapper.query(User.class, queryExpression);
for (User in : latestReplies) {
System.out.println(" Hashid: " + in.getId() + " DateTime: " + in.getDATETIME() + "location:" + in.getLOCID());
User ma = mapper.load(User.class, in.getId(), in.getDATETIME());
ma.setLOCID("Ohelig");
mapper.save(ma);
}
}

Salesforce Apex: List.add( value || 'default value')?

After querying for Account sObjects, I'm adding all the fields into a List. The problem is that some Account sObjects have certain fields and others do not. While adding the fields to my list, I'd like to be able to add field if it exists OR add a default string.
Let's go through the example.
My query:
List<Account> accountQuery = [SELECT name, (SELECT name, id FROM Contacts) FROM Account];
My map:
Map<String, List<String>> Result = new Map<String, List<String>>();
Iterating through the queryResult and saving the values:
For(Account i : accountQuery){
String[] temp = new list<string>();
temp.add(i.name)
//Now loop through contacts subquery
if(!i.contacts.isEmpty()){
for(contact j : i.Contacts){
temp.add(j.name || 'No Contact Name Associated'); //Doesn't work
temp.add(j.id || 'No Contact Id Associated');
}
}
else{
temp.add('No Contact Name Associated');
temp.add('No Contact Id Associated');
}
};
How can I achieve this temp.add(value || 'default value')?
Thank you!
What is the purpose of these manipulation with these strings? What do you need to do? I really can't to imagine any use case for this code and I guess that your task might be completed in more convenient way.
Anyway the answer to your question is using ternary operator - ?:
tmp.add(j.name != null ? j.name : 'No Contact Name Associated');

CF10 new query()

I am creating a query inside a function. Everything works fine until this line:
ulist = new query();
Then I get the error:
Could not find the ColdFusion component or interface query.
Code:
//GET USERS LISTS
remote query function getUserLists(userid) {
//CONFIGURE twitter4j
init();
//DEFINE USER LIST QUERY
var userLists = querynew("id, name, member_count", "Integer, VarChar, Integer");
//GET THE USER LISTS
getLists = t4j.getUserLists(#arguments.userid#);
//BUILD THE USER LIST QUERY
for (i=1;i LTE ArrayLen(getLists);i=i+1) {
newRecord = queryAddRow(userLists);
newRecord = querySetCell(userLists, "id", getLists[i].getId());
newRecord = querySetCell(userLists, "name", getLists[i].getName());
newRecord = querySetCell(userLists, "member_count", getLists[i].getMemberCount());
}
//SORT THE USER LIST BY NAME
ulist = new query();
ulist.setDBType("query");
ulist.setAttributes(sourceQuery=userLists);
ulist.setSQL("select * from sourceQuery order by name");
userListsSorted = ulist.execute().getresult();
//RETURN THE SORTED USER LIST QUERY
return userListsSorted;
}
As per Twitter, make sure you have a custom tag path pointing to [instance]/customtags - which should be there by default. You could use a mapping, pointing to one of the subdirectories within that [instance]/customtags directory, eg: /coldfusion pointing to [instance]\CustomTags\com\adobe\coldfusion, then use:
ulist = new coldfusion.query();
// etc
I'd just use the custom tag directory approach though.
Try using the full path:
ulist = new com.adobe.coldfusion.query()

Showing up the image through code behind

I have a sitecore control like this: <sc:Image ID="imgLogo" runat="server" Field="Image"/>
Now the current item does not have an Image field. I am pulling the Item through droptree in CurrentItem like this (GetFieldValue is same as GetField. I am overriding the base class in Sitecore):
string countryGuid = CurrentItem.GetFieldValue("Country", null);
Item country = sitecoreDatabase.GetItem(countryGuid);
BindCountryLogo();
Now in this Item I have an image for the country logo. All I want to show up on the sc:Image.
So far I got this:
private void BindCountryLogo(Item country)
{
Fields.ImageField logoField = country.Fields["Image"];
if (logoField != null && logoField.MediaItem != null)
{
//Sitecore.Data.Items.MediaItem image = new MediaItem(logoField.MediaItem);
//string src = Sitecore.Resources.Media.MediaManager.GetMediaUrl(image);
//imgLogo.DataSource = src;
//imgLogo.ImageUrl = logoField.MediaItem.Source.;
//string src = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(logoField));
//Sitecore.Data.Items.MediaItem img = new MediaItem(ImageField.Medi)
}
}
None of them are working.
The control has a property "Item" which you can set to the item that holds the imageField.
Your BindCountryLogo should look like this:
private void BindCountryLogo(Item country)
{
imgLogo.Item = country;
}
(Or remove the BindCountryLogo() method and set the Item in the main method ;) )