Adding custom dropdown(values dynamically from db) in the lead form in vTiger - vtiger

I am new to vtiger crm and need a code to add the dropdown that has values from the database table in add lead page.
Please provide a solution if somebody have ?

You can add drop-down field by using bellow code and follow the steps to achieve your result:
Add bellow code in one PHP file (e.g add_to_lead.php).
Put that file into your project directory.
Run that file from browser (e.g www.yourVtigerhost.com/add_to_lead.php)
$Vtiger_Utils_Log = true;
include_once('vtlib/Vtiger/Menu.php');
include_once('vtlib/Vtiger/Module.php');
$module = new Vtiger_Module();
$module = $module->getInstance('Leads');
// Create new Block into Lead Module and your drop-down added into new block
$block1 = new Vtiger_Block();
$block1->label = 'LBL_LEAD_INFORMATION';
$block1 = $block1->getInstance($block1->label,$module);
$field0 = new Vtiger_Field();
$field0->name = 'your field name';
$field0->table = $module->basetable;
$field0->label = 'Your field Name to display';
$field0->column = 'field_name';
$field0->columntype = 'VARCHAR(100)';
$field0->uitype = 15;
$field0->setPicklistValues( Array ('Dropdown Value1','Dropdown Value2','Dropdown Value3'));
$field0->typeofdata = 'V~O';
$block1->addField($field0);
New Dropdown have values like Dropdown Value1,Dropdown Value2,Dropdown Value3
If you want to add more values into dropdown than you can add from Setting-> Studio->Picklist Editor.

Related

Generating a data table to iterate through in a Django Template

I have this function that uses PrettyTables to gather information about the Virtual Machines owned by a user. Right now, it only shows information and it works well. I have a new idea where I want to add a button to a new column which allows the user to reboot the virutal machine. I already know how to restart the virtual machines but what I'm struggling to figure out is the best way to create a dataset which i can iterate through and then create a HTML table. I've done similar stuff with PHP/SQL in the past and it was straight forward. I don't think I can iterate through PrettyTables so I'm wondering what is my best option? Pretty tables does a very good job of making it simple to create the table (as you can see below). I'm hoping to use another method, but also keep it very simple. Basically, making it relational and easy to iterate through. Any other suggestions are welcome. Thanks!
Here is my current code:
x = PrettyTable()
x.field_names = ["VM Name", "OS", "IP", "Power State"]
for uuid in virtual_machines:
vm = search_index.FindByUuid(None, uuid, True, False)
if vm.summary.guest.ipAddress == None:
ip = "Unavailable"
else:
ip = vm.summary.guest.ipAddress
if vm.summary.runtime.powerState == "poweredOff":
power_state = "OFF"
else:
power_state = "ON"
if vm.summary.guest.guestFullName == None:
os = "Unavailable"
else:
os = vm.summary.guest.guestFullName
x.add_row([vm.summary.config.name, os, ip, power_state])
table = x.get_html_string(attributes = {"class":"table table-striped"})
return table
Here is a sample of what it looks like and also what I plan to do with the button. http://prntscr.com/nki3ci
Figured out how to query the prettytable. It was a minor addition without having to redo it all.
html = '<table class="table"><tr><th>VM Name</th><th>OS</th><th>IP</th><th>Power
State</th></tr>'
htmlend = '</tr></table>'
body = ''
for vmm in x:
vmm.border = False
vmm.header = False
vm_name = (vmm.get_string(fields=["VM Name"]))
operating_system = (vmm.get_string(fields=["OS"]))
ip_addr = ((vmm.get_string(fields=["IP"])))
body += '<tr><td>'+ vm_name + '</td><td>' + operating_system + '</td> <td>'+ ip_addr +'</td> <td>ON</td></tr>'
html += body
html += htmlend
print(html)

Search custom property in SharePoint User Profile

I created a custom property in the user profile.
I want to search through all the user profiles and output those profiles in which the custom property contains a certain string
For example:
User1- Custom Property value is 1,2,3
User2- Custom Property value in 2,4,5
User3- Custom Property value is 4,6,8
I want to output all the profiles in which Custom Property contains 2
(using c# code)
So the output should have User1 and User2
Can someone suggest the best way to implement this?
I did find some links in the internet for searching user profiles use KeyWord search but and not sure if those methods could be used to search through Custom Properties.
Example: https://www.collaboris.com/how-to-use-search-keywordquery-to-query-user-profiles-in-sharepoint/
I am using SharePoint 2013
We ended up promoting the Custom Property that we added to the User profile to a Managed property.
Also it seems like we can do wildcard searches on managed properties so we do People searches like "CustomProperty:*,2,*" so that it would return all the user profiles which have the number 2 in the custom property of their user profile
Interestingly the wildcard works only on the end for OOTB properties like FirstName so we cant do things like FirstName:oh and expect it would return John Doe's profile
But we can certainly do this - FirstName:joh* and that would return all the people whose first name starts with Joh (which would include John Doe)
But it seems like the wildcard works both at the beginning and the end for the custom managed properties (which helped a great deal for us)
On how to return the results of the search using c# we used this-
private DataTable GetPeople(SPSite spSite, string queryText)
{
var keywordQuery = new KeywordQuery(spSite)
{
QueryText = queryText,
KeywordInclusion = KeywordInclusion.AllKeywords,
SourceId = System.Guid.Parse("b09a7990-05ea-4af9-81ef-edfab16c4e31")
};
keywordQuery.RowLimit = this.MaxProfilesToDisplay;
keywordQuery.SelectProperties.Add("AccountName");
keywordQuery.SelectProperties.Add("PictureURL");
SearchExecutor e = new SearchExecutor();
ResultTableCollection rt = e.ExecuteQuery(keywordQuery);
var tab = rt.Filter("TableType", KnownTableTypes.RelevantResults);
var result = tab.FirstOrDefault();
DataTable DT = result.Table;
return DT;
}
and we would invoke this like
DataTable dt = GetPeople(SPContext.Current.Site, "CustomProperty:*,2,*" );

How to search for Items that doesn't contain certain keywords using Sitecore Advanced Database Crawler?

I have millions of items in the database. And user can search those items based on the keyword. In the search function, I need to provide a feature that search for NOT that keyword.
For example Item A has a field called msg and the value is Sitecore is awesome and great.
In the search box, user can check the checkbox that indicates to show any item that doesn't contain the keyword. Maybe user key in is keyword, so Item A will not be displayed or retrieved by ADC.
Edit: Currently I'm using sitecore6.6, thus Search method has been deprecated. I have tried the Not keyword by using Occurrence.MustNot, but it doesn't return any result.
The Sitecore Advanced Database Crawler is an extension of the Sitecore.Search API and Sitecore.Search API is a wrapper around Lucene.
In Lucene you can user queries with NOT or - to exclude something like "Sitecore NOT awesome" or "Sitecore -awesome".
To exclude something you need at least one include term.
Not sure if it works, but give it a try.
This is untested, but you might have luck by using a MatchAllDocsQuery and supplying the keywords in the form of a Filter.
BooleanQuery booleanQuery = new BooleanQuery();
QueryParser queryParser = new QueryParser("msg", new StandardAnalyzer());
Query userQuery = queryParser.Parse("Sitecore is awesome and great");
booleanQuery.Add(userQuery, reverseQuery.Checked ? BooleanClause.Occur.MUST_NOT : BooleanClause.Occur.MUST);
MatchAllDocsQuery matchAllQuery = new MatchAllDocsQuery();
Filter filter = new QueryFilter(booleanQuery);
using (QueryRunner queryRunner = new QueryRunner("myIndex"))
{
var skinnyItems = queryRunner.RunQuery(matchAllQuery, filter, ...)
}
What I have done to NOT include the keywords associated with the result item set is this:
protected List<Item> getSearchResults(string queryToSearch, string selectedFilter, string notToSearch)
{
Database db = Sitecore.Context.Database;
var index = SearchManager.GetIndex("siteSearchIndexName");
using (SortableIndexSearchContext context = new SortableIndexSearchContext(index))
{
if (!String.IsNullOrWhiteSpace(query))
{
query.ToLower();
CombinedQuery cq = new CombinedQuery();
QueryBase qbKeyword = new FieldQuery("_orderkeywordpair", query);
QueryBase qbContent = new FieldQuery("_content", query);
QueryBase qbHtml = new FieldQuery("html", query);
if (!String.IsNullOrWhiteSpace(selectedFilter) && selectedFilter.ToLower() != "all")
{
QueryBase qbFilter = new FieldQuery("_pagetype", selectedFilter);
cq.Add(qbFilter, QueryOccurance.Must);
}
cq.Add(qbKeyword, QueryOccurance.Should);
cq.Add(qbContent, QueryOccurance.Must);
cq.Add(qbHtml, QueryOccurance.MustNot);
SearchHits hits = context.Search(cq);

Deleting a file from sharepoint using web service

I am trying to delete a file from a sharepoint document library.
My application is in C#, which uses the web services of sharepoint.
Would like to know how this can be done.
Thanks in advance.
Delete a Document in SharePoint using Web Services
1.Add Web Reference to http://[your site]/_vti_bin/Lists.asmx
2.You need Document ID, Library Name, and Url to the document to be deleted
var spWebServiceLists = "http://[your site]/_vti_bin/Lists.asmx";
var listService = new Lists
{
Credentials = CredentialCache.DefaultCredentials,
Url = spWebServiceLists
};
string id = 10;
string library = #"Shared Documents";
string url = #"http://[your site]/Shared Documents/Test.docx";
string xml = "<Method ID='1' Cmd='Delete'>" +
"<Field Name='ID'>" + id + "</Field>" +
"<Field Name='FileRef'>" + HttpUtility.UrlDecode(url) + "</Field>" +
"</Method>";
/*Get Name attribute values (GUIDs) for list and view. */
System.Xml.XmlNode ndListView = listService.GetListAndView(library, "");
string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;
/*Create an XmlDocument object and construct a Batch element and its
attributes. Note that an empty ViewName parameter causes the method to use the default view. */
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
System.Xml.XmlElement batchElement = doc.CreateElement("Batch");
batchElement.SetAttribute("OnError", "Continue");
batchElement.SetAttribute("ListVersion", "1");
batchElement.SetAttribute("ViewName", strViewID);
/*Specify methods for the batch post using CAML. To update or delete,
specify the ID of the item, and to update or add, specify
the value to place in the specified column.*/
batchElement.InnerXml = xml;
XmlNode item;
item = listService.UpdateListItems(library, batchElement);
I just tested this code and works well.
For more information please see following links
Lists.UpdateListItems Method
How to: Update List Items
If you work with SharePoint 2010, you can use CSOM to access SharePoint web services. This link could be helpful to execute crud operations. If you work with SharePoint 2013 there is also CSOM API, it has similar funcitonality as in 2010.

EventReceiver not Firing on SharePoint List

I am trying to create an EventReceiver for a blog site (for the Posts list) and am having some trouble getting it working. I want to change the Created By column to Anonymous. Basically I have this whole thing working in a console application, however, that will only change the Created By column names when the console application is executed.
I need it to change the Created By whenever a new item is added to the list. My code is below....how do I modify this to use in an EventReceiver project??? Since I already tell the EventReceiver project the URL I want the EventReceiver attached to, I'm not sure what I can remove from this code, right now it just doesn't do anything, no error and no changing of the Created By column when I debug.
using (SPSite site = new SPSite("http://test-sharepoint/subsite/"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Posts"];
SPListItemCollection listItemCollection = list.Items;
foreach (SPListItem listItem in listItemCollection)
{
SPFieldUserValue userName = new SPFieldUserValue(web, 22, "Anonymous");
listItem["Author"] = userName;
listItem["Editor"] = userName;
listItem.Update();
}
web.Update();
}
}
EDIT: Code is in ItemAdded method
EDIT #2: This is trying the same code except without the loop and using properties.ListItem, this was my attempt in a Event Recevier project but no luck. It just doesn't change the Created By field, or any field for that matter (I tried the Title as well)
SPSite site = new SPSite("http://test-sharepoint/subsite/");
SPWeb web = site.OpenWeb();
SPFieldUserValue userName = new SPFieldUserValue(web, 22, "Anonymous");
properties.ListItem["Author"] = userName;
properties.ListItem["Editor"] = userName;
properties.ListItem.Update();
*Also from my understanding the SPFieldUserValue will grab either a User or a SharePoint User Group (Permissions) so in my code, the 22 grabs the SharePoint User Group that I want and "Anonymous" is the user from that group...
EDIT #3: More progress, this code works without issues for a list, however, not for the Posts or Comments lists, for those it does not change the Created By field. Could it be because of the approve/reject for all items??? Whether approved orpending it still does not show annonymous, BUT like I mentioned, it works fine in a different list.
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
SPSite site = new SPSite("http://test-sharepoint/hr/blog/"); //SPContext.Current.Site;
SPWeb web = site.OpenWeb();
SPFieldUserValue userName = new SPFieldUserValue(web,22,"Anonymous");
SPListItem currentItem = properties.ListItem;
//currentItem["Title"] = userName; //DateTime.Now.ToString();
currentItem["Author"] = userName;
currentItem["Editor"] = userName;
currentItem.SystemUpdate();
}
**EDIT #4: Alright I found my issue, when creating the project I chose Custom List as my list to attach to but I needed to choose Posts or Comments and now the above code works!!!
But now I have another problem, all posts on the blog are first submitted for approval...and due to this the event receiver doesn't seem to work for users other than the admin. It works fine for the admin account where I can just directly publish a post or comment but for a user with Contribute permissions whose posts are submitted for approval still shows their name on the Manage Posts page...what could I do about this? Any ideas?**
The code that works:
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
SPSite site = new SPSite("http://test-sharepoint/hr/blog/"); //SPContext.Current.Site;
SPWeb web = site.OpenWeb();
SPFieldUserValue userName = new SPFieldUserValue(web, 23, "Anonymous");
SPListItem currentItem = properties.ListItem;
currentItem["Author"] = userName;
currentItem["Editor"] = userName;
currentItem.SystemUpdate();
}
In response to edit #4, when working with SharePoint, if code works when executed by the administrator account, but does not work when executed by a "normal" account, permissions are likely to blame.
See the answer to the question SharePoint/WSS: Modify “created by” field? for an example of an SPItemEventReceiver that modifies the Author field.
Note: Many SharePoint developers recommend against the use of RunWithElevatedPrivileges and suggest using impersonation instead. See my answer to the question In which situation use SPSecurity.RunWithElevatedPrivileges with superusertoken? for more details.