Magento checkmaxlenght for text attributes - magento

I need to limit text field length for an attribute ("inspiration") similar as for meta_description. I have tried copying the code block in Attributes.php (\app\code\core\Mage\Adminhtml\Block\Catalog\Product\Edit\Tab):
if ($form->getElement('meta_description')) {
$form->getElement('meta_description')->setOnkeyup('checkMaxLength(this, 255);');
}
and replacing "meta_description" with "inspiration", but it doesn't work. Could anyone please help me on this?

Hard to say because you don't define "doesn't work" precisely.
My guess would be, that the <form> containing your inspiration input field is some custom template and doesn't contain the needed JavaScript method checkMaxLength()*.
function checkMaxLength(Object, MaxLen)
{
if (Object.value.length > MaxLen-1) {
Object.value = Object.value.substr(0, MaxLen);
}
return 1;
}
* which is usually only defined in app/design/adminhtml/default/default/template/catalog/product/edit.phtml

Seach for the phtml who build this part of code and make it with jQuery.

Related

Oracle Apex Force Upper Case first Letter.

I Guys
In forms I use,
onKeyUp="this.value = this.value.toUpperCase()"
To force upper-case. However for such as name fields. How do you force the upper letter to be upper-case only while the user is typing. I know INITCAP will do that but need to do as user is typing, if that makes sense.
Any help will be much appreciated.
This is a javascript question then, not and Oracle or APEX question. It shouldn't make any difference what the environment is as long as you have access to the DOM events with javascript functions. e.g. http://www.w3schools.com/jsref/event_onkeyup.asp
If you do a search there are lots of examples to Initcap a string in javascript, just pass in the string and reset the item in the dom e.g.
function capitalizeEachWord(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
I tried to solve this problem.
For that I created JavaScript function which check first letter capital ,if not then it display alert and revert text.
please check following code for text item:
function checkUpper()
{
var x = $x("P6_TEXT");
if (x.value.trim().substring(0,1) != x.value.trim().substring(0,1).toUpperCase()) {
alert ('First letter Must be in upper case');
x.value = x.value.trim().substring(0,x.value.trim().length-1).toString();
}
}
And set item P6_TEXT attribute as
onKeyUp="checkUpper();"
In the field custom attributes put this JS code:
onKeyUp="this.value = this.value.substring(0,1).toUpperCase()+this.value.substring(1).toLowerCase();"
You could use content modifiers from Universal Theme https://apex.oracle.com/pls/apex/apex_pm/r/ut/content-modifiers
I needed text in a page item to be uppercase and under Advanced I set the css classe to
u-textUpper
u-textInitCap - Sets The First Letter In Each Word To Use Uppercase

Validate file extensions in Apex

End user can upload files in a Visualforce page. In the backend I need to create a list of allowed file extensions, and restrict the user to that list. How do I create the extensions list and validate it? Any help is very much appreciated.
You don't need apex for that?
<apex:inputFile> has accept parameter which you can use. Bear in mind this will check contentType, not extension (which is bit more proper way to do it).
If you still want the validation in apex - probably something like this?
String fileName = 'foobar.xls';
Set<String> acceptedExtensions = new Set<String> {'.doc','.txt', '.jpg'};
Boolean found = false;
for(String s : acceptedExtensions){
if(found = fileName.endsWith(s)){ // yes, there's only one "=", I do want assignment here
break;
}
}
if(!found){ // after the whole loop it's still false?
ApexPages.addMessage(...);
}

How to prevent CKEditor replacing spaces with ?

I'm facing an issue with CKEditor 4, I need to have an output without any html entity so I added config.entities = false; in my config, but some appear when
an inline tag is inserted: the space before is replaced with
text is pasted: every space is replaced with even with config.forcePasteAsPlainText = true;
You can check that on any demo by typing
test test
eg.
Do you know how I can prevent this behaviour?
Thanks!
Based on Reinmars accepted answer and the Entities plugin I created a small plugin with an HTML filter which removes redundant entities. The regular expression could be improved to suit other situations, so please edit this answer.
/*
* Remove entities which were inserted ie. when removing a space and
* immediately inputting a space.
*
* NB: We could also set config.basicEntities to false, but this is stongly
* adviced against since this also does not turn ie. < into <.
* #link http://stackoverflow.com/a/16468264/328272
*
* Based on StackOverflow answer.
* #link http://stackoverflow.com/a/14549010/328272
*/
CKEDITOR.plugins.add('removeRedundantNBSP', {
afterInit: function(editor) {
var config = editor.config,
dataProcessor = editor.dataProcessor,
htmlFilter = dataProcessor && dataProcessor.htmlFilter;
if (htmlFilter) {
htmlFilter.addRules({
text: function(text) {
return text.replace(/(\w) /g, '$1 ');
}
}, {
applyToAll: true,
excludeNestedEditable: true
});
}
}
});
These entities:
// Base HTML entities.
var htmlbase = 'nbsp,gt,lt,amp';
Are an exception. To get rid of them you can set basicEntities: false. But as docs mention this is an insecure setting. So if you only want to remove , then I should just use regexp on output data (e.g. by adding listener for #getData) or, if you want to be more precise, add your own rule to htmlFilter just like entities plugin does here.
Remove all but not <tag> </tag> with Javascript Regexp
This is especially helpful with CKEditor as it creates lines like <p> </p>, which you might want to keep.
Background: I first tried to make a one-liner Javascript using lookaround assertions. It seems you can't chain them, at least not yet. My first approach was unsuccesful:
return text.replace(/(?<!\>) (?!<\/)/gi, " ")
// Removes but not <p> </p>
// It works, but does not remove `<p> blah </p>`.
Here is my updated working one-liner code:
return text.replace(/(?<!\>\s.)( (?!<\/)|(?<!\>) <\/p>)/gi, " ")
This works as intended. You can test it here.
However, this is a shady practise as lookarounds are not fully supported by some browsers.
Read more about Assertions.
What I ended up using in my production code:
I ended up doing a bit hacky approach with multiple replace(). This should work on all browsers.
.trim() // Remove whitespaces
.replace(/\u00a0/g, " ") // Remove unicode non-breaking space
.replace(/((<\w+>)\s*( )\s*(<\/\w+>))/gi, "$2<!--BOOM-->$4") // Replace empty nbsp tags with BOOM
.replace(/ /gi, " ") // remove all
.replace(/((<\w+>)\s*(<!--BOOM-->)\s*(<\/\w+>))/gi, "$2 $4") // Replace BOOM back to empty tags
If you have a better suggestion, I would be happy to hear 😊.
I needed to change the regular expression Imeus sent, in my case, I use TYPO3 and needed to edit the backend editor. This one didn't work. Maybe it can help another one that has the same problem :)
return text.replace(/ /g, ' ');

How can I check if some text exist or not in the page using Selenium?

I'm using Selenium WebDriver, how can I check if some text exist or not in the page? Maybe someone recommend me useful resources where I can read about it. Thanks
With XPath, it's not that hard. Simply search for all elements containing the given text:
List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + text + "')]"));
Assert.assertTrue("Text not found!", list.size() > 0);
The official documentation is not very supportive with tasks like this, but it is the basic tool nonetheless.
The JavaDocs are greater, but it takes some time to get through everything useful and unuseful.
To learn XPath, just follow the internet. The spec is also a surprisingly good read.
EDIT:
Or, if you don't want your Implicit Wait to make the above code wait for the text to appear, you can do something in the way of this:
String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));
This will help you to check whether required text is there in webpage or not.
driver.getPageSource().contains("Text which you looking for");
You could retrieve the body text of the whole page like this:
bodyText = self.driver.find_element_by_tag_name('body').text
then use an assert to check it like this:
self.assertTrue("the text you want to check for" in bodyText)
Of course, you can be specific and retrieve a specific DOM element's text and then check that instead of retrieving the whole page.
There is no verifyTextPresent in Selenium 2 webdriver, so you've to check for the text within the page source. See some practical examples below.
Python
In Python driver you can write the following function:
def is_text_present(self, text):
return str(text) in self.driver.page_source
then use it as:
try: self.is_text_present("Some text.")
except AssertionError as e: self.verificationErrors.append(str(e))
To use regular expression, try:
def is_regex_text_present(self, text = "(?i)Example|Lorem|ipsum"):
self.assertRegex(self.driver.page_source, text)
return True
See: FooTest.py file for full example.
Or check below few other alternatives:
self.assertRegexpMatches(self.driver.find_element_by_xpath("html/body/div[1]/div[2]/div/div[1]/label").text, r"^[\s\S]*Weather[\s\S]*$")
assert "Weather" in self.driver.find_element_by_css_selector("div.classname1.classname2>div.clearfix>label").text
Source: Another way to check (assert) if text exists using Selenium Python
Java
In Java the following function:
public void verifyTextPresent(String value)
{
driver.PageSource.Contains(value);
}
and the usage would be:
try
{
Assert.IsTrue(verifyTextPresent("Selenium Wiki"));
Console.WriteLine("Selenium Wiki test is present on the home page");
}
catch (Exception)
{
Console.WriteLine("Selenium Wiki test is not present on the home page");
}
Source: Using verifyTextPresent in Selenium 2 Webdriver
Behat
For Behat, you can use Mink extension. It has the following methods defined in MinkContext.php:
/**
* Checks, that page doesn't contain text matching specified pattern
* Example: Then I should see text matching "Bruce Wayne, the vigilante"
* Example: And I should not see "Bruce Wayne, the vigilante"
*
* #Then /^(?:|I )should not see text matching (?P<pattern>"(?:[^"]|\\")*")$/
*/
public function assertPageNotMatchesText($pattern)
{
$this->assertSession()->pageTextNotMatches($this->fixStepArgument($pattern));
}
/**
* Checks, that HTML response contains specified string
* Example: Then the response should contain "Batman is the hero Gotham deserves."
* Example: And the response should contain "Batman is the hero Gotham deserves."
*
* #Then /^the response should contain "(?P<text>(?:[^"]|\\")*)"$/
*/
public function assertResponseContains($text)
{
$this->assertSession()->responseContains($this->fixStepArgument($text));
}
In c# this code will help you to check whether required text is there in webpage or not.
Assert.IsTrue(driver.PageSource.Contains("Type your text here"));
You can check for text in your page source as follow:
Assert.IsTrue(driver.PageSource.Contains("Your Text Here"))
In python, you can simply check as follow:
# on your `setUp` definition.
from selenium import webdriver
self.selenium = webdriver.Firefox()
self.assertTrue('your text' in self.selenium.page_source)
Python:
driver.get(url)
content=driver.page_source
if content.find("text_to_search"):
print("text is present in the webpage")
Download the html page and use find()
boolean Error = driver.getPageSource().contains("Your username or password was incorrect.");
if (Error == true)
{
System.out.print("Login unsuccessful");
}
else
{
System.out.print("Login successful");
}
JUnit+Webdriver
assertEquals(driver.findElement(By.xpath("//this/is/the/xpath/location/where/the/text/sits".getText(),"insert the text you're expecting to see here");
If in the event your expected text doesn't match the xpath text, webdriver will tell you what the actual text was vs what you were expecting.
string_website.py
search string in webpage
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
browser.get("https://www.python.org/")
content=browser.page_source
result = content.find('integrate systems')
print ("Substring found at index:", result )
if (result != -1):
print("Webpage OK")
else: print("Webpage NOT OK")
#print(content)
browser.close()
run
python test_website.py
Substring found at index: 26722
Webpage OK
d:\tools>python test_website.py
Substring found at index: -1 ; -1 means nothing found
Webpage NOT OK
You can check a source code if the text exists:
source_code = driver.page_source
if "Im not a Robot" not in source_code:

Pulling Images from rss/atom feeds using magpie rss

Im using php and magpie and would like a general way of detecting images in feed item. I know some websites place images within the enclosure tag, others like this images[rss] and some simply add it to description. Is there any one with a general function for detecting if rss item has image and extracting image url after its been parsed by magpie?
i think reqular expressions would be needed to extract from description but im a noob at those. Please help if you can.
I spent ages searching for a way of displaying images in RSS via Magpie myself, and in the end I had to examine the code to figure out how to get it to work.
Like you say, the reason Magpie doesn't pick up images in the element is because they are specified using the 'enclosure' tag, which is an empty tag where the information is in the attributes, e.g.
<enclosure url="http://www.mysite.com/myphoto.jpg" length="14478" type="image/jpeg" />
As a hack to get it to work quickly for me I added the following lines of code into rss_parse.inc:
function feed_start_element($p, $element, &$attrs) {
...
if ( $el == 'channel' )
{
$this->inchannel = true;
}
...
// START EDIT - add this elseif condition to the if ($el=xxx) statement.
// Checks if element is enclosure tag, and if so store the attribute values
elseif ($el == 'enclosure' ) {
if ( isset($attrs['url']) ) {
$this->current_item['enclosure_url'] = $attrs['url'];
$this->current_item['enclosure_type'] = $attrs['type'];
$this->current_item['enclosure_length'] = $attrs['length'];
}
}
// END EDIT
...
}
The url to the image is in $myRSSitem['enclosure_url'] and the size is in $myRSSitem['enclosure_length'].
Note that enclosure tags can refer to many types of media, so first check if the type is actually an image by checking $myRSSitem['enclosure_type'].
Maybe someone else has a better suggestion and I'm sure this could be done more elegantly to pick up attributes from other empty tags, but I needed a v quick fix (deadline pressures) but I hope this might help someone else in difficulty!

Resources