Remove unwanted states from dropdown list in Magento - php

I am new to magento and I am not able to make out how one can remove the unwanted states from dropdown list in magento. I tried to edit my below function as per this link http://doejo.com/blog/magento-how-to-remove-certain-states-from-state-region-list-at-checkout-or-registration/ but it did not work. Below i sthe code for removing unwanted states but when I add to my class in local folder, not getting any results.
$excludeRegions = array('AE','AA');
foreach ($collection as $region) {
if (!$region->getRegionId()) {
continue;
}
***//Here is the code from the link given
//BOF Custom Logic Here***
$regionCode = $region->getCode();
$this->_select->from(array('region'=>$this->_regionTable),
array('region_id'=>'region_id', 'country_id'=>'country_id', 'code'=>'code', 'default_name'=>'default_name')
)->where('code NOT IN (?)', $exclude_regions);
_getRegions function edited as per above code and link respectively.
protected function _getRegions($storeId)
{
$countryIds = array();
$countryCollection = $this->getCountryCollection()->loadByStore($storeId);
foreach ($countryCollection as $country) {
$countryIds[] = $country->getCountryId();
}
/** #var $regionModel Mage_Directory_Model_Region */
$regionModel = $this->_factory->getModel('directory/region');
/** #var $collection Mage_Directory_Model_Resource_Region_Collection */
$collection = $regionModel->getResourceCollection()
->addCountryFilter($countryIds)
->load();
$regions = array(
'config' => array(
'show_all_regions' => $this->getShowNonRequiredState(),
'regions_required' => $this->getCountriesWithStatesRequired()
)
);
$excludeRegions = array('AE','AA');
foreach ($collection as $region) {
if (!$region->getRegionId()) {
continue;
}
***//Here is the code from the link given
//BOF Custom Logic Here***
$regionCode = $region->getCode();
$this->_select->from(array('region'=>$this->_regionTable),
array('region_id'=>'region_id', 'country_id'=>'country_id', 'code'=>'code', 'default_name'=>'default_name')
)->where('code NOT IN (?)', $exclude_regions);
//EOF Custom Logic Here
$regions[$region->getCountryId()][$region->getRegionId()] = array(
'code' => $region->getCode(),
'name' => $this->__($region->getName())
);
}
return $regions;
}
After making the above changes, I tried below steps as my code is in /app/code/core/Mage/Directory/Helper/Data.php
Create a module Vids_Directory in pool local like app/code/local/Vids/Directory
Create app/etc/modules/Vids_Directory.xml
Create app/code/local/Vids/Directory/etc/config.xml
create app/code/local/Vids/Helper/Data.php

Related

Trying to get property of non-object in foreach loop

I am developing a system that uses Maatwebsite to read and write data to the database from an excel sheet, which is working fine. Now before inserting the data, the system checks for the entries in parent table. And if there is any record that matches the record of the sheet, the system inserts foreign key to the child schema and if there's not, the system creates one first and then insert it's id as foreign key.
Here's the import class:
public function collection(Collection $rows){
$sub_chap = SubChapter::where(['chap_id' => $this->chap_id])->get();
$chapter = Chapter::where(['chap_id' => $this->chap_id])->first();
$author = Author::where(['author_status' => 1])->get();
$book = $chapter->book_id;
$author_id = 0;
$sub_chap_id = 0;
/* Working perfectly fine here...
foreach($author as $a){
echo $a->a_name."\r";
}
*/
foreach ($rows as $row){
if($row['quote_english'] != ""){
foreach($sub_chap as $sub){
if(trim($sub->sub_chap_english) == trim($row['sub_chap_english'])){
$sub_chap_id = $sub->sub_chap_id;
break;
} else{
$sub_chap_id = 0;
}
}
if($author->count() > 0){
foreach($author as $athr){
$author_id = (trim($athr->author_name) == trim($row['author_name']))? $athr->author_id : $author_id = 0;
}
}
if($author_id == 0){
$author = Author::create([
'author_name' => $row['author_name'],
...
...
'author_status' => 1,
]);
$author_id = $author->author_id;
}
$quote = Quote::create([
'quote_english' => $row['quote_english'],
'author_id' => $author_id,
'sub_chap_id' => $sub_chap_id,
'chap_id' => $this->chap_id,
'book_id' => $book
]);
}
}
}
It's saying:
Trying to get property 'author_name' of non-object
I know this error comes when you try to access an object's property from a non-object instance. get() is returning the collection object as usual and working fine outside the foreach() loop. what i can't figure out is why it's not working inside the loop. Any help would be appreciated!
I still can't figure out why it's saying that and seems like no else also. So I think it's about time I post the solution I came up with. I found a way around it, So, basically what I did was I stored the whole collection to a global variable and accessed it in the loop.
Here's the code:
/**
* Global variable for raavi's data.
*/
public $author;
/**
* Construction function.
*
* #param int $id
* #param Collection $arr
*/
function __construct($arr) {
$this->author= $arr;
}
/**
* This method is responsible for inserting the excel
* sheet's rows data to the database schema.
*
* #param Collection $rows
*/
public function collection(Collection $rows){
// other code as it is...
foreach($this->author['author'] as $athr){
$author_id = (trim($athr->a_name) == trim($row['author_name']))? $athr->a_id : 0 ;
}
}
and in my importing controller's import method:
$quotes = Excel::import(new QuotesImport(compact('author')));
Working fine till now. If there's some improving or anything that needs to be change, kindly feel free. I would appreciate it.

how to import xml file into octobercms using kylp

I am trying to utilize this plugin to import an xml file, I have a simple xml file.
<MYData>
<login_details>
<unique_ref>1-61</unique_ref>
<login_name>tomme</login_name>
<login>me</login>
<password>me</password>
<file1>Test</file1>
<file2/>
<file3/>
<file4/>
</login_details>
<login_details>
<unique_ref>1-61</unique_ref>
<login_name>tony</login_name>
<login>tony</login>
<password>tony</password>
<file1>Test1</file1>
<file2/>
<file3/>
<file4/>
</login_details>
</MYData>
but can only manage to import 3 nodes I wrongly thought I could simply append this code $postBlog = $blogPost::create(['unique_ref' => $item->unique_ref, 'slug' => Str::slug($item->unique_ref), 'login_name' => $item->login_name, 'login' =>$item->login);but the last node does not update the database any help would be gratefully appreciated as I am new to coding in October frame work.
I found this piece of code that works but my model requires the slug to have a value
foreach ($xmls->login_details as $row => $data) {
try {
if (!$refno_prop = array_get($data, 'refno_prop')) {
}
/*
* Find or create
*/
$post = Post::make();
if ($this->update_existing) {
$post = $this->findDuplicatePost($data) ?: $post;
}
$postExists = $post->exists;
/*
* Set attributes
*/
$except = ['id', 'categories', 'author_email'];
foreach (array_except($data, $except) as $attribute => $value) {
$post->{$attribute} = $value ?: null;
}
$post->forceSave();
/*
* Log results
*/
if ($postExists) {
$this->logUpdated();
}
}
catch (Exception $ex) {
$this->logError($row, $ex->getMessage());
}
}
so I am looking for a method to add the slug value from an existing node I also haven't figured out how to stop the same data from being added to the database

Invalid argument supplied for foreach() in theme_table() but I'm passing valid arrays?

Ok, so I'm very new to Drupal and I'm trying to create a custom module that generates a page that the user can navigate to. When the user clicks on the page, I'm trying to retrieve the titles of all the content pieces from the database and arrange them in a table using table_theme. Everything is working except the generating of the rows in the table. It's giving me this message at the top of the page:
"Warning: Invalid argument supplied for foreach() in theme_table() (line 2107 of /srv/bindings/4d0bbd3c7be847abb26f62e0dacbcc24/code/includes/theme.inc)."
This message appears once for each title that I retrieve from the database. Here is my content_titles.module file (my custom module file):
<?php
/**
* #file
* A module that creates a page to display all existing content titles
*/
/**
* Implements hook_help()
*
* Displays help and module information
*
* #param path
* Which path of the site we're using to display help
* #param arg
* Array that holds the current path as returned from arg() function
*/
function content_titles_help($path, $arg) {
switch ($path) {
case "admin/help#content_titles":
return '' . t("Displays all existing content titles
on an overview page") . '';
break;
}
}
/**
* Implements hook_menu()
*
* Enables the module to register a link to be placed in a menu
*/
function content_titles_menu() {
$items['test/content_titles'] = array(
'title' => 'Overview Test Page',
'page callback' => 'content_titles_simple',
'access callback' => TRUE,
'expanded' => TRUE,
);
return $items;
}
/**
* Constructs the Content Titles page
*/
function content_titles_simple() {
return array('#markup' => create_content_table());
}
/**
* This function will create the table to hold the content titles in
*/
function create_content_table() {
// Retrieve content titles from the database
$results = db_query('SELECT title FROM {node}');
$header = array('Content Titles');
$rows = array();
while ($row = $results->fetchAssoc()) {
$rows[] = $row['title'];
}
print_r($rows); // FOR DEBUGGING PURPOSES
$output = theme('table', array('header' => $header,
'rows' => $rows));
return $output;
}
The problem appears to be with my use of the theme function. I don't see how any of my arguments are invalid though. I'm passing the theme type of 'table' and two arrays that I've checked aren't empty (that's why I use print_r to print the array that I store my titles from the database in). I'm pretty stumped here. Any idea what the problem could be?
Thanks for the help everyone, I figured it out! I needed to push arrays onto the $rows array instead of the values. I changed this section of code:
$rows = array();
while ($row = $results->fetchAssoc()) {
$rows[] = $row['title'];
}
To:
$rows = array();
while ($row = $results->fetchAssoc()) {
$rows[] = array($row['title']);
}
You must use as below:
$header = array(
array('data' => t('Content Titles'), 'field' => 'title'),
);
$rows = array();
$query = db_select('node', 'n')->fields('n', array('title'));
$pager = $query->extend('PagerDefault')
->limit(10);
$results = $pager->execute();
foreach ($results as $row) {
$rows[] = array($row->title);
}
return theme('table', array(
'header' => $header,
'rows' => $rows)) . theme('pager');
Thanks

Magento workaround to avoid edit core functionality

Hi have a function in app\code\core\Mage\Downloadable\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable\Links.php
that its called when a user in admin panel enters in a downloadable product in catalog > product
The function its
public function getConvertPDF(){
$_prodId = $this->getProduct()->getId();
/*Validate if the product exist */
if ($_prodId){
$_proFile =$this->getLinkFile();
$product = Mage::registry('current_product');
if ($product->getTypeId() == 'downloadable') {
$table = Mage::getModel('downloadable/link');
$collection = $table->getCollection()->addProductToFilter($product->getId());
foreach ($collection as $downloadable){
$linkFile = $downloadable->getLinkFile();
break;
}
$_proFile = $linkFile;
}
$extencion = '.jpg';
$path= 'C:/wamp/www/magento/media/downloadable/files/links';
$pathout= 'C:/wamp/www/magento/media/catalog/product/small/';
$test ='/small/';
exec('convert '.$path.$_proFile.'[0] '.$pathout.$_prodId.$extencion);
/*-------------------------------------------------**/
$resource = Mage::getSingleton('core/resource');
$adapter = $resource->getConnection('write');
$bind = array(
'value' => $test.$_prodId.$extencion
);
$where = array(
'entity_id = ?' => $_prodId,
'attribute_id = ?' => 86
);
$adapter->update($resource->getTableName('catalog_product_entity_varchar'), $bind, $where);
}
}
I saw a tutorial and they dont recomend to edit the core ...
so my question its if there is way to make the same behavior , placing this function in other play ,
how should be the procedure?
Functions in magento can be override by creating the functionallity of core in local...
for example in these case
app\code\ local\Mage\Downloadable\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable\Links.php
Update
The function should extends the core .. for example
extends Mage_Adminhtml_Block_Template

How to update custom options programatically in magento?

I have lot of products with custom options, now I have requirement to update only custom options through csv file. so how we can do this programatically?
i found one solution for updating custom options programatically here is the solution
$product = Mage::getModel('catalog/product')->load($product_id);
$values = array();
foreach ($product->getOptions() as $o) {
$p = $o->getValues();
}
}
foreach($p as $v)
{
$values[$v->getId()]['option_type_id']= $v->getId();
$values[$v->getId()]['title']= 'test';
$values[$v->getId()]['price']= 23;
$values[$v->getId()]['price_type']= 'fixed';
$values[$v->getId()]['sku']= $value1;
}
$v->setValues($values);
$v->saveValues();
$product->save();
hope this help someone
this only update custom options value
I think this is also useful...
If you are customize the products .
<?php
$magePath = 'app/Mage.php';
require_once $magePath;
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product_ids = array(1,2,167);
$productmodel = Mage::getModel('catalog/product');
foreach ($product_ids as $product_id) {
/**i use this two arrays for collecte value because i uses inside setData of
current option*/
$cos=array();
$co=array();
$product = $productmodel->load($product_id);
$options = $product->getProductOptionsCollection();
if (isset($options)) {
foreach ($options as $o) {
$title = $o->getTitle();
/**
this block is for changing information of specific option from collection options inside
current product
the save method for this option in end of code
*/
if ($title == "Line 1/Front") {
$o->setProduct($product);
$o->setTitle("Line 1/Ftont");
$o->setType("drop_down");
$o->setIsRequire(1);
$o->setSortOrder(0);
}
/**
this block for update or add information of specific value inside current option
*/
$optionType = $o->getType();
//test type
if ($optionType == "drop_down") {
//getting collection of value related to current option
$values = $o->getValuesCollection();
$found = false;
foreach ($values as $k => $v) {
//test existing of value for update
if (1 == preg_match("/said$/i", $v->getTitle())) {
//update and save
$v->setTitle("morad")
->setSku("kk")
->setPriceType("fixed")
->setSortOrder(0)
->setPrice(floatval(13.0000));
$v->setOption($o)->save();
/**
this ligne is important i collecte all value required for normalize save function
related to current option
*/
$cos[]=$v->toArray($co);
}
}
/**
create new value object you can use $option->getValueInstance() for working with
getSingleton
*/
$value = Mage::getModel('catalog/product_option_value');
$value->setOption($o)
->setTitle('valueiwant')
->setSku("nn")
->setPriceType("fixed")
->setSortOrder(1)
->setPrice(12)
/**
this ligne is important (relation forigien key) for related this new value
to specific option
*/
->setOptionId($o->getId());
$value->save();
/**
this ligne is important i collecte all value required for normalize save function
related to current option
*/
$cos[]=$value->toArray($co);
}
$o->setData("values",$cos)->save();
//var_dump($cos);
}
}
}
Do you create a module to do that ? If you do, you must use the cron system of Magento and call a method of a custom model :
<config>
<!--...-->
<crontab>
<jobs>
<company_test>
<schedule>
<cron_expr>0,15,30,45 * * * *</cron_expr>
</schedule>
<run>
<model>test/testmodel::testMethod</model>
</run>
</company_module>
</jobs>
</crontab>
</config>
When this is done, you can update the option of a specific product by using the model Mage_Catalog_Model_Product_Option. I don't know how the CSV is made, but the algorithm can be something like that :
// foreach option
/** #var $opt Mage_Catalog_Model_Product_Option */
$opt = Mage::getModel('catalog/product_option');
$opt->setProduct($product);
$optionArray = array(
'is_delete' => 0,
'title' => 'Blabla',
'previous_group' => '',
'previous_type' => '',
'type' => 'field', //can be radio, drop_down, file, area...
'is_require' => 0,
'sort_order' => 42,
'values' => array()
);
$opt->addOption($optionArray);
$opt->saveOptions();
// end foreach
Also check this link : http://subesh.com.np/2009/12/adding-custom-options-product-magento/

Categories