CRM 2013 refresh subgrid with fetchxml - fetchxml

In my scenario, i have a new entity called "new_relations" with 2 fields (account1 and account2) that are both lookups to accounts.
In my accounts form i want to display a grid containing any record with the current account, in any of the 2 lookups, that exists in "new_relations" entity.
I´ve created account A and account B; created 1 record in new_relations with new_relations.account1 = account A and new_relations.account2 = account B.
So, when i open account A or Account B i want to see the record created in new_relations.
I have the following code, unfortunately its only showing the record in Account´s A form in my subgrid...
Can anyone help?
function FilterRelacao(){
var relacoes = document.getElementById("Relacoes");
var account = Xrm.Page.data.entity.getId();
var accountname = Xrm.Page.data.entity.attributes.get("name").getValue();
if(relacoes==null){
setTimeout(function () { FilterRelacao(); }, 2000);
return;
}
var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
"<entity name='new_relations'>" +
"<attribute name='new_type' />" +
"<attribute name='new_accountid1' />" +
"<attribute name='new_accountid2' />" +
"<attribute name='new_relationsid' />" +
"<order attribute='new_accountid1' descending='true' />" +
"<filter type='and'>" +
"<condition attribute='statecode' operator='eq' value='0' />" +
"<filter type='or'>" +
"<condition attribute='new_accountid1' operator='eq' uitype='account' uiname='" + accountname+ "' value='" + account + "' />" +
"<condition attribute='new_accountid2' operator='eq' uitype='account' uiname='" + accountname + "' value='" + account + "' />" +
"</filter></filter>" +
"</entity>" +
"</fetch>";
relacoes.control.SetParameter("fetchXml", fetchXml); //set the fetch xml to the sub grid
relacoes.control.SetParameter("effectiveFetchXml", fetchXml); //set the fetch xml to the sub grid
relacoes.control.Refresh(); //refresh the sub grid using the new fetch xml
}

Your fetch XML looks correct to me. When you set up the subgrid did you set "Records" = "All Record Types" in the Data Source section? If you did not then the subgrid will append a condition to your fetchxml so that it returns only records related to the specific relationship that you specified.

Related

React Native - undefined is not an object(evaluating '_ref2.label')

I am using DropDownPicker in React-Native. I want DropDownPicker to be loaded by default for example first index. I want the 1st item of this.state.allAdresses Array to be loaded as defaultValue. But I am getting the error in the thread. What is the reason?
DropDownPicker
style = {{marginTop:10}}
items={this.state.allAdresses.map((item, index)=> ({label:item.firstname + " " + item.lastname + " " + item.address_1 + " " + item.address_2 + " " + item.city + " " + item.company + " " + item.postcode ,value:item.lastname, key: index}))}
placeholder="Adres seçiniz"
containerStyle={{height: 40, width:'100%',}}
defaultValue={this.state.allAdresses[1]}
onChangeItem={(itemValue, itemIndex) => this.changeAddress(itemIndex)}
/>
This is because you are referencing this.state.allAdresses[1] in defaultValue while defaultValue must be the value of the object you are trying to display as selected.
Here is one way to fix it
//Create an array from allAdresses you want to populate dropdownpicker with.
const items = this.state.allAdresses.map((item, index)=> ({label:item.firstname + " " +
item.lastname + " " + item.address_1 + " " + item.address_2 + " " + item.city + " " + item.company + " " +
item.postcode ,value:item.lastname, key: index}))
<DropDownPicker
style={{marginTop:10}}
//reference it like this
items={items}
placeholder="Adres seçiniz"
containerStyle={{height: 40, width:'100%',}}
//set 1 index
defaultValue={items[1].value}
onChangeItem={(itemValue, itemIndex) => this.changeAddress(itemIndex)}
/>

Create a log note in a record through controller

I created a record of crm.lead model through controller, and I also want to upload image or file in log note.
class RequestForQuote(http.Controller):
#route('/form/sinsert', type="http", auth="public", website=True, csrf=True)
def qoute_application_process(self,**kwargs):
values = {}
for field_name, field_value in kwargs.items():
values[field_name] = field_value
internal_notes = values['comment'] + ' , ' +values['commercial_company_name'] + ", " +values['contact_address']+ ' ' +values['contact_city'] +' '+ \
values['contact_state'] +' '+values['zip'] + ', '+ values['meeting_ids']
name = values['first_name'] +' '+values['last_name']
opportunity = request.env['crm.lead'].sudo().create({'name': name ,'date_deadline':values['date'],'email_from':values['email'],
'description':internal_notes,'type':'opportunity'
})
return werkzeug.utils.redirect('/form/thankyou')
enter image description here
To create an internal note, you just need to call self.message_post:
self.message_post(body="Internal note", attachments=[('Image', self.partner_id.image)])
You can read more at mail.thread

SQL statement check for concatenated value and return statement if not found

I am trying to search a two column table with a CustomerID and a ServID. The primary key is the combination of both. I want the query to search if the combination is there. If it is return something I can use in c# to cancel the input or if it is not found have it insert the record. This is as far as I have made it after hours of searching.
IF (SELECT * FROM Cus_Ser WHERE customerID=inputnumber AND ServID=inputnumber) IS NULL
PRINT 'Already Exists'
ELSE
INSERT INTO Cus_Ser(CustomerID,ServID) VALUES(inputnumber, inputnumber)
Here is the code
#using WebMatrix.Data
#{
var CustomerID = Request.QueryString["CustomerID"];
var ServID = 0;
var db = Database.Open("Azure");
var selectedData = db.Query("SELECT * FROM Customer INNER JOIN Cus_Ser ON Customer.customerID=Cus_Ser.customerID INNER JOIN Service ON Cus_Ser.ServID=Service.ServID WHERE customer.CustomerID =" + CustomerID);
var grid = new WebGrid(source: selectedData);
var selectedData2 = db.Query("SELECT * FROM Service");
var grid2 = new WebGrid(source: selectedData2);
if (IsPost)
{ if (int.TryParse(Request.Form["ServID"], out int numbertest))
{
ServID = Int32.Parse(Request.Form["ServID"]);
var dbCommandSearch = "SELECT * FROM Cus_Ser WHERE customerID=" + CustomerID + " AND ServID=" + ServID;
//search = db.QuerySingle(dbCommandSearch);
//if ((CustomerID, "ServID") != search
db = Database.Open("Azure");
var insertCommand = "INSERT INTO cus_ser (customerID,ServID)VALUES(" + CustomerID + ", " + ServID + ")";
db.Execute(insertCommand);
Response.Redirect("~/ViewService?CustomerID=" + CustomerID);
}
//else
//{
//Validation.AddFormError("Entered Value is Not a Service Numberr");
//}
else
{
Validation.AddFormError("Entered Value is NOT a Service Number");
}
} }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Add Service</title>
<style>
.validation-summary-errors {
border: 2px dashed red;
color: red;
font-weight: bold;
margin: 12px;
}
</style>
</head>
<body>
<form method="post">
<fieldset>
<legend>Input Service To Add</legend>
<p>
<label for="ServID">Service ID:</label>
<input type="text" name="ServID" value="#ServID" />
</p>
<input type="hidden" name="CustomerID" value="#CustomerID" />
<p><input type="submit" name="buttonSubmit" value="Submit Changes" /></p>
</fieldset>
</form>
<p>Return to customer listing</p>
Multiple Inline SQL Statements
Your sample code seems to be very close. The QuerySingle method will return null if no matches are found. Thus you can check for a null value before issuing the insert statement, with something like:
ServID = Int32.Parse(Request.Form["ServID"]);
var dbCommandSearch = "SELECT * FROM Cus_Ser WHERE customerID=" + CustomerID + " AND ServID=" + ServID;
search = db.QuerySingle(dbCommandSearch);
if (search == null) { // record does not already exist
var insertCommand = "INSERT INTO cus_ser (customerID,ServID)VALUES(" + CustomerID + ", " + ServID + ")";
db.Execute(insertCommand);
Response.Redirect("~/ViewService?CustomerID=" + CustomerID);
}
else
{
Validation.AddFormError("Entered Value is Not a Service Numberr");
}
Single SQL Statement
You can combine this all into one big SQL statement, something like:
var sql = #"IF EXISTS (SELECT 1 FROM Cus_Ser WHERE customerID=#0 AND ServID=#1)
SELECT 0 as [Inserted];
ELSE
BEGIN
INSERT INTO Cus_Ser(CustomerID,ServID) VALUES(#0, #1)
SELECT 1 as [Inserted];
END";
You can execute this as a parameterized query, which is much safer* than the code you have:
var response = db.QuerySingle(sql, CustomerID, ServID); // passing the input value as a parameter
if (response.Inserted == 1) {
// WebMatrix might convert to a bool, in which you would want `response.Inserted == true` instead
Response.Redirect("~/ViewService?CustomerID=" + CustomerID);
}
else
{
Validation.AddFormError("Entered Value is Not a Service Numberr");
}
As I am not deeply familiar with WebMatrix, I am not 100% sure about this code. Hopefully it sets you in the right direction.
A word of warning: your original code is vulnerable to something called a SQL injection attack. Most programmers start out making that mistake; I know that I did. In summary: that inputnumber parameter could have a SQL statement in it instead of a number. If someone crafts that SQL Statement just right, then they could cause a lot of damage. For an entry-level programming assignment it is not something to worry about in detail. But as you progress in coding, you will need to learn how to use parameterized queries in order to guard against SQL injection. A few useful references:
SQL Injection
Introduction to Working with a Database in ASP.NET Web Pages (Razor) Sites

Can be get desired column from share point list?

I am using the following Caml Query to get data from a share point list.
oSb.Append(" <OrderBy>")
oSb.Append(" <FieldRef Name=""Title"" />")
oSb.Append(" </OrderBy>")
But this query is giving me all columns of list.
Is there any way to get only desired column from a share point list using Caml Query?
Please help me.
Take a look at the MSDN article about View Fields. You can specify those fields before running your CAML query.
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
// Build a query.
SPQuery query = new SPQuery();
query.Query = string.Concat(
"<Where><Eq>",
"<FieldRef Name='Status'/>",
"<Value Type='CHOICE'>Not Started</Value>",
"</Eq></Where>",
"<OrderBy>",
"<FieldRef Name='DueDate' Ascending='TRUE' />",
"<FieldRef Name=’Priority’ Ascending='TRUE' />",
"</OrderBy>");
query.ViewFields = string.Concat(
"<FieldRef Name='AssignedTo' />",
"<FieldRef Name='LinkTitle' />",
"<FieldRef Name='DueDate' />",
"<FieldRef Name='Priority' />");
query.ViewFieldsOnly = true; // Fetch only the data that we need.
// Get data from a list.
string listUrl = web.ServerRelativeUrl + "/lists/tasks";
SPList list = web.GetList(listUrl);
SPListItemCollection items = list.GetItems(query);
// Print a report header.
Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}",
"Assigned To", "Task", "Due Date", "Priority");
// Print the details.
foreach (SPListItem item in items)
{
Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}",
item["AssignedTo"], item["LinkTitle"], item["DueDate"], item["Priority"]);
}
}

shopping cart to email

I use simplecartjs to make a shopping cart on my website where you can select element and send it to your cart... next step, will be the checkout process, but for business reason, no checkout process will append, and a simple form with name and email and date for order pickup will be ask. Now the order must be send to an email address (at the company) that will fullfill the order.
The question : how to send the content of the cart to an email body or as attachement ?
This Will add the email order, suplimentary fields to the user "Phone and Adress",
Check during the CheckOut the the user is registered if not will redirect to registration.
WILL CLEAR Shopping cart only after succesful email order sent.
Will send 2 e-mail to the shop owner "shop#domain.com" and to the users email so he sees the order
Will need to make a new page for the Thank You part after succesful order is made
simplecartjs: around line 288 is in mine
me.emailCheckout = function() {
itemsString = "";
for( var current in me.items ){
var item = me.items[current];
itemsString += item.name + " " + item.quantity + " " + item.price + "\n";
}
var form = document.createElement("form");
form.style.display = "none";
form.method = "POST";
form.action = "sendjs.php";
form.acceptCharset = "utf-8";
form.appendChild(me.createHiddenElement("jcitems", itemsString));
form.appendChild(me.createHiddenElement("jctotal", me.total));
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
sendjs.php
<?php require( dirname(__FILE__) . '/wp-load.php' );
/* cheking is user is logged in*/
if ( is_user_logged_in() ) {
get_currentuserinfo(); /* getting user details*/
/* sending e-mail to the shop email */
$to = 'shop#domain.com';
$subject = 'New Order';
$jcitems = " Name: " . $current_user->user_lastname .
" \n First Name: " . $current_user->user_firstname .
" \n Email: " . $current_user->user_email .
" \n Phone: " . $current_user->phone .
" \n Adress: " . $current_user->adress ;
$headers = 'From: shop#domain.com' . "\r\n" .
'Reply-To: shop#domain.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $jcitems, $headers);
/* sending e-mail with the order to the users email*/
$to = $current_user->user_email;
$subject = 'Order copy from Domain';
$jcitems = "Thank you for you order. Below you have your ordered products".
" \n ORDER: \n\n " . $_POST['jcitems'] . "Total: " . $_POST['jctotal'] . " USD" .
"\n\n http://www.domain.com \nshop#domain.com";
$headers = 'From: shop#domain.com' . "\r\n" .
'Reply-To: shop#domain.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $jcitems, $headers);
/*Clearing the cart info after succesfull order is made*/
setcookie ("simpleCart", "", time() - 3600);
/*redirecting user to Thank you page from Wordpress*/
Header('Location: http://www.domain.com/thank_you/'); }
else { /*sending user to register*/
header( 'Location: http://www.domain.com/wp-login.php?action=register' ) ; exit; } ?>
You will need Register Plus plugin for wordpress to add the extra 2 fiels to the user "phone and address"
be sure to check
Add Registration Field
Add Profile Field
Required
You should add new checkout method to simplecartjs:
me.emailCheckout = function() {
itemsString = "";
for( var current in me.items ){
var item = me.items[current];
itemsString += item.name + " " + item.quantity + " " + item.price + "\n";
}
var form = document.createElement("form");
form.style.display = "none";
form.method = "POST";
form.action = "sendjs.php";
form.acceptCharset = "utf-8";
form.appendChild(me.createHiddenElement("jcitems", itemsString));
form.appendChild(me.createHiddenElement("jctotal", me.total));
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
This will create new form element and submit cart data to sendjs.php. Enable this checkout method by setting me.checkoutTo = 'Email' in simplecart options.
Now create a new sendjs.php file:
<?php
$to = 'you#example.com';
$subject = 'the subject';
$jcitems = $_POST['jcitems'];
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $jcitems, $headers);
Header('Location: thankyou.html');
?>
This will send the email message and redirect to thankyou.html page you should also create.