Magento attributes import php gives internal server error - php

I've been looking for an extension or php of some sort to export and import my attributes. Because of website moving to another server, this is needed. I have a lot of attributes and I'm not willing to do it by hand.
I've seen this post and used the code:
Source: https://magento.stackexchange.com/questions/11520/how-to-export-and-import-all-attributes-and-attribute-sets-from-one-magento-to-o <- credits to this guy!
Code export attributes:
<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
Mage::app();
$entity_type_id = Mage::getModel('catalog/product')->getResource()->getTypeId();
prepareCollection($entity_type_id);
function prepareCollection($ent_type_id){
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_read');
$select_attribs = $connection->select()
->from(array('ea'=>$resource->getTableName('eav/attribute')))
->join(array('c_ea'=>$resource->getTableName('catalog/eav_attribute')), 'ea.attribute_id = c_ea.attribute_id');
// ->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
// ->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
$select_prod_attribs = $select_attribs->where('ea.entity_type_id = '.$ent_type_id)
->order('ea.attribute_id ASC');
$product_attributes = $connection->fetchAll($select_prod_attribs);
$select_attrib_option = $select_attribs
->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
->order('e_ao.attribute_id ASC');
$product_attribute_options = $connection->fetchAll($select_attrib_option);
$attributesCollection = mergeCollections($product_attributes, $product_attribute_options);
prepareCsv($attributesCollection);
}
function mergeCollections($product_attributes, $product_attribute_options){
foreach($product_attributes as $key => $_prodAttrib){
$values = array();
$attribId = $_prodAttrib['attribute_id'];
foreach($product_attribute_options as $pao){
if($pao['attribute_id'] == $attribId){
$values[] = $pao['value'];
}
}
if(count($values) > 0){
$values = implode(";", $values);
$product_attributes[$key]['_options'] = $values;
}
else{
$product_attributes[$key]['_options'] = "";
}
/*
temp
*/
$product_attributes[$key]['attribute_code'] = $product_attributes[$key]['attribute_code'];
}
return $product_attributes;
}
function prepareCsv($attributesCollection, $filename = "importAttrib.csv", $delimiter = '|', $enclosure = '"'){
$f = fopen('php://memory', 'w');
$first = true;
foreach ($attributesCollection as $line) {
if($first){
$titles = array();
foreach($line as $field => $val){
$titles[] = $field;
}
fputcsv($f, $titles, $delimiter, $enclosure);
$first = false;
}
fputcsv($f, $line, $delimiter, $enclosure);
}
fseek($f, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="'.$filename.'"');
fpassthru($f);
}
Code import attributes:
<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/../app/Mage.php';
Mage::app();
// $fileName = MAGENTO . '/var/import/importAttrib.csv';
$fileName = 'importAttrib.csv';
// getCsv($fileName);
getAttributeCsv($fileName);
function getAttributeCsv($fileName){
// $csv = array_map("str_getcsv", file($fileName,FILE_SKIP_EMPTY_LINES));
$file = fopen($fileName,"r");
while(!feof($file)){
$csv[] = fgetcsv($file, 0, '|');
}
$keys = array_shift($csv);
foreach ($csv as $i=>$row) {
$csv[$i] = array_combine($keys, $row);
}
foreach($csv as $row){
$labelText = $row['frontend_label'];
$attributeCode = $row['attribute_code'];
if($row['_options'] != "")
$options = explode(";", $row['_options']); // add this to createAttribute parameters and call "addAttributeValue" function.
else
$options = -1;
if($row['apply_to'] != "")
$productTypes = explode(",", $row['apply_to']);
else
$productTypes = -1;
unset($row['frontend_label'], $row['attribute_code'], $row['_options'], $row['apply_to'], $row['attribute_id'], $row['entity_type_id'], $row['search_weight']);
createAttribute($labelText, $attributeCode, $row, $productTypes, -1, $options);
}
}
/**
* Create an attribute.
*
* For reference, see Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
*
* #return int|false
*/
function createAttribute($labelText, $attributeCode, $values = -1, $productTypes = -1, $setInfo = -1, $options = -1)
{
$labelText = trim($labelText);
$attributeCode = trim($attributeCode);
if($labelText == '' || $attributeCode == '')
{
echo "Can't import the attribute with an empty label or code. LABEL= [$labelText] CODE= [$attributeCode]"."<br/>";
return false;
}
if($values === -1)
$values = array();
if($productTypes === -1)
$productTypes = array();
if($setInfo !== -1 && (isset($setInfo['SetID']) == false || isset($setInfo['GroupID']) == false))
{
echo "Please provide both the set-ID and the group-ID of the attribute-set if you'd like to subscribe to one."."<br/>";
return false;
}
echo "Creating attribute [$labelText] with code [$attributeCode]."."<br/>";
//>>>> Build the data structure that will define the attribute. See
// Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
$data = array(
'is_global' => '0',
'frontend_input' => 'text',
'default_value_text' => '',
'default_value_yesno' => '0',
'default_value_date' => '',
'default_value_textarea' => '',
'is_unique' => '0',
'is_required' => '0',
'frontend_class' => '',
'is_searchable' => '1',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '0',
'used_in_product_listing' => '0',
'used_for_sort_by' => '0',
'is_configurable' => '0',
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'backend_type' => 'varchar',
'default_value' => '',
'is_user_defined' => '0',
'is_visible' => '1',
'is_used_for_price_rules' => '0',
'position' => '0',
'is_wysiwyg_enabled' => '0',
'backend_model' => '',
'attribute_model' => '',
'backend_table' => '',
'frontend_model' => '',
'source_model' => '',
'note' => '',
'frontend_input_renderer' => '',
);
// Now, overlay the incoming values on to the defaults.
foreach($values as $key => $newValue)
if(isset($data[$key]) == false)
{
echo "Attribute feature [$key] is not valid."."<br/>";
return false;
}
else
$data[$key] = $newValue;
// Valid product types: simple, grouped, configurable, virtual, bundle, downloadable, giftcard
$data['apply_to'] = $productTypes;
$data['attribute_code'] = $attributeCode;
$data['frontend_label'] = array(
0 => $labelText,
1 => '',
3 => '',
2 => '',
4 => '',
);
//<<<<
//>>>> Build the model.
$model = Mage::getModel('catalog/resource_eav_attribute');
$model->addData($data);
if($setInfo !== -1)
{
$model->setAttributeSetId($setInfo['SetID']);
$model->setAttributeGroupId($setInfo['GroupID']);
}
$entityTypeID = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
$model->setEntityTypeId($entityTypeID);
$model->setIsUserDefined(1);
//<<<<
// Save.
try
{
$model->save();
}
catch(Exception $ex)
{
echo "Attribute [$labelText] could not be saved: " . $ex->getMessage()."<br/>";
return false;
}
if(is_array($options)){
foreach($options as $_opt){
addAttributeValue($attributeCode, $_opt);
}
}
$id = $model->getId();
echo "Attribute [$labelText] has been saved as ID ($id).<br/>";
// return $id;
}
function addAttributeValue($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
if(!attributeValueExists($arg_attribute, $arg_value))
{
$value['option'] = array($arg_value,$arg_value);
$result = array('value' => $value);
$attribute->setData('option',$result);
$attribute->save();
}
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
function attributeValueExists($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
The import code doesn't work. It returns a 500 Internal Server error. Is there anything I miss in the import code? And if not, do you have a suggestion for me?
If any more information needed, feel free to ask.
Thanks in advance!

How long does it take until the 500 appears?
If your PHP runs under CGI and the activityTimeout is below the max_execution_time (e.g. you set max_execution_time to 1200 via ini_set or htaccess and CGIs activityTimeout is just 40 by default) it will throw a 500 instead of a PHP-error. It allways acts like that if CGIs settings are lower tha the PHP ones (memory, maxrequests, timeout, etc.)
A real misconfiguration 500 (e.g. php.ini or .htaccess) would appear just in time on startup, not only when yous script starts/runs.

Related

How to repeat fuction in php?

Is it possible to repeat a function when it has finished. For Example: I have a function for export mysql to json file with a limit of 100 data. if it is successful create a json file with 100 data. Then it will repeat the same function to create json file 100 more data (no duplicate data) until the data runs out.
my code for generate json file :
$results = $db->SELECT()
->FROM( array( 'MM'=>'M_MEMBER'),
array( 'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS'
)
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT(100)
->QUERY()->FETCHALL();
if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
{
$counter = formatNbr($counterFile);
$data = array();
foreach ($results as $key=>$row) {
$data[$key] = $row;
$data[$key]['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$out = array_values($data);
$jsonAr = json_encode($out);
$json = substr($jsonAr, 1, -1);
$jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
$file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
$createJson = file_put_contents($file, $jsonData);
if($createJson){
echo "Create Json File Success In :".$file;
}else{
echo "Create Json Failed";
}
}
the code can only generate a json file once, how can it be repeated after generating a successful json file
note: I added a flag for each successful data generated json file
You can extract your codes to a function and use the function in the loop.
Example:
function exporter($limit = 100)
{
$results = $db->SELECT()
->FROM( array( 'MM'=>'M_MEMBER'),
array( 'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS'
)
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT($limit)
->QUERY()->FETCHALL();
if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
{
$counter = formatNbr($counterFile);
$data = array();
foreach ($results as $key=>$row) {
$data[$key] = $row;
$data[$key]['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$out = array_values($data);
$jsonAr = json_encode($out);
$json = substr($jsonAr, 1, -1);
$jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
$file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
$createJson = file_put_contents($file, $jsonData);
if($createJson) {
echo "Create Json File Success In :".$file;
} else {
echo "Create Json Failed";
}
}
$numberOfRows = 10000; # use the count query here
$limit = 100;
while($numberOfRows > 0) {
exporter($limit);
$numberOfRows -= $limit;
}
Also, you can call your function in your function recursively (https://www.w3schools.blog/php-recursive-functions)
Putting the existing code in a loop seems like the obvious answer here.
do {
$results = $db
->SELECT()
->FROM(
['MM'=>'M_MEMBER'],
[
'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS',
]
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT(100)
->QUERY()
->FETCHALL();
if (count($results) === 0) {
break;
}
$data = [];
foreach ($results as $row) {
$row['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$data[] = $row;
//
// this is UNSAFE and inefficient, use a prepared statement if possible
//
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$json = json_encode($out);
$filename = sprintf(
"%sdataMember_%s_%s.json",
$store_path_pos,
date("Y-m-d"),
formatNbr($counterFile)
);
if ($json && file_put_contents($filename, $json)) {
echo "Create Json File Success In $file";
} else {
echo "Create Json Failed";
}
} while (true);
I fixed a few inefficiencies in your code; I have no idea what DB library you're using but as a rule you should never inject variables into an SQL query. It's likely safe in this context, but if your library allows you should prepare the statement outside the loop and execute it inside the loop for better performance.

Laravel maatwebsite excel package import 2000+ rows results in 1390 code error

I have 4 excel files that contains 1000 rows in every file. I merged it and make it 4000 so that I can save some time. But if I import the merged file it returns me an error of General error: 1390 Prepared statement contains too many placeholders. But when I insert them ony by one it works. I dont know why it return such error, they have even the same values in every column. Can someone tell me what to do with this error? Help would be appriciated. Thanks a lot
Im using laravel maatwebsite excel package.
My import code
public function import(Request $request)
{
if($request->hasFile('template')){
$path = $request->file('template')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count() > 0){
$rows = $data->toArray();
foreach ($rows as $row) {
$level = '';
$stack = '';
$unit = '';
$gunit = '';
$street = '';
$block_unit = '';
//DONT MIND THIS FUNCTION HERE
if (strpos($row['address'], '#') !== false) {
$unit = explode("#",$row['address']);
$gunit = $unit[1];
$block = explode(" ",$unit[0],2);
if(isset($unit[1])) {
$x = explode("-",$unit[1]);
$level = $x[0];
$stack = $x[1];
$street = $block[1];
$block_unit= $block[0];
}
}
elseif(strpos($row['address'], ' ') !== false){
$unit = explode(" ",$row['address']);
$block = explode(" ",$unit[0],2);
if(isset($unit[1])) {
$x = explode("-",$unit[1]);
$level = '';
$stack = '';
$x = preg_replace('/[0-9]+/', '', $row['address']);
$street = $x.substr($street,1);
$block_unit= $block[0];
}
}
else{
$level = '';
$stack = '';
$unit = '';
$gunit = '';
$block_unit = '';
$street = '';
}
//END
$inserts[]=[
'transtype' => 'RESI',
'project_name' => $row['project_name'],
'unitname' => $gunit,
'block' => $block_unit,
'street' => $street,
'level' => $level,
'stack' => $stack,
'no_of_units' => $row['no._of_units'],
'area' => $row['area_sqm'],
'type_of_area' => $row['type_of_area'],
'transacted_price' => $row['transacted_price'],
'nettprice' => $row['nett_price'],
'unitprice_psm' => $row['unit_price_psm'],
'unitprice_psf' => $row['unit_price_psf'],
'sale_date' => $row['sale_date'],
'contract_date' => $row['sale_date'],
'property_type' => $row['property_type'],
'tenure' => $row['tenure'],
'completion_date' => $row['completion_date'],
'type_of_sale' => $row['type_of_sale'],
'purchaser_address_indicator' => $row['purchaser_address_indicator'],
'postal_district' => $row['postal_district'],
'postal_sector' => $row['postal_sector'],
'postal_code' => $row['postal_code'],
'planning_region' => $row['planning_region'],
'planning_area' => $row['planning_area'],
];
}
}
if(empty($inserts)){
dd('Request data does not have any files to import.');
}
else {
\DB::table('xp_pn_ura_transactions')->insert($inserts);
dd('record inserted');
}
}
}
You can not insert more than 1000 records using laravel insert() method. If you want to achieve expected output then you can use array_chunk function of php or collection of laravel.
For example using array_chunk :
$chuncked = array_chunk($inserts, 1000);
foreach($chuncked as $insert){
\DB::table('xp_pn_ura_transactions')->insert($insert);
}

fopen creates file like Resource id #3?

i am trying yo create a new file using a existing file.
but When i create a new file in my uploads folder a file is automatically created with resource id #3 WHY??
public function edit_ini_custom($id)
{
/*Getting parameters name to display in view*/
$this->data['params'] = $this->parameter_m->get();
/*Path of our BASE and CUSTOM INI files*/
$path = "./uploads/";
$this->db->select('*');
$this->db->where('id',$id);
/*Here the id is the ID we got from URI View*/
$this->db->from('base_ini');
$query = $this->db->get();
$result = $query->row();
$filename= $result->base_ini_filename;
$path= $result->file_path;
/*Reading Contents from our path and the name of file we got from database*/
file_get_contents($path.$filename);
$this->data['parameters'] = parse_ini_file($path.$filename);
/*Getting Our POST DATA from View*/
$data = array(
'SipUserName' => $this->input->post('SipUserName') ,
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'Param_1' => $this->input->post('Param_1'),
'Param_2' => $this->input->post('Param_2')
);
$this->load->helper('file');
$suffix =$this->input->post('SipUserName');
/*Setting the Name of File*/
$name =$this->session->userdata('username');
/*Creating New file with the name of customer loggedin*/
$file_new = fopen('uploads/'.$name.$suffix.'.ini', 'w');
fwrite($file_new, "[INIDetails]\n");
foreach ($data as $key => $value)
{
fwrite($file_new, " $key = $value\n");
}
fclose($file_new);
/*Setting path to New CUSTOM file with customer name as prefix*/
$file = $path.$file_new;
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
/*Creates ini file, dumps array to string and creates .INI file*/
write_php_ini($data,$file);
/*Back to you index page id data is submmited*/
if(isset($_POST['submit'] ))
{
redirect('customer/upload_ini/index');
}
$this->data['subview'] = 'customer/upload/edit_ini_custom';
$this->load->view('customer/_layout_main', $this->data);
}

Imploding Delimiters True Position (PHP)?

It's a function in my class. I have no idea for imploding $newConditions with ( OR ) ( AND ).
Anybody have an idea ?
// #GETSSQ = Get Secured Select Query
function getSSQ($query) {
$conDelimiters = array(' OR ',' AND '); // Condition Delimiters
$fivaDelimiters = array('LIKE','<=>','<>','=>','<=','!=','=','<','>'); // Field & Value delimiters {Operators}
$conditions = preg_split("/(".implode('|',$conDelimiters).")/", $query);
$newConditions = array();
$operator = array("operator" => null);
foreach ($conditions as $idx => $cond) {
$operator["index"] = strlen($cond);
foreach ($fivaDelimiters as $sym) {
$pos = strpos($cond,$sym);
if ($pos === false)
continue;
else {
if ($pos < $operator['index']) {
$operator['index'] = $pos;
$operator['operator'] = $sym;
}
}
}
// Operatör bölme işlemine devam et...
$parts = array();
if ($operator['operator'] === null) {
$error = array(
"error" => "Koşullar arası yazım hatası tespit edildi. [".$this->options['connectionType'].":".$query."]",
"code" => "008"
);
$this->showError($error);
continue;
} else {
$condParts = explode($operator['operator'],$cond);
foreach ($condParts as $idx => $val) {
$condParts[$idx] = trim($val);
}
$parts['field'] = $this->__getSSQ_editFields($condParts[0]);
$parts['operator'] = $this->__getSSQ_editOperators($operator['operator']);
$newValue = $condParts[1];
if (count($condParts) > 2) { // If condition value has an operator character set
unset($condParts[0]);
$newValue = implode($operator['operator'],$condParts);
}
if (preg_match("/^['|\"](.*?)['|\"]$/", $newValue)) { // If value has {'} or {"} character begin & end , remove it
$newValue = substr($newValue, 1, (strlen($newValue)-2));
}
$newValue = $this->__getSSQ_editValues($newValue);
$parts['value'] = $newValue;
} #ENDIF OPERATOR === NULL
$newConditions[] = $parts['field'].' '.$parts['operator'].' '.$parts['value'];
} #END FOREACH CONDITIONS
var_dump($newConditions);
}
For Example My Function :
$condition = "id=5 AND parentCategory=2 AND firstName LIKE 'B%' AND usingMobile = 'true'";
$db = new XXClass();
$db->getSSQ($condition);
This output =>
array (size=4)
0 => string 'id = '5'' (length=8)
1 => string 'parentCategory = '2'' (length=20)
2 => string 'firstName LIKE 'B%'' (length=19)
3 => string 'usingMobile = 'true'' (length=20)
I can reach Fields , Operators , Values with __getSSQ_editXXXXX functions

joomla: adding a select.optgroup to select.genericlist

I need to add a select.optgroup to my select.genericlist, this is my code:
foreach ($this->methods as $method) {
if ($this->checkConditions($cart, $method, $cart->pricesUnformatted)) {
$methodSalesPrice = $this->calculateSalesPrice($cart, $method, $cart->pricesUnformatted);
$method->$method_name = $this->renderPluginName($method);
$session = JFactory::getSession();
$htmlI[] = $this->getPluginHtml($method, $selected, $methodSalesPrice);
// this is my attempt
$htmlI[] = JHTML::_('Select.optgroup', 'My optgroup');
// my attempt ends here
$htmlI[] = JHTML::_('Select.genericlist', $this->banks, 'service_issuer', 'size=1', 'key', 'value', $session->get('service_issuer', 0, 'vm'));
$html[] = $htmlI;
}
}
this returns the following:
array
Has anyone done this before? Advice is much appreciated
I've managed to fix it myself, below is the working code
if($method->payment_method == "mymethod") {
$session = JFactory::getSession();
$htmlI = $this->getPluginHtml($method, $selected, $methodSalesPrice);
$banksEra[] = JHTML::_('select.option', '', JText::_('VMPAYMENT_BANKS'));
$banksEra[] = JHTML::_('select.optgroup', 'Countries');
foreach ($this->banksEra as $key => $value) {
$banksEra[] = JHTML::_( 'select.option', $key, $value );
}
$htmlI .= JHTML::_('select.genericlist', $banksEra, 'issuer', 'class="inputbox"', 'value', 'text', $session->get('issuer', 0, 'vm'));
$html[] = $htmlI;
}

Categories