joomla: adding a select.optgroup to select.genericlist - php

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;
}

Related

laravel - unable to get data outside foreach

dump($data) outside the foreach loop gives me only 1 data where as dump($data) inside the foreach shows all arrays of rows of data . How can i get all rows of data outside the foreach too?
$skillId = $request->skillId;
if (CourseFiles::where('skillId', $skillId)->exists()) {
$courseId = CourseFiles::where('skillId', $skillId)->get(['courseId']);
foreach ($courseId as $row) {
$id = Course::find($row);
$data = [];
$data['courseDisplayName'] = $id[0]['courseDisplayName'];
$data['courseInfo'] = $id[0]['courseUniqueName'];
$data['paidStatus'] = $id[0]['paid_status'];
$data['coursePatternsId'] = $id[0]['course_patterns_id'];
$fileId = CourseFiles::where('skillId', $skillId)->get(['fileId']);
$id = Uploads::find($fileId);
$data['filePath'] = $id[0]['FilePath'];
$contentTypeID = $id[0]['FileType'];
$id = ContentTypes::find($contentTypeID);
$data['file_height'] = $id[0]['height'];
$data['file_width'] = $id[0]['width'];
dump($data);
}
//dump($data);
if ($data) {
return response()->json([
'message' => 'Fetched Data successfully',
'data' => $data,
'statusCode' => 200,
'status' => 'success'
], 200);
}
}
EDIT:
$response[]=$data;
$response->paginate(5);
Error: Call to a member function paginate() on array
In Controller add new function for it
$data = $this->paginate($myArray);
After that crate that function for pagination
public function paginate($items, $perPage = 5, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
return that $data in response
just do like this,
$output = array();
foreach ($courseId as $key => $row) {
$id = Course::find($row);
$fileId = CourseFiles::where('skillId', $skillId)->get(['fileId']);
$idtwo = Uploads::find($fileId);
$idthree = ContentTypes::find($idtwo[0]['FileType']);
//your data want to push to array
$output[$key] = array(
'courseDisplayName' => $id[0]['courseDisplayName'];
'courseInfo' => $id[0]['courseUniqueName'];
'paidStatus' => $id[0]['paid_status'];
'coursePatternsId' => $id[0]['course_patterns_id'];
'filePath' => $idtwo[0]['FilePath'];
'file_height' => $idthree[0]['height'];
'file_width' => $idthree[0]['width'];
);
}
dd($output);

Read Multiple Values from Array in Foreach Loop PHP

I want to get array values one by one and add into foreach dynamically
$tracker = array('1','2','3')
I am able to do it manually by creating multiple foreach below
<?php
$tracker = array( '1' );
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
$openseed = $value['seeders'];
}
$tracker = array( '2' );
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
$pirateseed = $value['seeders'];
}
$tracker = array( '3' );
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
$rarbgseed = $value['seeders'];
}
?>
But I want to add all array values to foreach dynamically at once instead of creating one by one manually
<?php
$tracker = array('1','2','3');
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
$openseed = $value['seeders'];
}
?>
The above code read only first array value and i want to read all array values and store the results separately and then calculate the total number of generated result by using array_sum() like this below
$totalseed = array($pirateseed,$openseed,$rarbgseed);
echo 'Total <font color="green">Seeders:</font> '. array_sum($totalseed). '<br />';
Any help will be appreciated thanks
var tracker = [1,2,3];
var tracker_counts = [];
for( let i in tracker ) {
// scrape
tracker_counts[i] = parseInt(Math.random() * 10); // put your $value['seeders'] here
}
console.log( "Tracker seeders individually: " + tracker_counts.join(',') );
console.log( "Seeders in total: " + tracker_counts.reduce((c,v) => c+=v ) ); // use array_sum in php
As PHP
<?php
$tracker = [1,2,3];
$tracker_counts = [];
foreach( $tracker as $k => $v ) {
// scrape of $v
$tracker_counts[$k] = rand(1,9); // put your $value['seeders'] here
}
echo "Tracker seeders individually: " . implode( ', ', $tracker_counts);
echo "\n";
echo "Seeders in total: " . array_sum( $tracker_counts );
Output
Tracker seeders individually: 7, 9, 6
Seeders in total: 22
I have figured it out by the help of Andreas and Pilan so I am posting the final working solution in case of anybody else looking for it
<?php
$ftracker = array('udp://tracker.torrent.eu.org:451/announce', 'http://tracker.tfile.co:80/announce', 'http://retracker.spb.ru:80/announce', 'udp://open.demonii.si:1337/announce');
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $ftracker );
$openseed = [];
foreach($ftracker as $track){
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $track );
foreach ($info as $key => $value) {
$openseed[] = $value['seeders'];
}
}
echo 'Seed for Each Tracker Separately'.implode( ', ', $openseed);
echo 'Total Seed for All Trackers'. array_sum( $openseed );
?>
Thanks to Andreas and Pilan

How to convert a multidimensional associative array to JSON?

As you can see in the JSON file, this looks not so necessary.
I get values from input-s and add it to the array and send it via AJAX. A simple array I know how to convert, but a multidimensional one is not. Can eat what that function? I tried to create an array with "keys", but there is a lot of trouble, I never reached the end , and I'm sure it's not right. Tell me what you can do.
i want this
{
"user1" : {
first_name":"Michael",
"last_name":"Podlevskykh",
"phones" : {
"phone_1":"5345",
"phone_2":"345345",
"phone_3":"123"
}
}
}
//this is what i see
JSON
[
{"first_name":"Michael"},
{"last_name":"Podlevskykh"},
[{"phone_1":"5345"},
{"phone_2":"345345"},
{"phone_3":"0991215078"}
]
]
PHP
//[["5345", "345345", "123"], "Michael", "Podlevskykh"]
$userInfo = (json_decode($_POST["phones"], true));
$namePhones = ["phone_1", "phone_2", "phone_3"];
$nameUser = ["first_name", "last_name"];
$jsonPhones = $userInfo;
$nameLName = $userInfo;
$jsonPhones = array_splice($jsonPhones, 0, 1);
$nameLName = array_splice($nameLName, -2);
foreach ($jsonPhones[0] as $key => $value) {
$phones[] = array($namePhones[$key] => $jsonPhones[0][$key]);
}
foreach ($nameLName as $key => $value) {
$usersName[] = array($nameUser[$key] => $nameLName[$key]);
}
array_push($usersName, $phones);
echo "<pre>";
echo json_encode($usersName);
//[
// {"first_name":"Michael"},{"last_name":"Podlevskykh"},
// [{"phone_1":"5345"},{"phone_2":"345345"},{"phone_3":"123"}]
//]
I don't get all the complications, I would do something like this if I'm sure the $input format is the same:
<?php
$input = '[["5345", "345345", "123"], "Michael", "Podlevskykh"]';
$input = json_decode($input, true);
$output = [
'user1' => [
'first_name' => $input[1],
'last_name' => $input[2],
'phones' => [
'phone_1' => $input[0][0],
'phone_2' => $input[0][1],
'phone_3' => $input[0][2]
]
]
];
echo '<pre>';
echo json_encode($output);
If you want an object as output, you need to create an object:
$userInfo = (json_decode($_POST["phones"], true));
$namePhones = ["phone_1", "phone_2", "phone_3"];
$nameUser = ["first_name", "last_name"];
$jsonPhones = $userInfo;
$nameLName = $userInfo;
$jsonPhones = array_splice($jsonPhones, 0, 1);
$nameLName = array_splice($nameLName, -2);
$user = new stdClass();
foreach ($nameLName as $key => $value) {
$user->{$nameUser[$key]} = $nameLName[$key];
}
$phones = new stdClass();
foreach ($jsonPhones[0] as $key => $value) {
$phones->{$namePhones[$key]} = $jsonPhones[0][$key];
}
$user->phones = $phones;
$users = new stdClass();
$users->user1 = $user;
echo json_encode($users);
Output:
{"user1": {
"first_name":"Michael",
"last_name":"Podlevskykh",
"phones":{
"phone_1":"5345",
"phone_2":"345345",
"phone_3":"123"
}
}
}

Magento attributes import php gives internal server error

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.

No Data & No Error when using function inside IF Statement

I am having trouble getting my php script to work when using a function in if statements.
The code currently runs, but doesn't give me any information, nor any errors, if I remove the IF'S it works fine, but the project I am working on, this is essential.
Here is my code - I have took out the SQL to save space..
if ($VAR === 'PK%') {
CDB::UseDB('blah', 'blah', 'blah', 'blah');
$sql = "blah blah
";
$lrs = CDB::ExecuteQuery($sql);
if ($lrs) {
$jsonData = convert($lrs);
function convert($lrs)
{
// RE-GET VARIABLE AS IT CAN'T GET IT FROM OUTSIDE OF FUNCTION
$VAR = $_GET['VARIABLE'];
$intermediate = array();
while ($vals = CDB::GetAssoc($lrs)) {
$key = $vals['VAR'];
$y = $vals['MEASURE_1'];
if (!isset($intermediate[$key])) $intermediate[$key] = array();
$intermediate[$key][] = array('x' => count($intermediate[$key]), 'y' => $y);
}
$output = array();
foreach ($intermediate as $key => $values) {
$output[] = array(
"key" => $key,
'values' => $values
);
}
return json_encode($output, JSON_NUMERIC_CHECK);
}
}
}
Can anyone shed some light on what I am doing wrong?
You are defining your function in a conditional way. In that case its definition must be processed prior to being called.
I would recommend declaring your function separately and then use it, like:
function convert($lrs) {
// RE-GET VARIABLE AS IT CAN'T GET IT FROM OUTSIDE OF FUNCTION
$VAR = $_GET['VARIABLE'];
$intermediate = array();
while ($vals = CDB::GetAssoc($lrs)) {
$key = $vals['VAR'];
$y = $vals['MEASURE_1'];
if (!isset($intermediate[$key])) $intermediate[$key] = array();
$intermediate[$key][] = array('x' => count($intermediate[$key]), 'y' => $y);
}
$output = array();
foreach ($intermediate as $key => $values) {
$output[] = array(
"key" => $key,
'values' => $values
);
}
return json_encode($output, JSON_NUMERIC_CHECK);
}
if ($VAR === 'PK%') {
CDB::UseDB('blah', 'blah', 'blah', 'blah');
$sql = "blah blah";
$lrs = CDB::ExecuteQuery($sql);
if ($lrs) {
$jsonData = convert($lrs);
}
}

Categories