substring extraction in salesforce apex not working how I expected it too - apex-code

So I am trying to auto-populate a subject and comments case field in a salesforce case object based of information that is passed through our description field.
currently we are assuming the structure of said description will look something like this:
“
Subject: test-emailtocase2
Internal Comments: this is second attempt as case trigger
…
“
so far my code for the substring looks like:
c.Subject = c.Description.substringAfter('Subject: ').substringBefore('Internal Comments: ');
c.Comments = c.Description.substringAfter('Internal Comments: ').substringBefore('\n');
the issue i am encountering is that the subject field populates just fine, but for some reason the comments field doesn't populate, and I've tried a couple different configurations.
~to my knowledge I believe my field name references are correct

Dumb question, why not just use carriage returns?
String tempString = 'Subject: test-emailtocase2' + '\n' + 'Internal Comments: this is second attempt as case trigger\n' + '…';
String[] splitup = tempString.split('\n');
String subject = splitup[0].replace('Subject: ', '');
String comments = splitup[1].replace('Internal Comments: ', '');
System.debug(subject);
System.debug(comments);

Related

Create title slug + random string Laravel 7

I would like to create a slug that combines the title + a random string in Laravel.
I tried this, but nothing, in the second case it does nothing but combine the character string with the title.
Str::slug(request('title'), '-', Str::random());
or
Str::slug(request('title'), Str::random());
I would like something like this:
this-is-an-example-title-Jfij4jio4523q234
Double-check the method signature from https://laravel.com/docs/7.x/helpers#method-str-slug (and deeper at https://github.com/laravel/framework/blob/7.x/src/Illuminate/Support/Str.php#L552)
To be explicit, the second parameter of the method is the character used to replace whitespace, and the third parameter refers to the locale to use when generating the slug. That means you need your string to be fully composed before passing it to the method.
Assuming you want your slug joined by a - then something like this is what you want:
$value = request('title') . ' ' . Str::random();
$slug = Str::slug($value); // optionally Str::slug($value, '-'); to explicitly define the join
Str::Slug() has been defined as:
slug(string $title, string $separator = '-', string $language = 'en')
The third param can be seen as language with default value: en.
Str::slug($request->input('title').Str::random(40), '-');
I hope this helps.

Search Query Parameter

I want to search email which contains '+' in it. for example
something like this myemail.subdomain+1#domain.com.
URL - https://example.com?searchKey=myemail.subdomain+1#
I am using Laravel, this parameter is fetched from route using
$request->get('searchKey');
but it's converting '+' to ' ' ,
as a result i am getting
searchKey as myemail.subdomain 1#
which leads to improper result.
Any help?
PHP assumes that + from GET request is a space. Right encoded plus symbol is %2B.
You have to just prepare string from request to save plus symbol:
$searchKey= urlencode(request()->get('searchKey'));
In your case you'll get # as %40. Then you can replace plus with correct code and decode it. But then be careful with usual spaces!
$searchKey = urlencode(request()->get('searchKey'));
$searchKey = urldecode(str_replace('+', '%2B', $searchKey));
https://www.php.net/manual/en/function.urlencode.php
https://www.php.net/manual/en/function.urldecode.php
P.S. I suppose it is not the best soulution, but it should work.
P.P.S. Or, if you can prepare plus as a %2B before it will be at search parameter, do it

String value with double quote in C#

I was trying to do autocomplete for my input box. When user start typing "I, then I should exactly search the keyword what user has typed ("I). When keys pressed, I was getting the string value as "\"I. How can i do the search based on what user has entered without stripping off any character from the string. Pls provide me any suggestion to help my issue.
Sample Code
public JsonResult AutoBibs(string searchTerm)
{
model = (from line in db.BibContents
where (line.Value.StartsWith(searchTerm) || line.Value.Contains(" " + searchTerm))
select new PoDetails
{
BibId = line.BibId
}).ToList();
return model;
}
The " always appends with an Escape character while processing the String variables in C# i.e. it appends "\" at the beginning. It would not change your functionality and you can still continue with your Auto Complete feature. Generally you can find this during in DEBUG mode only.
Read this MSDN article for more details.

XQuery looking for text with 'single' quote

I can't figure out how to search for text containing single quotes using XPATHs.
For example, I've added a quote to the title of this question. The following line
$x("//*[text()='XQuery looking for text with 'single' quote']")
Returns an empty array.
However, if I try the following
$x("//*[text()=\"XQuery looking for text with 'single' quote\"]")
It does return the link for the title of the page, but I would like to be able to accept both single and double quotes in there, so I can't just tailor it for the single/double quote.
You can try it in chrome's or firebug's console on this page.
Here's a hackaround (Thanks Dimitre Novatchev) that will allow me to search for any text in xpaths, whether it contains single or double quotes. Implemented in JS, but could be easily translated to other languages
function cleanStringForXpath(str) {
var parts = str.match(/[^'"]+|['"]/g);
parts = parts.map(function(part){
if (part === "'") {
return '"\'"'; // output "'"
}
if (part === '"') {
return "'\"'"; // output '"'
}
return "'" + part + "'";
});
return "concat(" + parts.join(",") + ")";
}
If I'm looking for I'm reading "Harry Potter" I could do the following
var xpathString = cleanStringForXpath( "I'm reading \"Harry Potter\"" );
$x("//*[text()="+ xpathString +"]");
// The xpath created becomes
// //*[text()=concat('I',"'",'m reading ','"','Harry Potter','"')]
Here's a (much shorter) Java version. It's exactly the same as JavaScript, if you remove type information. Thanks to https://stackoverflow.com/users/1850609/acdcjunior
String escapedText = "concat('"+originalText.replace("'", "', \"'\", '") + "', '')";!
In XPath 2.0 and XQuery 1.0, the delimiter of a string literal can be included in the string literal by doubling it:
let $a := "He said ""I won't"""
or
let $a := 'He said "I can''t"'
The convention is borrowed from SQL.
This is an example:
/*/*[contains(., "'") and contains(., '"') ]/text()
When this XPath expression is applied on the following XML document:
<text>
<t>I'm reading "Harry Potter"</t>
<t>I am reading "Harry Potter"</t>
<t>I am reading 'Harry Potter'</t>
</text>
the wanted, correct result (a single text node) is selected:
I'm reading "Harry Potter"
Here is verification using the XPath Visualizer (A free and open source tool I created 12 years ago, that has taught XPath the fun way to thousands of people):
Your problem may be that you are not able to specify this XPath expression as string in the programming language that you are using -- this isn't an XPath problem but a problem in your knowledge of your programming language.
Additionally, if you were using XQuery, instead of XPath, as the title says, you could also use the xml entities:
"" for double and &apos; for single quotes"
they also work within single quotes
You can do this using a regular expression. For example (as ES6 code):
export function escapeXPathString(str: string): string {
str = str.replace(/'/g, `', "'", '`);
return `concat('${str}', '')`;
}
This replaces all ' in the input string by ', "'", '.
The final , '' is important because concat('string') is an error.
Well I was in the same quest, and after a moment I found that's there is no support in xpath for this, quiet disappointing! But well we can always work around it!
I wanted something simple and straight froward. What I come with is to set your own replacement for the apostrophe, kind of unique code (something you will not encounter in your xml text) , I chose //apos// for example. now you put that in both your xml text and your xpath query . (in case of xml you didn't write always we can replace with replace function of any editor). And now how we do? we search normally with this, retrieve the result, and replace back the //apos// to '.
Bellow some samples from what I was doing: (replace_special_char_xpath() is what you need to make)
function repalce_special_char_xpath($str){
$str = str_replace("//apos//","'",$str);
/*add all replacement here */
return $str;
}
function xml_lang($xml_file,$category,$word,$language){ //path can be relative or absolute
$language = str_replace("-","_",$language);// to replace - with _ to be able to use "en-us", .....
$xml = simplexml_load_file($xml_file);
$xpath_result = $xml->xpath("${category}/def[en_us = '${word}']/${language}");
$result = $xpath_result[0][0];
return repalce_special_char_xpath($result);
}
the text in xml file:
<def>
<en_us>If you don//apos//t know which server, Click here for automatic connection</en_us> <fr_fr>Si vous ne savez pas quelle serveur, Cliquez ici pour une connexion automatique</fr_fr> <ar_sa>إذا لا تعرفوا أي سرفير, إضغطوا هنا من أجل إتصال تلقائي</ar_sa>
</def>
and the call in the php file (generated html):
<span><?php echo xml_lang_body("If you don//apos//t know which server, Click here for automatic connection")?>

CodeIgniter: set_message for max_length[x]

How do you set an error message for max_length and min_length rules. For instance, if I set a rule max_length[6], I'd like the error message to display
Max characters allowed: 5
I got the same problem and even though this post is old, there's no correct answer.. You just have to use the string placeholder %s in second place of your message. In the documentation (http://codeigniter.com/user_guide/libraries/form_validation.html#settingerrors) there is an example for a field not being empty:
$this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
There, it uses the %s placeholder for the name of the field, but if you modify the 'max_length' message putting the field name first and the length second like this:
$this->form_validation->set_message('max_length', 'The field %s max length is %s');
it will work. Is not the best solution, but that one works for me. Hope it helps
application/language/en/en_lang.php I have this:
$lang['name'] = "Name";
$lang['form_required'] = "is required.";
application/language/es/es_lang.php I have this:
$lang['name'] = "Nombre";
$lang['form_required'] = "es requiero.";
application/controllers/yourController.php I have this:
$this->form_validation->set_rules('name', $this->lang->line('name'), 'required|alpha|xss_clean');
$this->form_validation->set_message('required', '%s ' . $this->lang->line('form_required'));
I hope this help!
#Daniel is correct. Per CodeIgniter's documentation, you can override the default error message for any validation rule (such as "min_length", "max_length", etc.) like this:
$this->form_validation->set_message('validation_rule', 'Your message here');
So, in your example you could do:
$this->form_validation->set_message('max_length', 'Max characters allowed: 5');
Simply include that where your validation rules exist.
gAMBOOKa,
create a 'new' rule that also checks for max_length
$this->form_validation->set_rules('username', 'Username', 'required|_max_length[12]');
and for the method..
function _max_length($val)
{
if (strlen($this->input->post('username')) > $val)
{
$this->form_validation->set_message('_max_length', 'Max characters allowed: 5')
return FALSE;
}
return TRUE;
}
add this to your controller as a new rule and set the message like so ---^
CodeIgniter has one of the better documentations out of all the frameworks. Read the userguide on their site or the one in your CI directory.
http://codeigniter.com/user_guide/libraries/form_validation.html#settingerrors
Take a look in system/language/english/form_validation_lang.php and you'll find
$lang['max_length'] = "The %s field can not exceed %s characters in length.";
Which is easily overridden by copying it to
application/language/english/form_validation_lang.php
And changing it to the string you'd like. Do not edit the file in system/ directly, then it'll be overwritten if you upgrade CodeIgniter.
There is no need to add a new method. You may set a custom message to a form validation error by accessing the "max_length" rule as shown below.
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]', array('required' => 'Username is required.','max_length' => 'Max characters allowed: 5')
);
Note: This is also applicable for "min_length" rule.

Resources