What function do I use in a Salesforce apex trigger to trim a text field? - triggers

I'm new to writing apex triggers. I've looked through a lot of the apex developer documentation, and I can't seem to find the combination of functions that I should use to automatically trim characters from a text field.
My org has two text fields on the Case object, which automatically store the email addresses that are included in an email-to-case. The text fields have a 255 character limit each. We are seeing errors pop up because the number of email addresses that these fields contain often exceeds 255 characters.
I need to write a trigger that can trim these text fields to the last ".com" before it hits the 255 character limit.
Perhaps I'm going about this all wrong. Any advice?

You can use replace() function in Apex.
String s1 = 'abcdbca';
String target = 'bc';
String replacement = 'xy';
String s2 = s1.replace(target, replacement);
If you need to use regular expression to find the pattern, then you can use replaceAll()
String s1 = 'a b c 5 xyz';
String regExp = '[a-zA-Z]';
String replacement = '1';
String s2 = s1.replaceAll(regExp, replacement);
For more information please refer Apex Reference Guide

The following code I think that covers what you are searching:
String initialUrl = 'https://stackoverflow.com/questions/69136581/what-function-do-i-use-in-a-salesforce-apex-trigger-to-trim-a-text-field';
Integer comPosition = initialUrl.indexOf('.com');
System.debug(initialUrl.left(comPosition + 4));
//https://stackoverflow.com
The main problems that I see are that other extensions are not covered (like ".net" urls) and that urls that have a ".com" appearing previous to the last one (something like "https://www.comunications.com"). But I think that this covers most of the use cases.

Why not increasing the length of that specific field? Trimming the text might cause data loss or unusable. Just go to object manager find that object and that specific field. Edit field and increase the length.

Related

How do I prevent users to use thousands separator in FileMaker Pro?

In FileMaker Pro, when using number field, the user can choose to use a thousand separator or not. For example, if I have a database with a field for the price of an item, the user can either enter 1,000 or 1000.
I am using my database to generate an XML file that needs to be uploaded. The thing is, that my XML scheme dictates that only a value of 1000 is allowed and not 1,000. Therefore, I want to either automatically remove the comma, or (my preference in this case) alert the user when trying to enter a value with a thousand separator.
What I tried is the following.
For the field, I am setting Validation options. For example:
Require Strict data type: Numeric Only
Validated by calculation: Position ( Self ; ","; 1 ; 1 ) = 0
Validated by calculation: Self = Substitue ( Self, ",", "")
Auto-enter calculation: Filter( Self ; "0123456789." )
Unfortunately, none of these work. As the field is defined as a number (and I want to keep it like this, as I am also performing calculations based on this number), the Position function and the Substitute function apparently ignore the thousand separator!
EDIT:
Note that I am generating my XML by concatenating a string, for example:
"<Products><Product><Name>" & Name & "</Name><Price>" & Price & "</Price></Product></Product>"
The reason is that what I am exporting is dependent on the values in my database. Therefore, I am not using the [File][Export records...] function.
Auto-enter calculation will work, but you need to uncheck the box "Do not replace existing value of field" (which is checked by default).
I'd suggest using the calculation GetAsNumber(self) as the auto-enter calc. If it should only contain integers, wrap that in a call to Int()
I am using my database to generate an XML file that needs to be uploaded. The thing is, that my XML scheme dictates that only a value of 1000 is allowed and not 1,000.
If this is only a problem when you export, why not handle it when exporting?
If you are exporting as XML using XSLT, you can add an instruction to
your stylesheet to remove the comma from all number fields;
Alternatively, you can export from a layout where the field is
formatted to display without the comma and select the Apply current's layout data formatting to exported data option when
exporting.
Added:
Perhaps I should have clarified. I am not using the export function to generate the XML as there is some logic involved in how the XML should be formatted (dependent on the data that I want to export). What I do instead is that I make a string where I combine XML-tags and actual values from the database.
IMHO, you're making a mistake by not taking advantage of the built-in XML/XSLT export option. Any imaginable logic can be implemented this way, without burdening your solution with the fragile task of creating a valid XML.
In any case, if you're using the field in a calculation, you can replace all references to it with:
GetAsNumber (YourField )
to get an unformatted, numeric-only, value.
Your question puzzles me. As far as I know, FileMaker does not store the thousands separator, but rather offers it only as a display option.
That's also why those functions can't find it.
Are you sure you are exporting the raw data and not a "formatted as layout" variant?

Crystal reports select critera with comma delimited

I have a crystal report I need to change the select criteria on. Currently criteria compare's a database field to the parameter I created in the report.
{MaterialCR.MaterialId} = {?MaterialId}
I am now have a field that has comma delimited data in it I need to make sure the parameter includes any of the other ids in the new field.
Materialused has this data in it. "MA0161 ,MA0167" (No double quotes) . This doesn't work
{MaterialCR. MaterialUsed} = {?MaterialId}
I have tried to create a function to compare the two but it does not seem to work. It does not see the parameter as a string array.
My material match function that does not work
Function MaterialMatch (MaterialUsed as string,v1 () As String)
dim MyArray() as string
MyArray = Split (MaterialUsed,"," )
dim Match as boolean
Match = false
dim x as number
For x = 1 To count(v1) Step 1
IF "ALL" in v1 then
Match = true
x = count(MyArray)
end if
if MyArray(x) in v1 then
Match = true
x = count(MyArray)
end if
Next x
MaterialMatch = Match
End Function
This is what the data I am looking at looks like. We have many materials with a Material ID in it. We also have associated time that we need to select. It does not have a material id as it is a many to one situation. I need to retrieve all the records associated with the material including the time. Getting the material with ids is not the issue. I need to get the Time records also. I modified the view this report uses to include the material that overlaps the time. This is where I am stuck.
This is what my select expert formula looks like now. I do know the material used part is wrong.
(
{JobTimeMaterialCR.MaterialId} = {?MaterialId}
or
(
{JobTimeMaterialCR.Type} = "Time"
and
{JobTimeMaterialCR.MaterialUsed} = {?MaterialId}
))
I was able to write a formula that worked for me using the logic I described in my comment. Use this formula as your Record Selection Formula. In Formula Workshop these are found in Selection Formulas > Record Selection.
Local StringVar array values := Split({?Search Values},",");
Local NumberVar indexCount := Count(values);
Local BooleanVar found := false;
Local NumberVar counter;
For counter := 1 to indexCount Step 1 Do
(
If InStr({ARINVT.DESCRIP}, values[counter]) > 0 Then
found := true
);
found;
It's rough, but a good start. The search is case sensitive, so you may need to tweak it with some Lower() functions if you want case insensitive searches. Also, if there is a space between the delim character and the search string in your CSV string, then the space is included in the search. A Replace() function can help you get around this, but that would prevent you from using spaces in the search strings. If you need to use spaces in searches, then just take care when building your CSV String that there are no spaces before or after the comma that is your delim character.
If you need any help understanding the syntax of my formula feel free to comment and I will answer any questions.
I used a parameter field called {?Search Values} to simulate the CSV string data. {ARINVT.DESCRIP} is a field name from my test database I used to search thousands of records for key words I typed into my parameter field. You will want to replace these field names in the formula with your field names and you should be able to get this working without much trouble.

(Vba) Ms Word: Work around the 255 characters limit

I'm new to programming and I'm trying to copy the content of a form field to another form field in the same Word document like this:
Sub Copyfield()
Dim Temp As String
Temp = ActiveDocument.FormFields("Field1").Result
ActiveDocument.FormFields("Field2").Result = Temp
End Sub
My problem is that my "Field1" is a piece of text of more than 255 characters which seems to be a problem with "Result". I know there is a very similar topic here: Passing MS-Access string >255 characters to MS-Word field but I still don't have the 50 reputation to comment on that thread.
Could anyone please help me understand how to implement the changes in my code?
Well, here's one possibility. Since I don't have your environment it was easier for me to test text in the document rather than another form field with so much content. You'll need to adjust the code accordingly.
The key is to get the Selection "inside" the form field so that it doesn't hit the "protection barrier". Just using FormField.Select puts the focus at the beginning of the field, which VBA is seeing as "protected". Moving one character to the right corrects that and long text can then be assigned to the Selection. But the field needs to have content.
So what my code is doing is "slicing off" the first word of the text to go into the form field. That's short enough to assign to the Result property and lets the Selection move to its right. Then the rest - the long text - can be assigned to the Selection.
You'll probably want to assign the entire FormField.Result to a string variable, then manipulate that string.
Sub WriteLongTextToFormField()
Dim ffld As word.FormField
Dim doc As word.Document
Dim rng As word.Range
Dim s1 As String, s2 As String
Set doc = ActiveDocument
'Get the long text
Set rng = doc.Range(doc.Paragraphs(1).Range.Start, doc.Paragraphs(6).Range.End)
'Split off a bit to go into FormField.Result
s1 = rng.Words(1)
rng.MoveStart wdWord, 1
'The rest of the long text, to be assigned to Selection.Text
s2 = rng.Text
Set ffld = doc.FormFields("Text1")
ffld.result = s1
ffld.Select
Selection.MoveRight wdCharacter, 1
Selection.Text = s2
End Sub
Ok, after 3 days at the border of madness, finally thanks to the help of #Cindy Meister (and some serious personal digging), I made it work. Maybe it's not a big deal for you geniouses out there but believe me for me it was like seeing everything in Matrix code (from the movie guys, the movie).
I want to post it and share because I tried to find it in every corner of our Internet and part of the extraterrestrial one and I couldn't. So hopefully it will be useful for another programming illiterate / dumb person (as myself).
Here is the code:
Sub CopyField()
Dim ffld As Word.FormField
Dim doc As Word.Document
Dim rng As String
Dim s1 As String, s2 As String
Set doc = ActiveDocument
'Get the long text
rng = ActiveDocument.FormFields("Field1").Result
'Split off a bit to go into FormField.Result
s1 = Left(rng, 4) 'Keeps the first 4 characters of the rng string starting from left to right this can be adapted
'The rest of the long text, to be assigned to Selection.Text
s2 = Mid(rng, 5) 'Starting from the 5th character from the left keeps the rest of the string
Set ffld = doc.FormFields("Field2")
ffld.Result = s1
ffld.Select
Selection.MoveRight wdCharacter, 1
ActiveDocument.Unprotect 'Unprotects the document!
Selection.Text = s2
ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True 'Protects the document again!
ActiveDocument.Bookmarks("Field1").Select ' "Sends cursor" back to Field1
End Sub
Big part of the code is originally by #Cindy Meister... I just adapted it to my situation where I had 2 form fields instead of paragraphs. I also had to add some lines to unprotect the document at a certain point in order to make it work (ask the Pros for the reason) and a final instruction to come back to "Field1" (which is some pages up) after the process. Finally just a note for my dumb fellows: I added the macro "on exit" on the "Field1" properties to automatize the process.
Huge thanks Cindy again and I hope you help in my dark programming moments again ! (please do)
:)

Query string parsing as number when it should be a string

I am trying to send a search input to a REST service. In some cases the form input is a long string of numbers (example: 1234567890000000000123456789). I am getting 500 error, and it looks like something is trying the convert the string to a number. The data type for the source database is a string.
Is there something that can be done in building the query string that will force the input to be interpreted as a string?
The service is an implementation of ArcGIS server.
More information on this issue per request.
To test, I have been using a client form provided with the service installation (see illustration below).
I have attempted to add single and double quotes, plus wildcard characters in the form entry. The form submission does not error, but no results are found. If I shorten the number("1234"), or add some alpha numeric characters ("1234A"), the form submission does not error.
The problem surfaced after a recent upgrade to 10.1. I have looked for information that would tie this to a known problem, but not found anything yet.
In terms of forcing the input to be interpreted as a string, you enclose the input in single quotes (e.g., '1234567890000000000123456789'). Though if you are querying a field of type string then you need to enclose all search strings in single quotes, and in that case none of your queries should be working. So it's a little hard to tell from the information you've provided what exactly you are doing and what might be going wrong. Can you provide more detail and/or code? Are you formatting a where clause that you are using in a Query object via one of Esri's client side API's (such as the JavaScript API)? In that case, for fields of data type string you definitely need to enclose the search text in single quotes. For example if the field you are querying were called 'FIELD', this is how you'd format the where clause:
FIELD = '1234'
or
FIELD Like '1234%'
for a wildcard search. If you are trying to enter query criteria directly into the Query form of a published ArcGIS Server service/layer, then there too you need to enclose the search in single quotes, as in the above examples.
According to an Esri help technician, this is known bug.

JQuery Wildcard for using atttributes in selectors

I've research this topic extensibly and I'm asking as a last resort before assuming that there is no wildcard for what I want to do.
I need to pull up all the text input elements from the document and add it to an array. However, I only want to add the input elements that have an id.
I know you can use the \S* wildcard when using an id selector such as $(#\S*), however I can't use this because I need to filter the results by text type only as well, so I searching by attribute.
I currently have this:
values_inputs = $("input[type='text'][id^='a']");
This works how I want it to but it brings back only the text input elements that start with an 'a'. I want to get all the text input elements with an 'id' of anything.
I can't use:
values_inputs = $("input[type='text'][id^='']"); //or
values_inputs = $("input[type='text'][id^='*']"); //or
values_inputs = $("input[type='text'][id^='\\S*']"); //or
values_inputs = $("input[type='text'][id^=\\S*]");
//I either get no values returned or a syntax error for these
I guess I'm just looking for the equivalent of * in SQL for JQuery attribute selectors.
Is there no such thing, or am I just approaching this problem the wrong way?
Actually, it's quite simple:
var values_inputs = $("input[type=text][id]");
Your logic is a bit ambiguous. I believe you don't want elements with any id, but rather elements where id does not equal an empty string. Use this.
values_inputs = $("input[type='text']")
.filter(function() {
return this.id != '';
});
Try changing your selector to:
$("input[type='text'][id]")
I figured out another way to use wild cards very simply. This helped me a lot so I thought I'd share it.
You can use attribute wildcards in the selectors in the following way to emulate the use of '*'. Let's say you have dynamically generated form in which elements are created with the same naming convention except for dynamically changing digits representing the index:
id='part_x_name' //where x represents a digit
If you want to retrieve only the text input ones that have certain parts of the id name and element type you can do the following:
var inputs = $("input[type='text'][id^='part_'][id$='_name']");
and voila, it will retrieve all the text input elements that have "part_" in the beginning of the id string and "_name" at the end of the string. If you have something like
id='part_x_name_y' // again x and y representing digits
you could do:
var inputs = $("input[type='text'][id^='part_'][id*='_name_']"); //the *= operator means that it will retrieve this part of the string from anywhere where it appears in the string.
Depending on what the names of other id's are it may start to get a little trickier if other element id's have similar naming conventions in your document. You may have to get a little more creative in specifying your wildcards. In most common cases this will be enough to get what you need.