Browsing all articles in Javascripts

CRM 2011 Set State to a Record

Posted Posted by cllamas in CRM 2011, Javascripts     Comments No comments
Nov
30

Código Jscript para Cambiar Estado a un Registro usando Jscript para CRM 2011:

   1: function SetState(EntityName,Id,State,Status)

   2: {

   3:     var authenticationHeader = GenerateAuthenticationHeader();

   4:     // Prepare the SOAP message. 

   5:     var xml = "<?xml version='1.0' encoding='utf-8'?>" +

   6:  

   7:     "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +

   8:     " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +

   9:     authenticationHeader +

  10:     "<soap:Body>" +

  11:     "<Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +

  12:     "<Request xsi:type='SetStateDynamicEntityRequest'>" +

  13:     "<Entity>"+

  14:     "<Id xmlns='http://schemas.microsoft.com/crm/2006/CoreTypes'>"+Id+"</Id>" +

  15:     "<Name xmlns='http://schemas.microsoft.com/crm/2006/CoreTypes'>"+EntityName+"</Name>" +

  16:     "</Entity>" +

  17:     "<State>"+State+"</State>" +

  18:     "<Status>"+Status+"</Status>" +

  19:     "</Request>" +

  20:     "</Execute>" +

  21:     "</soap:Body>" +

  22:     "</soap:Envelope>";

  23:     

  24:     // Prepare the xmlHttpObject and send the request. 

  25:     var xHReq = new ActiveXObject("Msxml2.XMLHTTP"); 

  26:     xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false); 

  27:     xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute"); 

  28:     xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); 

  29:     xHReq.setRequestHeader("Content-Length", xml.length); 

  30:     xHReq.send(xml); 

  31:     // Capture the result. 

  32:     var resultXml = xHReq.responseXML;

  33:     

  34:     // Check for errors. 

  35:     var errorCount = resultXml.selectNodes('//error').length;

  36:     if (errorCount != 0) 

  37:     { 

  38:     var msg = resultXml.selectSingleNode('//description').nodeTypedValue; 

  39:     alert(msg); 

  40:     }

  41: }

CRM 2011 – Jscripts sobre Campos y elementos del Formulario

Posted Posted by cllamas in CRM 2011, Javascripts, Trucos     Comments No comments
May
3

 

Con el cambio de versión de Microsoft Dynamics CRM 4.0 a CRM 2011, se presentaron cambios en la interfaz grafica lo cual significa que hay cambios en los Jscrips para usar nuevas convenciones y usar las nuevas capacidades de CRM 2011.

CRM 4.0 hace uso del objeto crmForm para proveer acceso a los campos del formulario. En la versión 2011 este objeto está es desuso. Algunos Scripts usando crmForm van a seguir siendo soportados por asuntos de compatibilidad, pero para usar las correctamente CRM 2011 se deben cambiar los Scripts de crmForm a Xrm.Page:

SELECCIONAR VALOR DE UN CAMPO

Xrm.Page.getAttribute(“attribute”).getValue();

ESTABLECER VALOR DE UN CAMPO

Xrm.Page.getAttribute(“attribute”).setValue(“Value”);

ESTABLECER VALOR DE UN PICKLIST EN OPCION 1000000000

Xrm.Page.getAttribute(“attribute”).setValue(100000000);

ESTABLECER VALOR DE UN CAMPO EN NULO

Xrm.Page.getAttribute(“attribute”).setValue(null);

ESTABLECER NIVEL DE REQUERIMIENTO DE UN CAMPO

Xrm.Page.getAttribute(“attribute”).setRequiredLevel(“required”);

Xrm.Page.getAttribute(“attribute”).setRequiredLevel(“recommended”);

Xrm.Page.getAttribute(“attribute”).setRequiredLevel(“none”);

DESHABILITAR / HABILITAR CAMPOS

Xrm.Page.getControl(attribute”).setDisabled(true);

Xrm.Page.getControl(“attribute”).setDisabled(false);

MOSTRAR / OCULTAR CAMPOS

Xrm.Page.getControl (“attribute”).setVisible(true);

Xrm.Page.getControl (“attribute”).setVisible(false);

SET FOCUS

Xrm.Page.getControl(“attribute”).setFocus(true);

ESCONDER / MOSTRAR TAB

Xrm.Page.ui.tabs.get(1).setVisible(true);

Xrm.Page.ui.tabs.get(1).setVisible(false);

ESTABLECER EL VALOR EN UN CAMPO BOOLEAN

Xrm.Page.getAttribute(“attribute”).setValue(true);

Xrm.Page.getAttribute(“attribute”).setValue(false);

ID DE LA ENTIDAD DEL FORMULARIO ACTUAL

Xrm.Page.data.entity.getId();

SALVAR EL FORMULARIO ACTUAL

Xrm.Page.data.entity.save();

ACCIÓN FireOnChange DE UN CAMPO EN OTRO

Xrm.Page.getAttribute(“attribute”).fireOnChange();

ID O EL CONTENIDO DEL CAMPO LOOKUP (BUSQUEDA)

Xrm.Page.getAttribute(“attribute”).getValue()[0].id;

Xrm.Page.getAttribute(“attribute”).getValue()[0].name;

DETENER EL EVENTO GUARDAR (SAVE) DEL FORMULARIO

event.returnValue = false;

DEVUELVE EL GUID DEL ROL DE SEGURIDAD DEL USUARIO CRM

Xrm.page.context.getUserRoles();


Nuevo_Logo

Convertir Jscripts de CRM 4.0 a CRM 2011

Posted Posted by cllamas in CRM 2011, Javascripts, Trucos     Comments No comments
Nov
17

Encontré en el blog MSCRM Bing’d esta herramienta que permite convertir Jscripts (Java Scripts) que fueron creados para la versión 4.0 a la última versión de Microsoft Dynamics CRM 2011.

La herramienta utiliza XML que contiene los nodos de CRM 4.0 y de CRM 2011 y permite a la herramienta realizar la operación de “Buscar” y “Reemplazar” en sentencias especificas del código.

Descarguela y conozca más.

image

 

Nuevo_Logo

CRM 4.0 – Mostrar Registros Inactivos en la Vista Asociada de una Entidad

Posted Posted by cllamas in Javascripts, Microsoft CRM, Trucos     Comments No comments
Oct
13

Se requieren que se muestren los registros tanto Activos como Inactivos en la Vista Asociada de una Entidad. Por ejemplo, en la entidad Oportunidad uno desea ver los registros tanto Activos como Inactivos de una Entidad con la que se tiene una relacion 1 – N. Lo que debe hacer es:

  1. Exportar las Personalizaciones para la entidad
  2. Abrir XML con un editor de Texto
  3. Buscar dentro del archivo por la sección en la cual se encuentre la vista asociada. Por ejempo “Account Associated View”
  4. En la sección SavedQuery, buscar el Filtro especificado en el Columnset.
            <filter type="and">
              <condition column="statecode" value="0" operator="eq" />
            </filter>
  5. Remover esas 3 líneas de código.
  6. Importar la personalización.
  7. Publicar la personalización importada.

read more

Ocultar o mostrar una sección en un formulario

Posted Posted by fdaza in Javascripts     Comments No comments
Oct
7

A veces es necesario ocultar algunas secciones en un formulario.

Es posible hacer aparecer y desaparecer secciones dependiendo de valores en un campo picklist (lista desplegable).

Por ejemplo en Cuenta, si seleccionamos ‘Otro’ (opción numero 6 del picklist) en Tipo de Documento, debe desaparecer la seccion Clasificacion:

En la ventana de diseño, en el evento OnChange de Tipo de Documento, escriba el siguiente codigo:

//MuestraOculta secciones__________
var pField=crmForm.all.new_tipodocumento.DataValue;
if (pField!=6)
{
//Entry Point  
MostrarTipocuenta();
}
else if(pField==6)
{
//Entry Point  
OcultaTipocuenta();
}

//Mostrar Clasificacion_____________
function MostrarTipocuenta()  
{  
ToggleSection( 0 , 3 , "" /* "inline" */);  
}

//Ocultar Clasificacion_____________
function OcultaTipocuenta()  
{  
ToggleSection( 0 , 3 , "none" /* "inline" */);  
}  
 
// Tabs and Section Collections are zero based  
function ToggleSection( tabIndex , sectionIndex , displayType )  
{  
var sec = document.getElementById( "tab" + tabIndex );  
sec.childNodes[0].rows[ sectionIndex ].style.display = displayType;  
}

De esta forma. Guardar y publicar:

Cuando el campo Tipo de Documento es igual a ‘Otro’, la seccion  Clasificacion desaparece, si selecciona cualquier otra, la seccion aparece de nuevo:

 

Nuevo_Logo

Cambiar la entidad de búsqueda en un campo LookUp

Posted Posted by fdaza in Javascripts     Comments No comments
Mar
10

Al intentar abrir un campo de busqueda (lookup) normalmente queda asignada una entidad por defecto.

Por ejemplo, en Citas el campo ‘Asistentes opcionales’ aparece automaticamente asignado a la entidad Cuentas. Normalmente el usuario debe cambiar a ‘Contactos’ para seleccionar convenientemente uno o varios contactos.

Para cambiar la opcion por defecto a Contactos deberá abrir la entidad Cita en modo diseño. En el evento On Load, agruegue el siguiente codigo JavaScript:

crmForm.all.optionalattendees.lookuptypes = "1,2";
crmForm.all.optionalattendees.lookuptypeIcons = "/_imgs/ico_16_1.gif:/_imgs/ico_16_2.gif:";
crmForm.all.optionalattendees.defaulttype = "2";

Guarde y publique los cambios.

A partir de ahora, cuando intente registrar un contacto opcional en Citas, aparecerá por defecto la entidad ‘Contacto’. Seleccione los contactos que desee agregar, uno o varios:

Cambiar el Valor que muestra un Lookup (2)

Posted Posted by cllamas in Javascripts     Comments No comments
Feb
22

Otra opción distinta a la del post Cambiar el Valor que muestra un Lookup.

En el Evento OnLoad del Formulario, colocar siguiente Jscript en el evento onLoad (Update) y en el Onchange del atributo. Modificar:

  • new_id: Nombre del Campo Lookup
  • entityName: Entidad a la cual se realiza Lookup
  • otherName: Nombre a mostrar que va a reemplazar el que se muestra por defecto

Codigo:

if(crmForm.all.new_id.DataValue!=null)
{
var lookupItem1 = new Array;
lookupItem1 = crmForm.all.new_id.DataValue;
var id = lookupItem1[0].id;
var authenticationHeader = GenerateAuthenticationHeader();
// Prepare the SOAP message.
var xml = "<?xml version=’1.0′ encoding=’utf-8′?>"+
"<soap:Envelope xmlns:soap=’http://schemas.xmlsoap.org/soap/envelope/‘"+
" xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance‘"+
" xmlns:xsd=’http://www.w3.org/2001/XMLSchema‘>"+
authenticationHeader+
"<soap:Body>"+
"<Retrieve xmlns=’http://schemas.microsoft.com/crm/2007/WebServices‘>"+
"<entityName>entityName</entityName>"+
"<id>"+id+"</id>"+
"<columnSet xmlns:q1=’http://schemas.microsoft.com/crm/2006/Query‘ xsi:type=’q1:ColumnSet’>"+
"<q1:Attributes>"+
"<q1:Attribute>otherName</q1:Attribute>"+
"</q1:Attributes>"+
"</columnSet>"+
"</Retrieve>"+
"</soap:Body>"+
"</soap:Envelope>";
// Prepare the xmlHttpObject and send the request.
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// Capture the result.
var resultXml = xHReq.responseXML;
// Check for errors.
var errorCount = resultXml.selectNodes(‘//error’).length;
if (errorCount != 0)
{
var msg = resultXml.selectSingleNode(‘//description’).nodeTypedValue;
alert(msg);
}
// Display the retrieved value.
else
{
var lookupData = new Array();
var lookupItem= new Object();
lookupItem.id = id;
lookupItem.typename = ‘entityName’;
lookupItem.name = resultXml.selectSingleNode("//q1:otherName").nodeTypedValue;
lookupData[0] = lookupItem;
crmForm.all.new_id.DataValue = lookupData;
}
}

Nuevo_Logo

Cambiar el Valor que muestra un Lookup

Posted Posted by cllamas in Javascripts     Comments No comments
Feb
22

Tomado de Aquí.

Step 1

Go on the form where the lookup is displayed:

On the onload event, add this line of code and change LookupSchemaName by the schema name of your lookup.

crmForm.all.LookupSchemaName.FireOnChange();

Step 2

On the onchange event of the lookup, Copy the following code (inside the table):

  • fieldToDisplay = the name of the attribute that you want to display in the lookup. Take the schema name of the attribute in the linked entity.
  • fieldToDisplayIsText:
    • true if you want to display a nvarchar field.
    • false if you want to display a picklist or a lookup field.
  • organizationName = name of your organization (without spaces).

var fieldToDisplay = ‘accountnumber’;
var fieldToDisplayIsText = true;
var organizationName = ‘MyOrganizationName’;

var lookupData = new Array();
var lookupItem= new Object();
var lookup = event.srcElement.DataValue;

if (typeof(lookup) != ‘undefined’ && lookup != null && lookup[0] != null)
{
var myValue = GetAttributeValueFromID(lookup[0].typename,lookup[0].id,fieldToDisplay,fieldToDisplayIsText);

if(myValue != ”)
{

  lookupItem.id = lookup[0].id;
   lookupItem.typename = lookup[0].typename;
   lookupItem.name = myValue;
   lookupData[0] = lookupItem; 
   crmForm.all[event.srcElement.id].DataValue = lookupData;
}

}

function GetAttributeValueFromID(sEntityName, sGUID, sAttributeName, isTextField)
{
var xml = "" +

"<?xml version="1.0" encoding="utf-8"?>" +

"<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">" +

"  <soap:Header>" +

"    <CrmAuthenticationToken xmlns="http://schemas.microsoft.com/crm/2007/WebServices">" +

"      <AuthenticationType xmlns="http://schemas.microsoft.com/crm/2007/CoreTypes">0</AuthenticationType>" +

"      <OrganizationName xmlns="http://schemas.microsoft.com/crm/2007/CoreTypes">"+organizationName +"</OrganizationName>" +

"      <CallerId xmlns="http://schemas.microsoft.com/crm/2007/CoreTypes">00000000-0000-0000-0000-000000000000</CallerId>" +

"    </CrmAuthenticationToken>" +

"  </soap:Header>" +

"  <soap:Body>" +

"    <Execute xmlns="http://schemas.microsoft.com/crm/2007/WebServices">" +

"      <Request xsi:type="RetrieveRequest" ReturnDynamicEntities="false">" +

"        <Target xsi:type="TargetRetrieveDynamic">" +

"          <EntityName>" + sEntityName + "</EntityName>" +

"          <EntityId>" + sGUID + "</EntityId>" +

"        </Target>" +

"        <ColumnSet xmlns:q1="http://schemas.microsoft.com/crm/2006/Query" xsi:type="q1:ColumnSet">" +

"          <q1:Attributes>" +

"            <q1:Attribute>" + sAttributeName + "</q1:Attribute>" +

"          </q1:Attributes>" +

"        </ColumnSet>" +

"      </Request>" +

"    </Execute>" +

"  </soap:Body>" +

"</soap:Envelope>" +

"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);

xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");

xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");

xmlHttpRequest.setRequestHeader("Content-Length", xml.length);

xmlHttpRequest.send(xml);

var result = null;

if(isTextField){

result = xmlHttpRequest.responseXML.selectSingleNode("//q1:" + sAttributeName).text;

}

else

{

result = xmlHttpRequest.responseXML.selectSingleNode("//q1:" + sAttributeName).getAttribute(‘name’);

}
                        if (result == null)
                        {
                                    return ”;
}
                        else
                        return result;
            }

Step 3

Save and publish the entity

 Nuevo_Logo

Esconder un Tab de un Formulario

Posted Posted by cllamas in Javascripts     Comments No comments
Feb
22

Muchas veces hay campos que no se pueden borrar en un formulario.  En estos casos estos campos se ponen en un tab diferente.  La mejor opción es esconder ese tab para que los usuarios no puedan ver estos campos.

Abrir el Formulario formulario y seleccionar propiedades del formulario. En el Evento On Load incluir el siguiente código:

/*hide a tab(tab number comes from 0)*/  
crmForm.all.tab1Tab.style.display = ‘none’;

IMPORTANTE  Se empiezan a contar los tabs de izquiera a derecha iniciando en 0

HideTab.gif

Esconder/Mostrar Campos y Secciones

//Ocultar un campo
crmForm.all.field.style.display = ‘none’;

//Ocultar un Label de un campo
crmForm.all.field_c.style.display = ‘none’;

//Mostrar de nuevo un campo
crmForm.all.field.style.display = "";
//Ocultar la sección en la que esta contenida el campo
crmForm.all.field.parentElement.parentElement.parentElement.style.display = ‘none’;

Nuevo_Logo

Cambiar el estado de una Tarea usando Jscript (CrmService)

Posted Posted by cllamas in Javascripts, Microsoft CRM     Comments No comments
Feb
22

El propósito de este Jscript es utilizar los WebServices de Microsoft Dynamics CRM para que desde un evento asíncrono en un formulario de CRM cambiar el estado de una actividad “Tarea”.

// Prepare variables.
var EntityId = "6C9E7246-E12D-DE11-8D96-005056C00008";
var TaskState = "Canceled";
var TaskStatus = "6";
var authenticationHeader = GenerateAuthenticationHeader();

// Prepare the SOAP message.
var xml = "<?xml version=’1.0′ encoding=’utf-8′?>"+
"<soap:Envelope xmlns:soap=’http://schemas.xmlsoap.org/soap/envelope/‘"+
" xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance‘"+
" xmlns:xsd=’http://www.w3.org/2001/XMLSchema‘>"+
authenticationHeader+
"<soap:Body>"+
"<Execute xmlns=’http://schemas.microsoft.com/crm/2007/WebServices‘>"+
"<Request xsi:type=’SetStateTaskRequest’>"+
"<EntityId>"+EntityId+"</EntityId>"+
"<TaskState>"+TaskState+"</TaskState>"+
"<TaskStatus>"+TaskStatus+"</TaskStatus>"+
"</Request>"+
"</Execute>"+
"</soap:Body>"+
"</soap:Envelope>";

// Prepare the xmlHttpObject and send the request.
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// Capture the result.
var resultXml = xHReq.responseXML;

// Check for errors.
var errorCount = resultXml.selectNodes(‘//error’).length;
if (errorCount != 0)
{
var msg = resultXml.selectSingleNode(‘//description’).nodeTypedValue;
alert(msg);
}

Nuevo_Logo

Archivo

Categorias

Ingrese su Correo para insribirse en nuestro blog y lo notificaremos cuando tengamos nuevas entradas