getelementbyid on dynamically created elements not working - php

I am creating an element with this code. Setting the ID as it should be set. (Do I need the validateonparse?):
$sectionContainer = $dom->createElement('div', $section);
$sectionContainer->setAttribute("id", $section);
$sectionContainer->setIdAttribute("id", TRUE);
$dom->validateOnParse = true;
$divup->parentNode->insertBefore($sectionContainer, $divup);
echo 'avant'."</br>";
echo $section;
print_r($dom->getElementById($section)->getAttribute('id'));
echo 'apres'."</br>";
But I get this:
Fatal error: Uncaught Error: Call to a member function getAttribute() on null
So it can't locate the element I just created, why?

Hey_ there,
the problem is not with $dom->validateOnParse = true;.
Your error comes from this line of code - $sectionContainer->setIdAttribute("id", TRUE);.
If you want to set id attribute of DOMElement like <div id="myId"></div> you only need $domElement->setAttribute("id", "myId"); which you already have.
DOMElement::setIdAttribute is actually indicating that this attribute is unique identifier which has nothing to do with the id="myId" attribute
(PHP 5, PHP 7)
DOMElement::setIdAttribute — Declares the attribute
specified by name to be of type ID
Description
public void DOMElement::setIdAttribute ( string $name , bool $isId )
Declares the attribute name to be of type ID.
Well it is not very clear what is type ID, but I can say that it is something different from id attribute of html element.
Check demo HERE

Related

Why i can't use $element as paremeter in the function WebDriverExpectedCondition::elementToBeClickable()?

The $value->click(); method works. But when I use elementToBeClickable($value), the PHP throws the error:
"Fatal error: Uncaught TypeError: Argument 1 passed to Facebook\WebDriver\WebDriverExpectedCondition::elementToBeClickable() must be an instance of Facebook\WebDriver\WebDriverBy, instance of Facebook\WebDriver\Remote\RemoteWebElement given".
Code:
foreach ($submitButtons as $key => $value) {
$action = $this->driver->action();
$action->moveToElement($value)->perform();
try {
$this
->driver
->wait(5)
->until(
WebDriverExpectedCondition::elementToBeClickable($value)
);
} catch (\Exception $e) {
$action->moveToElement($value)->perform();
sleep(5);
}
$value->click();
}
How I can convert the RemoteWebElement object to WebDriverBy? In this case I cannot use a Explicit CSS WebDriverBy, cause its dynamically selected inside the foreach.
Yes, you'd be able to do it as soon as the updates are implemented in the respective binding arts. The recent change in Selenium-Python allows both WebDriverBy as well as RemoteWebElement. Hence the argument have been renamed to mark to indicate that both locator and WebElement args are valid.
As per the latest Python API Docs:
def element_to_be_clickable(mark):
"""
An Expectation for checking an element is visible and enabled such that
you can click it.
element is either a locator (text) or an WebElement
"""
# renamed argument to 'mark', to indicate that both locator
# and WebElement args are valid
def _predicate(driver):
target = mark
if not isinstance(target, WebElement): # if given locator instead of WebElement
target = driver.find_element(*target) # grab element at locator
target = visibility_of(target)(driver)
if target and target.is_enabled():
return target
else:
return False
return _predicate
As well from the blob:
def element_to_be_clickable(mark):
"""
An Expectation for checking an element is visible and enabled such that
you can click it.
element is either a locator (text) or an WebElement
"""
# renamed argument to 'mark', to indicate that both locator
# and WebElement args are valid
def _predicate(driver):
target = mark
if not isinstance(target, WebElement): # if given locator instead of WebElement
target = driver.find_element(*target) # grab element at locator
target = visibility_of(target)(driver)
if target and target.is_enabled():
return target
else:
return False
return _predicate

Get product atribute value in magento

Hi i have got the maximum elements of products using below code but it doesn't show the size attribute of my product, the size attribute is visible on front-end but i cant understand why it is not printing with this code
<?php
ob_start();
session_start();
ini_set('display_errors', 1);
//for order update
include '../../../../app/Mage.php';
Mage::app('default');
echo '<pre>';
if(isset($_REQUEST['productid'])){
$productId = $_REQUEST['productid'];
}else{
$productId = '12402'; // product ID 10 is an actual product, and used here for a test
}
$product = Mage::getModel('catalog/product')->load($productId); //load the product
//$product_id = $product->getId();
//$created_at = $product->getcreated_at();
//$description = $product->getdescription();
//$short_description = $product->getshort_description();
//$sku = $product->getsku();
//$size_fit = $product->getsize_fit();
//$style_ideas = $product->getstyle_ideas();
//$name = $product->getname();
//$price = $product->getprice();
//$stocklevel = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();
If its the size_fit attribute (i'm guessing that because its the only size attempt in your code..) use $product->getSizeFit(). For just size use $product->getSize(). When this is not returning anything, please post the attribute installer if you have one. Mufadall his answer is also correct but judging your code you are just using wrong syntax.
Basicly according to the magic get method the first letter is turned into a capital and all other letters after an underscore.
Ex.: To fetch my_sample_attribute use getMySampleAttribute().
getData('my_sample_attribute') would also be an option but you shouldn't make a habbit of doing that because in some cases, for some attributes getData('attribute') returns a different value then getAttribute()....
$product->getData($attribute_code);
will return you the actual attribute value. For attribute with type dropdown it will return option id
$product->getResource()->getAttribute($attribute_code)->getFrontend()->getValue($product);
will return actual value
You can use this:
$product->getData('Your Attribute ID');
Go to Size attribute and check for Drop Down used in product listing if it set to No then set it to Yes, after that you can get your size attribute with other product attribute
You can use the getters, or getData();
The getter is set in magento with the magic __get() method, and you can use it in the following way:
$product->getDescription() // ( to get description attribute)
$product->getShortDescription() // (to get short_description attribute)
So basically you explode the attribute with underscores, and capitalize the words, and you will get what you need to put after "get".
Here is something very useful I use all the time
Zend_Debug::dump($product->getData());
This gets you all the data you have to work with. If you are missing data, it means it's not loaded.
Good luck!

Codeigniter issue with submitted variables as blank

I have a form :
<?php
$attr = array('id'=>'urlSubmit');
$urlInputAttr = array('name'=>'urlInput','value'=>'yourdomain.com','maxlength'=>'50','size'=>'25');
echo form_open('urlSubmission',$attr);
echo form_input($urlInputAttr);
#echo form_submit('urlInput', '');
echo form_close();
?>
a controller called urlsubmission
$this->load->model('domaincheckmodel');
$this->domaincheckmodel->verifyduplicates($this->input->post('urlInput'));
and a function within a model(domaincheckmodel) which basically checks for duplicate records and inserts a new domain:
function verifyduplicates($tldEntered){
# $_POSTed value of urlInput
## Gather if the domain exists in db
$DupDomains = $this->db->get_where('ClientDomain', array('tld'=>$tldEntered));
if($DupDomains->num_rows() > 0 ){
$this->load->view('err/domainexists'); ##domain already used
}
# else, no domain present, insert.
else{
#array of insert values:
$insertNewDomain = array('tld'=>$this->input->post('urlInput',TRUE));
$this->db->insert('ClientDomain', $insertNewDomain);
$this->load->view('success/domainfree'); ##domain is free and has been entered.
}
}
$this->domaincheckmodel->verifyduplicates($this->input->post('urlInput'));
function verifyduplicates($tldEntered){
# $_POSTed value of urlInput
## Gather if the domain exists in db
$DupDomains = $this->db->get_where('ClientDomain', array('tld'=>$tldEntered));
You're passing from the form to the controller to the model, are you sure the post variable is staying populated? Try the above, capture the post variable in the controller and pass it to the model instead of trying to read it in the model itself?
A little clarification on passing parameters to functions. You can do this via whatever is inside the brackets as follows.
Controller:
$myVariable = $this->someModel->someFunction($someParameter)
Model:
function someFunction($variableIWantToPopulateWithSomeParameter)
So someParameter gets passed from the controller to the function name in the model. There is one thing to be aware of though and that is that model function now EXPECTS a parameter and if you don't give it one, ie you call someFunction() you'll get an error. This can be avoided by giving it a default value like this:
function someFunction($myVariable = 1)
What that is going to do is say if I don't get a value passed to me I am going to make $myVariable equal to one, if I do I'll overwrite 1 with the new value. So if you send two calls to that function this is what you can expect:
//$myVariable is going to be 1, the default.
$this->someModel->someFunction();
//$myVariable is going to be 5, the value passed to it
$this->someModel->someFunction(5);

create attribute set in Magento setup script

Creating attributes and assigning them to existing attribute sets is a solved problem but we are running into an issue trying to create an attribute set and populate it with default and specific attributes is failing. This is the code in use:
$setup->addAttributeSet('catalog_product', 'women_sizing_denim');
$oAttributeSetModel = Mage::getModel("eav/entity_attribute_set")
->load($setup->getAttributeSetId('catalog_product', 'women_sizing_denim'))
->initFromSkeleton($setup->getAttributeSetId('catalog_product', 'default'))
->save();
I can verify by debugging through that the initfromSkeleton method does load the attributes from the default attribute_set as advertised, however after the save(), the new set is empty.
Adding new attributes to the set is possible, so it does exist and is created correctly, but the missing default attributes make it unusable since SKU, price, name, etc are all required.
I remember that the issue with creating attribute sets based on the default attribute set was, that you need to save the attribute set twice, once before calling initSkeleton() and once after it.
I don't remember the exact reason anymore, it's too long ago. Anyway, here's what worked for me:
// Mage_Eav_Model_Entity_Setup
$oEntitySetup = $this;
$oEntitySetup->startSetup();
$sNewSetName = 'myset';
$iCatalogProductEntityTypeId = (int) $oEntitySetup->getEntityTypeId('catalog_product');
$oAttributeset = Mage::getModel('eav/entity_attribute_set')
->setEntityTypeId($iCatalogProductEntityTypeId)
->setAttributeSetName($sNewSetName);
if ($oAttributeset->validate()) {
$oAttributeset
->save()
->initFromSkeleton($iCatalogProductEntityTypeId)
->save();
}
else {
die('Attributeset with name ' . $sNewSetName . ' already exists.');
}
$oEntitySetup->endSetup();
Please notice that setup class needs to extend
Mage_Catalog_Model_Resource_Eav_Mysql4_Setup
so that
$oEntitySetup->getEntityTypeId('catalog_product');
can be called.
I used Jürgen Thelen answer which worked.
But I found the new attribute set did not have default options and options group such as general and invoice etc.
So to get round this include $installer->getAttributeSetId('catalog_product', 'default') in the initFromSkeleton()
if($attributeSet->validate()) {
$attributeSet
->save()
->initFromSkeleton($installer->getAttributeSetId('catalog_product', 'default'))
->save();
} else {
die('Attributeset with name ' . $setName . ' already exists.');
}

Zend_Form set and validate field value manually

I have a Zend_Form with a dropdown field.
When the user sets a value in the url this one should be selected as default value in this dropdown.
So what i do at the moment is this:
$parlang = $this->getRequest()->getParam('lang');
if($parlang){
$this->view->filterForm->getElement('ddLanguage')->setValue($parlang);
}
if ($this->getRequest()->isPost()) {
if($this->view->filterForm->isValid($_POST)){
...
...
...
No i want to check if the value of the variable is even a valid value for the dropdown? How can i check this in coorporation with the form validation. Yes i can check the variable against a array or so but this seems to be "fighting against the framework".
So what is the Zend way to do such a thing?
Edit:
My final solution for all who are interested, is:
$parlang = $this->getRequest()->getParam('lang');
if($parlang){
$ddLanguage = $this->view->filterForm->ddLanguage;
if($ddLanguage->isValid($parlang)){
$ddLanguage->setValue($parlang);
$language = $parlang;
}
}
I ran a quick test and it looks like one method you can use is Zend_Form_Element_Select::getMultiOption() to check if the language exists in the select values.
<?php
$parlang = $this->getRequest()->getParam('lang');
if ($parlang) {
$el = $this->view->filterForm->getElement('ddLanguage');
// attempt to get the option
// Returns null if no such option exists, otherwise returns a
// string with the display value for the option
if ($el->getMultiOption($parlang) !== null) {
$el->setValue($parlang);
}
}
If your Multiselect element contains a list of country, I would just populate a default in your element value according to the one in the URL.
In order to do so, you could create a custom Zend_Form_Element as follow:
class My_Form_Element_SelectCountry extends Zend_Form_Element_Select
{
protected $_translatorDisabled = true;
public function init()
{
$locale = Zend_Registry::get('Zend_Locale');
if (!$locale) {
throw new Exception('No locale set in registry');
}
$countries = Zend_Locale::getTranslationList('territory', $locale, 2);
unset($countries['ZZ']);
// fetch lang parameter and set US if there is no param
$request = Zend_Controller_Front::getInstance()->getRequest();
$lang = $request->getParam('lang', 'US');
// sort your country list
$oldLocale = setlocale(LC_COLLATE, '0');
setlocale(LC_COLLATE, 'en_US');
asort($countries, SORT_LOCALE_STRING);
setlocale(LC_COLLATE, $oldLocale);
// check weither the lang parameter is valid or not and add it to the list
if (isset($countries[$lang])) {
$paramLang = array($lang => $countries[$lang]);
$countries = array_merge($paramLang, $countries);
}
$this->setMultiOptions($countries);
}
}
You get the idea from this custom form.
If what you're trying to do isn't a Multiselect field filled by a country list but a list of language instead, then the logic is the same, you just need to change the call to the static method Zend_Locale::getTranslationList()and grab whatever information you need.
One more thing, if you just want a single element in your Multiselect element, then go for a Zend_Form_Element_Hidden.
It's a lot of "if" but I can't understand how looks like your Multiselect element exactly from your question.
Now let's take a look on the validation side, when you're using a Multiselect element, Zend_Framework automatically adds an InArray validator, which means that you don't have anything to do to check weither the data sent are correct or not. isValid is going to do it for you.
Weither a user let the default parameter and everything will be fine, or he modifies/deletes this parameter and the default parameter (en_US in this case, see code above) is going to be set as a default value for the Multiselect field.
To answer your last question, no it's not against the framework to check a variable set by a user and compare it with an array (from getTranslationList()for example). I would say it's even the recommended way to do things.

Categories