Кастомизация
24
Май
0

Удаление объектов из Расширенного поиска

Иногда бывает такое требование – удалить лишние объекты списка с выбором в Расширенном поиске. Но такой настройки нет – в нем отображаются все объекты, к которым есть доступ на чтение. Поэтому воспользуемся фокусом с кнопкой и JS-функцией на определение ее видимости:

  • Создайте JS Веб-ресурс с таким кодом:
    var entities = [
        //'account',//Account
        'accountleads',//AccountLeads
        'activitymimeattachment',//ActivityMimeAttachment
        'activityparty',//ActivityParty
        'activitypointer',//ActivityPointer
        'advancedsimilarityrule',//AdvancedSimilarityRule
        'annotation',//Annotation
        'annualfiscalcalendar',//AnnualFiscalCalendar
        'applicationfile',//ApplicationFile
        'appointment',//Appointment
        'asyncoperation',//AsyncOperation
        'attachment',//Attachment
        'attributemap',//AttributeMap
        'audit',//Audit
        'authorizationserver',//AuthorizationServer
        'azureserviceconnection',//AzureServiceConnection
        'bookableresource',//BookableResource
        'bookableresourcebooking',//BookableResourceBooking
        'bookableresourcebookingheader',//BookableResourceBookingHeader
        'bookableresourcecategory',//BookableResourceCategory
        'bookableresourcecategoryassn',//BookableResourceCategoryAssn
        'bookableresourcecharacteristic',//BookableResourceCharacteristic
        'bookableresourcegroup',//BookableResourceGroup
        'bookingstatus',//BookingStatus
        'bulkdeletefailure',//BulkDeleteFailure
        'bulkdeleteoperation',//BulkDeleteOperation
        'bulkoperation',//BulkOperation
        'bulkoperationlog',//BulkOperationLog
        'businessdatalocalizedlabel',//BusinessDataLocalizedLabel
        'businessprocessflowinstance',//BusinessProcessFlowInstance
        'businessunit',//BusinessUnit
        'businessunitmap',//BusinessUnitMap
        'businessunitnewsarticle',//BusinessUnitNewsArticle
        'calendar',//Calendar
        'calendarrule',//CalendarRule
        'campaign',//Campaign
        'campaignactivity',//CampaignActivity
        'campaignactivityitem',//CampaignActivityItem
        'campaignitem',//CampaignItem
        'campaignresponse',//CampaignResponse
        'category',//Category
        'channelaccessprofile',//ChannelAccessProfile
        'channelaccessprofileentityaccesslevel',//ChannelAccessProfileEntityAccessLevel
        'channelaccessprofilerule',//ChannelAccessProfileRule
        'channelaccessprofileruleitem',//ChannelAccessProfileRuleItem
        'channelproperty',//ChannelProperty
        'channelpropertygroup',//ChannelPropertyGroup
        'characteristic',//Characteristic
        'childincidentcount',//ChildIncidentCount
        'clientupdate',//ClientUpdate
        'columnmapping',//ColumnMapping
        'commitment',//Commitment
        'competitor',//Competitor
        'competitoraddress',//CompetitorAddress
        'competitorproduct',//CompetitorProduct
        'competitorsalesliterature',//CompetitorSalesLiterature
        'complexcontrol',//ComplexControl
        'connection',//Connection
        'connectionrole',//ConnectionRole
        'connectionroleassociation',//ConnectionRoleAssociation
        'connectionroleobjecttypecode',//ConnectionRoleObjectTypeCode
        'constraintbasedgroup',//ConstraintBasedGroup
        //'contact',//Contact
        'contactinvoices',//ContactInvoices
        'contactleads',//ContactLeads
        'contactorders',//ContactOrders
        'contactquotes',//ContactQuotes
        'contract',//Contract
        'contractdetail',//ContractDetail
        'contracttemplate',//ContractTemplate
        'convertrule',//ConvertRule
        'convertruleitem',//ConvertRuleItem
        'customcontrol',//CustomControl
        'customcontroldefaultconfig',//CustomControlDefaultConfig
        'customcontrolresource',//CustomControlResource
        'customeraddress',//CustomerAddress
        'customeropportunityrole',//CustomerOpportunityRole
        'customerrelationship',//CustomerRelationship
        'dataperformance',//DataPerformance
        'delveactionhub',//DelveActionHub
        'dependency',//Dependency
        'dependencyfeature',//DependencyFeature
        'dependencynode',//DependencyNode
        'discount',//Discount
        'discounttype',//DiscountType
        'displaystring',//DisplayString
        'displaystringmap',//DisplayStringMap
        'documentindex',//DocumentIndex
        'documenttemplate',//DocumentTemplate
        'duplicaterecord',//DuplicateRecord
        'duplicaterule',//DuplicateRule
        'duplicaterulecondition',//DuplicateRuleCondition
        'dynamicproperty',//DynamicProperty
        'dynamicpropertyassociation',//DynamicPropertyAssociation
        'dynamicpropertyinstance',//DynamicPropertyInstance
        'dynamicpropertyoptionsetitem',//DynamicPropertyOptionSetItem
        'email',//Email
        'emailhash',//EmailHash
        'emailsearch',//EmailSearch
        'emailserverprofile',//EmailServerProfile
        'emailsignature',//EmailSignature
        'entitlement',//Entitlement
        'entitlementchannel',//EntitlementChannel
        'entitlementcontacts',//EntitlementContacts
        'entitlementproducts',//EntitlementProducts
        'entitlementtemplate',//EntitlementTemplate
        'entitlementtemplatechannel',//EntitlementTemplateChannel
        'entitlementtemplateproducts',//EntitlementTemplateProducts
        'entitymap',//EntityMap
        'equipment',//Equipment
        'exchangesyncidmapping',//ExchangeSyncIdMapping
        'externalparty',//ExternalParty
        'externalpartyitem',//ExternalPartyItem
        'fax',//Fax
        'feedback',//Feedback
        'fieldpermission',//FieldPermission
        'fieldsecurityprofile',//FieldSecurityProfile
        'filtertemplate',//FilterTemplate
        'fixedmonthlyfiscalcalendar',//FixedMonthlyFiscalCalendar
        'goal',//Goal
        'goalrollupquery',//GoalRollupQuery
        'hierarchyrule',//HierarchyRule
        'hierarchysecurityconfiguration',//HierarchySecurityConfiguration
        'imagedescriptor',//ImageDescriptor
        'import',//Import
        'importdata',//ImportData
        'importentitymapping',//ImportEntityMapping
        'importfile',//ImportFile
        'importjob',//ImportJob
        'importlog',//ImportLog
        'importmap',//ImportMap
        'incident',//Incident
        'incidentknowledgebaserecord',//IncidentKnowledgeBaseRecord
        'incidentresolution',//IncidentResolution
        'integrationstatus',//IntegrationStatus
        'internaladdress',//InternalAddress
        'interprocesslock',//InterProcessLock
        'invaliddependency',//InvalidDependency
        'invoice',//Invoice
        'invoicedetail',//InvoiceDetail
        'isvconfig',//IsvConfig
        'kbarticle',//KbArticle
        'kbarticlecomment',//KbArticleComment
        'kbarticletemplate',//KbArticleTemplate
        'knowledgearticle',//KnowledgeArticle
        'knowledgearticleincident',//KnowledgeArticleIncident
        'knowledgearticlescategories',//KnowledgeArticlesCategories
        'knowledgearticleviews',//KnowledgeArticleViews
        'knowledgebaserecord',//KnowledgeBaseRecord
        'knowledgesearchmodel',//KnowledgeSearchModel
        'languagelocale',//LanguageLocale
        //'lead',//Lead
        'leadaddress',//LeadAddress
        'leadcompetitors',//LeadCompetitors
        'leadproduct',//LeadProduct
        'letter',//Letter
        'license',//License
        'list',//List
        'listmember',//ListMember
        'localconfigstore',//LocalConfigStore
        'lookupmapping',//LookUpMapping
        'mailbox',//Mailbox
        'mailboxstatistics',//MailboxStatistics
        'mailboxtrackingfolder',//MailboxTrackingFolder
        'mailmergetemplate',//MailMergeTemplate
        'metadatadifference',//MetadataDifference
        'metric',//Metric
        'mobileofflineprofile',//MobileOfflineProfile
        'mobileofflineprofileitem',//MobileOfflineProfileItem
        'mobileofflineprofileitemassociation',//MobileOfflineProfileItemAssociation
        'monthlyfiscalcalendar',//MonthlyFiscalCalendar
        'msdyn_postalbum',//msdyn_PostAlbum
        'msdyn_postconfig',//msdyn_PostConfig
        'msdyn_postruleconfig',//msdyn_PostRuleConfig
        'msdyn_wallsavedquery',//msdyn_wallsavedquery
        'msdyn_wallsavedqueryusersettings',//msdyn_wallsavedqueryusersettings
        'multientitysearch',//MultiEntitySearch
        'multientitysearchentities',//MultiEntitySearchEntities
        'notification',//Notification
        'officedocument',//OfficeDocument
        'officegraphdocument',//OfficeGraphDocument
        'opportunity',//Opportunity
        'opportunityclose',//OpportunityClose
        'opportunitycompetitors',//OpportunityCompetitors
        'opportunityproduct',//OpportunityProduct
        'orderclose',//OrderClose
        'organization',//Organization
        'organizationstatistic',//OrganizationStatistic
        'organizationui',//OrganizationUI
        'orginsightsmetric',//OrgInsightsMetric
        'owner',//Owner
        'ownermapping',//OwnerMapping
        'partnerapplication',//PartnerApplication
        'personaldocumenttemplate',//PersonalDocumentTemplate
        'phonecall',//PhoneCall
        'picklistmapping',//PickListMapping
        'pluginassembly',//PluginAssembly
        'plugintracelog',//PluginTraceLog
        'plugintype',//PluginType
        'plugintypestatistic',//PluginTypeStatistic
        'position',//Position
        'post',//Post
        'postcomment',//PostComment
        'postfollow',//PostFollow
        'postlike',//PostLike
        'postregarding',//PostRegarding
        'postrole',//PostRole
        'pricelevel',//PriceLevel
        'principalattributeaccessmap',//PrincipalAttributeAccessMap
        'principalentitymap',//PrincipalEntityMap
        'principalobjectaccess',//PrincipalObjectAccess
        'principalobjectaccessreadsnapshot',//PrincipalObjectAccessReadSnapshot
        'principalobjectattributeaccess',//PrincipalObjectAttributeAccess
        'principalsyncattributemap',//PrincipalSyncAttributeMap
        'privilege',//Privilege
        'privilegeobjecttypecodes',//PrivilegeObjectTypeCodes
        'processsession',//ProcessSession
        'processstage',//ProcessStage
        'processtrigger',//ProcessTrigger
        'product',//Product
        'productassociation',//ProductAssociation
        'productpricelevel',//ProductPriceLevel
        'productsalesliterature',//ProductSalesLiterature
        'productsubstitute',//ProductSubstitute
        'publisher',//Publisher
        'publisheraddress',//PublisherAddress
        'quarterlyfiscalcalendar',//QuarterlyFiscalCalendar
        'queue',//Queue
        'queueitem',//QueueItem
        'queueitemcount',//QueueItemCount
        'queuemembercount',//QueueMemberCount
        'queuemembership',//QueueMembership
        'quote',//Quote
        'quoteclose',//QuoteClose
        'quotedetail',//QuoteDetail
        'ratingmodel',//RatingModel
        'ratingvalue',//RatingValue
        'recommendationcache',//RecommendationCache
        'recommendationmodel',//RecommendationModel
        'recommendationmodelmapping',//RecommendationModelMapping
        'recommendationmodelversion',//RecommendationModelVersion
        'recommendationmodelversionhistory',//RecommendationModelVersionHistory
        'recommendeddocument',//RecommendedDocument
        'recordcountsnapshot',//RecordCountSnapshot
        'recurrencerule',//RecurrenceRule
        'recurringappointmentmaster',//RecurringAppointmentMaster
        'relationshiprole',//RelationshipRole
        'relationshiprolemap',//RelationshipRoleMap
        'replicationbacklog',//ReplicationBacklog
        'report',//Report
        'reportcategory',//ReportCategory
        'reportentity',//ReportEntity
        'reportlink',//ReportLink
        'reportvisibility',//ReportVisibility
        'resource',//Resource
        'resourcegroup',//ResourceGroup
        'resourcegroupexpansion',//ResourceGroupExpansion
        'resourcespec',//ResourceSpec
        'ribboncommand',//RibbonCommand
        'ribboncontextgroup',//RibbonContextGroup
        'ribboncustomization',//RibbonCustomization
        'ribbondiff',//RibbonDiff
        'ribbonrule',//RibbonRule
        'ribbontabtocommandmap',//RibbonTabToCommandMap
        'role',//Role
        'roleprivileges',//RolePrivileges
        'roletemplate',//RoleTemplate
        'roletemplateprivileges',//RoleTemplatePrivileges
        'rollupfield',//RollupField
        'rollupjob',//RollupJob
        'rollupproperties',//RollupProperties
        'routingrule',//RoutingRule
        'routingruleitem',//RoutingRuleItem
        'salesliterature',//SalesLiterature
        'salesliteratureitem',//SalesLiteratureItem
        'salesorder',//SalesOrder
        'salesorderdetail',//SalesOrderDetail
        'salesprocessinstance',//SalesProcessInstance
        'savedorginsightsconfiguration',//SavedOrgInsightsConfiguration
        'savedquery',//SavedQuery
        'savedqueryvisualization',//SavedQueryVisualization
        'sdkmessage',//SdkMessage
        'sdkmessagefilter',//SdkMessageFilter
        'sdkmessagepair',//SdkMessagePair
        'sdkmessageprocessingstep',//SdkMessageProcessingStep
        'sdkmessageprocessingstepimage',//SdkMessageProcessingStepImage
        'sdkmessageprocessingstepsecureconfig',//SdkMessageProcessingStepSecureConfig
        'sdkmessagerequest',//SdkMessageRequest
        'sdkmessagerequestfield',//SdkMessageRequestField
        'sdkmessageresponse',//SdkMessageResponse
        'sdkmessageresponsefield',//SdkMessageResponseField
        'semiannualfiscalcalendar',//SemiAnnualFiscalCalendar
        'service',//Service
        'serviceappointment',//ServiceAppointment
        'servicecontractcontacts',//ServiceContractContacts
        'serviceendpoint',//ServiceEndpoint
        'sharepointdata',//SharePointData
        'sharepointdocument',//SharePointDocument
        'sharepointdocumentlocation',//SharePointDocumentLocation
        'sharepointsite',//SharePointSite
        'similarityrule',//SimilarityRule
        'site',//Site
        'sitemap',//SiteMap
        'sla',//SLA
        'slaitem',//SLAItem
        'slakpiinstance',//SLAKPIInstance
        'socialactivity',//SocialActivity
        'socialinsightsconfiguration',//SocialInsightsConfiguration
        'socialprofile',//SocialProfile
        'solution',//Solution
        'solutioncomponent',//SolutionComponent
        'sqlencryptionaudit',//SqlEncryptionAudit
        'statusmap',//StatusMap
        'stringmap',//StringMap
        'subject',//Subject
        'subscription',//Subscription
        'subscriptionclients',//SubscriptionClients
        'subscriptionmanuallytrackedobject',//SubscriptionManuallyTrackedObject
        'subscriptionstatisticsoffline',//SubscriptionStatisticsOffline
        'subscriptionstatisticsoutlook',//SubscriptionStatisticsOutlook
        'subscriptionsyncentryoffline',//SubscriptionSyncEntryOffline
        'subscriptionsyncentryoutlook',//SubscriptionSyncEntryOutlook
        'subscriptionsyncinfo',//SubscriptionSyncInfo
        'subscriptiontrackingdeletedobject',//SubscriptionTrackingDeletedObject
        'syncattributemapping',//SyncAttributeMapping
        'syncattributemappingprofile',//SyncAttributeMappingProfile
        'syncerror',//SyncError
        'systemapplicationmetadata',//SystemApplicationMetadata
        'systemform',//SystemForm
        'systemuser',//SystemUser
        'systemuserbusinessunitentitymap',//SystemUserBusinessUnitEntityMap
        'systemuserlicenses',//SystemUserLicenses
        'systemusermanagermap',//SystemUserManagerMap
        'systemuserprincipals',//SystemUserPrincipals
        'systemuserprofiles',//SystemUserProfiles
        'systemuserroles',//SystemUserRoles
        'systemusersyncmappingprofiles',//SystemUserSyncMappingProfiles
        'task',//Task
        'team',//Team
        'teammembership',//TeamMembership
        'teamprofiles',//TeamProfiles
        'teamroles',//TeamRoles
        'teamsyncattributemappingprofiles',//TeamSyncAttributeMappingProfiles
        'teamtemplate',//TeamTemplate
        'template',//Template
        'territory',//Territory
        'textanalyticsentitymapping',//TextAnalyticsEntityMapping
        'theme',//Theme
        'timestampdatemapping',//TimeStampDateMapping
        'timezonedefinition',//TimeZoneDefinition
        'timezonelocalizedname',//TimeZoneLocalizedName
        'timezonerule',//TimeZoneRule
        'topic',//Topic
        'topichistory',//TopicHistory
        'topicmodel',//TopicModel
        'topicmodelconfiguration',//TopicModelConfiguration
        'topicmodelexecutionhistory',//TopicModelExecutionHistory
        'traceassociation',//TraceAssociation
        'tracelog',//TraceLog
        'traceregarding',//TraceRegarding
        'transactioncurrency',//TransactionCurrency
        'transformationmapping',//TransformationMapping
        'transformationparametermapping',//TransformationParameterMapping
        'unresolvedaddress',//UnresolvedAddress
        'uom',//UoM
        'uomschedule',//UoMSchedule
        'userapplicationmetadata',//UserApplicationMetadata
        'userentityinstancedata',//UserEntityInstanceData
        'userentityuisettings',//UserEntityUISettings
        'userfiscalcalendar',//UserFiscalCalendar
        'userform',//UserForm
        'usermapping',//UserMapping
        'userquery',//UserQuery
        'userqueryvisualization',//UserQueryVisualization
        'usersettings',//UserSettings
        'webresource',//WebResource
        'webwizard',//WebWizard
        'wizardaccessprivilege',//WizardAccessPrivilege
        'wizardpage',//WizardPage
        'workflow',//Workflow
        'workflowdependency',//WorkflowDependency
        'workflowlog',//WorkflowLog
        'workflowwaitsubscription',//WorkflowWaitSubscription
     
        // Кастомные объекты
        'new_autonumber',
    ];
    
    function isRemoveItems() {
        var select = $("#slctPrimaryEntity");
        if (select.length > 0) {
            for(var i = 0; i < entities.length; i++)
                $("#slctPrimaryEntity option[value='" + entities[i] + "']").remove();
        }
    
        return false;
    }
    
    • Здесь у нас вначале задается массив объектов, которые надо скрыть. Каждое значение из этого списка должно соответствовать DOM-овской опции из Расширенного поиска (атрибут Value тэга Option).
    • Далее идет основная функция, которая проходится по массиву объектов и если находит соответствующую опцию в ниспадающем списке с объектами в Расширенном поиске, то удаляет ее.
    • И напоследок мы возвращаем false, чтобы кнопка не отображалась.
  • Добавьте на Application Ribbon кнопку. Разместите ее в разделе Mscrm.AdvancedFind.Groups.Show.Controls._children. В качестве Enable Rule задайте функцию isRemoveItems из созданного JS Веб-ресурса.
    В целом XML будет примерно таким:

    <RibbonDiffXml xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <CustomActions>
        <CustomAction Id="new.ApplicationRibbon.RemoveItems.Button.CustomAction" Location="Mscrm.AdvancedFind.Groups.Show.Controls._children" Sequence="35">
          <CommandUIDefinition>
            <Button Alt="$LocLabels:new.ApplicationRibbon.RemoveItems.Button.Alt" Command="new.ApplicationRibbon.Command.RemoveItems" Id="new.ApplicationRibbon.RemoveItems.Button" LabelText="$LocLabels:new.ApplicationRibbon.RemoveItems.Button.LabelText" Sequence="35" TemplateAlias="o1" ToolTipTitle="$LocLabels:new.ApplicationRibbon.RemoveItems.Button.ToolTipTitle" ToolTipDescription="$LocLabels:new.ApplicationRibbon.RemoveItems.Button.ToolTipDescription" />
          </CommandUIDefinition>
        </CustomAction>
      </CustomActions>
      <Templates>
        <RibbonTemplates Id="Mscrm.Templates" />
      </Templates>
      <CommandDefinitions>
        <CommandDefinition Id="new.ApplicationRibbon.Command.RemoveItems">
          <EnableRules>
            <EnableRule Id="new.ApplicationRibbon.EnableRule.RemoveItems" />
          </EnableRules>
          <DisplayRules />
          <Actions />
        </CommandDefinition>
      </CommandDefinitions>
      <RuleDefinitions>
        <TabDisplayRules />
        <DisplayRules />
        <EnableRules>
          <EnableRule Id="new.ApplicationRibbon.EnableRule.RemoveItems">
            <CustomRule FunctionName="isRemoveItems" Library="$webresource:new_hideAFe.js" Default="true" />
          </EnableRule>
        </EnableRules>
      </RuleDefinitions>
      <LocLabels>
        <LocLabel Id="new.ApplicationRibbon.RemoveItems.Button.LabelText">
          <Titles>
            <Title description="RemoveItems" languagecode="1049" />
          </Titles>
        </LocLabel>
        <LocLabel Id="new.ApplicationRibbon.RemoveItems.Button.ToolTipTitle">
          <Titles>
            <Title description="RemoveItems" languagecode="1049" />
          </Titles>
        </LocLabel>
        <LocLabel Id="new.ApplicationRibbon.RemoveItems.Button.ToolTipDescription">
          <Titles>
            <Title description="RemoveItems" languagecode="1049" />
          </Titles>
        </LocLabel>
        <LocLabel Id="new.ApplicationRibbon.RemoveItems.Button.Alt">
          <Titles>
            <Title description="RemoveItems" languagecode="1049" />
          </Titles>
        </LocLabel>
      </LocLabels>
    </RibbonDiffXml>
    


Комментарии (0)

*

code