magento connections to two databases - php

I have a problem in magento. i want to connect two databases with magento.one database will be the main database and the other will be for stores. I dont know how to do it.By this time my connection is in the file app/etc/local.xml.....my local.xml is follows
please help
false
[mysql4]]>
1

There may be a more elegant solution that what I've implemented, but my method works. I did this for an osCommerce import/export module.
/httpdocs/app/etc/config.xml
<!-- osCommerce db/read/write -->
<oscommercedb>
<connection>
<host>localhost</host>
<username>root</username>
<password>pass</password>
<dbname>oscommerce_database_name</dbname>
<model>mysql4</model>
<initstatements>SET NAMES utf8</initstatements>
<type>pdo_mysql</type>
<active>1</active>
</connection>
</oscommercedb>
<oscommercedb_write>
<connection>
<use>oscommercedb</use>
</connection>
</oscommercedb_write>
<oscommercedb_read>
<connection>
<use>oscommercedb</use>
</connection>
</oscommercedb_read>
<!-- end osCommerce db -->
This gives you the ability to call oscommercedb within your models. The above code goes within the <resources> block.
Let's take a look at a model now.
/httpdocs/app/code/local/Company/Extension/Model/OsCustomers.php
class Company_Extension_Model_OsCustomers extends Mage_Core_Model_Abstract
{
protected $_name = 'customers'; // name of the table
/**
* Returns rowset of tables for customers
*
* #return Zend_Db_Table_Rowset
*/
public function getAllOscommerceCustomers()
{
$read = Mage::getSingleton('core/resource')->getConnection('oscommercedb');
$stmt = $read->select();
$stmt->from(array('c' => 'customers'))
->join(array('a' => 'address_book'), 'a.address_book_id = c.customers_default_address_id')
->joinLeft('zones', 'zones.zone_id = a.entry_zone_id')
->join('countries','a.entry_country_id = countries.countries_id', array('countries_iso_code_2'));
return $read->fetchAll($stmt);
}
If you run into a specific problem let me know.

Related

magento adding a column in existing table

I am new to Magento. I want to add a column in the newsletter_subscriber table so I made a new file mysql4-upgrade-1.6.0.0-1.6.0.1.php in app/code/core/mage/newsletter_setup/
<?php
$installer = $this;
$installer->startSetup();
$installer->getConnection()->addColumn(
$this->getTable('newsletter/subscriber'), //table name
'groupid', //column name
'varchar(100) NOT NULL' //datatype definition
);
$installer->endSetup();
?>
I updated the config file:
<modules>
<Mage_Newsletter>
<version>1.6.0.0</version>
</Mage_Newsletter>
</modules>
It doesn't work, please guide what I am doing wrong
It is not recommended to add/modify or do changes to any core files . Better you make a new module to add an extra column .
You have to mention correct version for module upgrade in app/code/local/your/module/sql/your_module_setup/upgrade-0.1.2-0.1.3.php file. (This means your upgrade the module version from 0.1.2 to 0.1.3). If your are not using upgrade script, remember to define <resources> in module config.xml and the setup script name is mysql4-install-0.1.0.php
Below is Mysql setup script file - upgrade-0.1.2-0.1.3.php
<?php
ini_set('display_errors', '1');
$installer = $this;
$installer->startSetup();
$installer->getConnection()
->addColumn(
$installer->getTable('newsletter/subscriber'), //Get the newsletter Table
'your_field_name', //New Field Name
array(
'type' => Varien_Db_Ddl_Table::TYPE_TEXT, //Field Type like TYPE_INTEGER ...
'nullable' => true,
'length' => 255,
'default' => 'Some thing default value',
'comment' => 'Your field comment'
)
);
$installer->endSetup();
?>
and after that change app/code/local/your/module/etc/config.xml version for example
<config>
<modules>
<NameSpace_ModuleName>
<version>0.1.3</version> <!-- if upgrade script version is 0.1.3 -->
</NameSpace_ModuleName>
</modules>
<global>
<resources>
<NameSpace_ModuleName_setup>
<setup>
<module>NameSpace_ModuleName</module>
<class>Mage_Catalog_Model_Resource_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</NameSpace_ModuleName_setup>
</resources>
</global>
</config>
With setup scripts they will be executed according to changes in the module's version.
In your case, your filename is mysql4-upgrade-1.6.0.0-1.6.0.1.php, while your version is 1.6.0.0. To get this particular script to execute you will need to bump the version to 1.6.0.1.
That being said - you're adding functionality to core Magento modules which is bad practice. You should instead move this into a local pool (app/code/local) module.
simply you can create a script and in you dbscripts folder and run this file from terminal or web browser.
e.g save file in pub/dbscripts/filename.php paste this code and change according to your requirement
<?php
use Magento\Framework\App\Bootstrap;
require '../../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
error_reporting(E_ALL);
ini_set('display_errors', 1);
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$salesTable = $resource->getTableName('Table_Name');
$sql = "ALTER TABLE ".$salesTable. " ADD `Field_name` varchar(255)";
$connection->query($sql);
echo"Script Run Successfully";
run this file from browser like
domain.name/pub/dbscripts/filename.php

Magento - passing data between front and backend

This is my first time with Magento. I have to prepare module which adds select field (yes/no) into General information (Category in admin Panel). I have already done this part. Next step is to check value selected in General information form when user goes to category side. If the user is not logged-in and admin option has been selected to "yes" in General information form, system should display information like: "you must log in".
Below my folder structure:
- app
-> code
-> community
-> AttributeCategory
->CustomAttributeCategory->
- etc
-> config.xml
<?xml version="1.0"?>
<config>
<modules>
<AttributeCategory_CustomAttributeCategory>
<version>0.0.3</version>
</AttributeCategory_CustomAttributeCategory>
</modules>
<global>
<resources>
<add_category_attribute_login>
<setup>
<module>AttributeCategory_CustomAttributeCategory</module>
<class>Mage_Catalog_Model_Resource_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</add_category_attribute_login>
<add_category_attribute_login_write>
<connection>
<use>core_write</use>
</connection>
</add_category_attribute_login_write>
<add_category_attribute_login_read>
<connection>
<use>core_read</use>
</connection>
</add_category_attribute_login_read>
</resources>
</global>
</config>
- sql -> add_category_attribute_login ->
- mysql4-install-0.0.3.php :
<?php
$this->startSetup();
$this->addAttribute(Mage_Catalog_Model_Category::ENTITY, 'is_category_allowed', [
'group' => 'General Information',
'type' => 'int',
'input' => 'select',
'label' => 'required logged-in user',
'sort_order' => 1000,
'visible' => true,
'required' => true,
'source' => 'eav/entity_attribute_source_boolean',
'visible_on_front' => true,
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'option' => [
'values' => [
0 => 'No',
1 => 'Yes',
]
],
]);
$this->endSetup();
AND
- app->etc->modules:
AttributeCategory_CustomAttributeCategory.xml:
<?xml version="1.0"?>
<config>
<modules>
<AttributeCategory_CustomAttributeCategory>
<active>true</active>
<codePool>community</codePool>
</AttributeCategory_CustomAttributeCategory>
</modules>
</config>
Please, tell me how can I check value in front when users visit category pages?
You should create an observer which looks at the attribute value on the category that is loaded, then performs the check and if necessary sets an error message and redirects to the customer's login page.
You could observe the event catalog_controller_category_init_after which is dispatched in Mage_Catalog_CategoryController::_initCategory after the category is loaded. This means that all attributes for the category will be available to look at, regardless of whether they are in the category flat tables or not.
Create an observer:
// File: app/code/community/AttributeCategory/CustomAttributeCategory/Model/Observer.php
class AttributeCategory_CustomAttributeCategory_Model_Observer
{
public function checkLoggedInForCategory(Varien_Event_Observer $event)
{
// Get the category from the event
/** #var Mage_Catalog_Model_Category $category */
$category = $event->getCategory();
// Get the customer's session model
/** #var Mage_Customer_Model_Session $customerSession */
$customerSession = Mage::getSingleton('customer/session');
if ($category->getIsCategoryAllowed() && !$customerSession->isLoggedIn()) {
// Add a custom message here?
$customerSession->addError('You must be logged in to view this category.');
// Redirect to login page
Mage::app()
->getResponse()
->setRedirect(Mage::getUrl('customer/account/login'))
->sendResponse();
exit;
}
}
}
The logic here basically says "get the category from the event" which can be done because the point where it is dispatched passes it as an argument, "get the customer session" which is always available regardless of whether the customer is logged in or not, "check 'is_category_allowed' is truthy and that the customer is not logged in" and if so add a validation error message, and redirect to the login page.
The login page automatically renders and displays all message block entries, so you don't need to handle the display manually.
Now you need to define your observer in your config.xml and connect it to the event:
<!-- File: app/code/community/AttributeCategory/CustomAttributeCategory/etc/config.xml -->
<?xml version="1.0"?>
<config>
<modules>
<AttributeCategory_CustomAttributeCategory>
<version>0.0.3</version>
</AttributeCategory_CustomAttributeCategory>
</modules>
<global>
...
</global>
<frontend>
<events>
<catalog_controller_category_init_after>
<observers>
<ensure_customer_can_view_category>
<class>AttributeCategory_CustomAttributeCategory_Model_Observer</class>
<method>checkLoggedInForCategory</method>
</ensure_customer_can_view_category>
</observers>
</catalog_controller_category_init_after>
</events>
</frontend>
</config>
I hope this helps. There's plenty of resource online about how to create observers etc, they're very useful things to use.
This registers an observer in the class AttributeCategory_CustomAttributeCategory_Model_Observer, method named checkLoggedInForCategory which is connected to the catalog_controller_category_init_after event in the frontend only. You can always define this in the global scope as well, but there's no point since it's only dispatched in the frontend, and should only be used for customers in the frontend.

Magento 1.9.1 model rewrite not executed

I've been trying for days now to get a rewritten model to function.
The code seems to be correct and the rewrite seems to work, but I can't see the logs, that I've put there for debugging purposes in the system.log.
I've tried several tutorials with all the same result.
Module WR_EPO is active and running. Even some installer-scripts for adding new columns in to my sql database are working fine.
Here's my code:
under local/WR/EPO/etc/config.xml:
<?xml version="1.0"?>
<config>
<modules>
<WR_EPO>
<version>1.0.0.1</version>
</WR_EPO>
</modules>
<global>
<models>
<wr_epo>
<class>WR_EPO_Model</class>
<resourceModel>wr_epo_resource</resourceModel>
</wr_epo>
<wr_epo_resource>
<class>WR_EPO_Model_Resource</class>
<entities>
<field>
<table>wr_epo_field</table>
</field>
</entities>
</wr_epo_resource>
<catalog>
<rewrite>
<product_option_type>WR_Catalog_Model_Product_Option_Type</product_option_type>
</rewrite>
</catalog>
<wishlist>
<rewrite>
<item>WR_Wishlist_Model_Item</item>
</rewrite>
</wishlist>
</models>
<resources>
<wr_epo_setup>
<setup>
<module>WR_EPO</module>
</setup>
</wr_epo_setup>
</resources>
<blocks>
<adminhtml>
<rewrite>
<tag_edit>WR_Adminhtml_Block_Catalog_Product_Edit_Tab_Options</tag_edit>
</rewrite>
</adminhtml>
</blocks>
</global>
</config>
the rewritten model under local/WR/EPO/Catalog/Model/Product/Option/Type/text.php:
<?php
class WR_Catalog_Model_Product_Option_Type_Text extends Mage_Catalog_Model_Product_Option_Type_Text
{
/**
* Validate user input for option
*
* #throws Mage_Core_Exception
* #param array $values All product option values, i.e. array (option_id => mixed, option_id => mixed...)
* #return Mage_Catalog_Model_Product_Option_Type_Default
*/
public function validateUserValue($values)
{
parent::validateUserValue($values);
$option = $this->getOption();
$value = trim($this->getUserValue());
// Check requires option to have some value
if (strlen($value) == 0 && $option->getIsRequire() && !$this->getSkipCheckRequiredOption()) {
$this->setIsValid(false);
Mage::throwException(Mage::helper('catalog')->__('Please specify the product\'s required option(s).'));
}
// Check maximal length limit
$maxCharacters = $option->getMaxCharacters();
$minValue = $option->getMinValue();
$maxValue = $option->getMaxValue();
if ($maxCharacters > 0 && Mage::helper('core/string')->strlen($value) > $maxCharacters) {
Mage::log(
"success maxChar in text.php",
null,
'WR_product-updates.log'
);
Mage::Log("success maxChar in text.php");
if (isset($minValue) && isset($maxValue) && ($value < $minValue || $value > $maxValue)){
$this->setIsValid(false);
Mage::throwException(Mage::helper('catalog')->__('The value is not in range!!!'));
}
else{
$this->setIsValid(false);
Mage::throwException(Mage::helper('catalog')->__('The text is too long'));
}
}
$this->setUserValue($value);
return $this;
}
}
here I add 2 variables $minValue and $maxValue und afterwards I do the logging into system.log and additionally into a custom log file, but none of them appear, when I refresh the page (cache cleared beforehand).
How can I fix/debug this? Why is the rewritten model not loaded instead of the core one? From what I've read custom rewrites override core Models.
Help is very appreciated
You need to change
<product_option_type>WR_Catalog_Model_Product_Option_Type</product_option_type>
to
<product_option_type_text>WR_EPO_Model_Product_Option_Type_Text</product_option_type_text>
put file to WR/EPO/Model/Product/Option/Type/Text.php
and change it class name from
class WR_Catalog_Model_Product_Option_Type_Text
to
class WR_EPO_Model_Product_Option_Type_Text

Magento 1.9 : sql script is not running

Basically what i am trying to do : I want some custom attributes for Customer entity. And to add those fields in db i am executing script.
I tried lots & lots of tweaks , methods but i cant solve SQL script error.
The important thing in it is : It makes entry in core_resource table.
My script made entry in core_resource.
I made extension according to this Alan storm Site .
Any help is highly appreciated.
My extension structure
Here is my coding part.
Config file of module
<?xml version="1.0"?>
<config>
<modules>
<StackExchange2_Customer>
<version>0.1.0</version>
</StackExchange2_Customer>
</modules>
<global>
<resources>
<stackExchange2_customer_setup>
<setup>
<module>StackExchange2_Customer</module>
<class>StackExchange2_Customer_Model_Resource_Mysql4_Setup</class>
<!-- <class>StackExchange2_Customer_Sql</class>-->
</setup>
<!--Mew node-->
<connection>
<use>core_setup</use>
</connection>
</stackExchange2_customer_setup>
<!--as per sOverflow-->
<stackExchange2_customer_write>
<connection>
<use>core_write</use>
</connection>
</stackExchange2_customer_write>
<stackExchange2_customer_read>
<connection>
<use>core_read</use>
</connection>
</stackExchange2_customer_read>
</resources>
</global>
</config>
Setup.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//Mage_Eav_Model_Entity_Setup
class StackExchange2_Customer_Model_Resource_Mysql4_Setup extends Mage_Core_Model_Resource_Setup{
}
mysql4-install-0.1.0.php
<?php
//echo "in script";die;
$installer = $this;
echo "hi123";
$installer->startSetup();
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//attr1
$installer->addAttribute('customer','name_of_child', array(
'type' => 'varchar',
'label' => 'Name of child',
'input' => 'text',
'position' => 120,
'required' => false,//or true
'is_system' => 0,
));
$attribute1 = Mage::getSingleton('eav/config')->getAttribute('customer', 'name_of_child');
//
$attribute1->setData('used_in_forms', array(
'adminhtml_customer',
'checkout_register',
'customer_account_create',
'customer_account_edit',
));
//
$attribute1->setData('is_user_defined', 0);
//
$attribute1->save();
Mage::log(__FILE__ . 'Update installed.');
$installer->endSetup();
Any help is highly appreciated
NOTE : In localhost it gives error : Am I using wrong class or anything missing?
( ! ) Fatal error: Call to undefined method StackExchange2_Customer_Model_Resource_Mysql4_Setup::addAttribute() in D:\xampp\htdocs\mykidscare\app\code\local\StackExchange2\Customer\sql\stackexchange2_customer_setup\mysql4-install-0.1.0.php on line 12
Add the following.
<resources>
<stackExchange2_customer_setup>
<setup>
<module>StackExchange2_Customer</module>
<class>Mage_Eav_Model_Entity_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</stackExchange2_customer_setup>
<stackExchange2_customer_write>
<connection>
<use>core_write</use>
</connection>
</stackExchange2_customer_write>
<stackExchange2_customer_read>
<connection>
<use>core_read</use>
</connection>
</stackExchange2_customer_read>
</resources>
You need to add Mage_Eav_Model_Entity_Setup class in setup in order to add any attribute.
Finally i solved it :) .
NOW it works after extending proper class (Mage_Customer_Model_Entity_Setup).
class StackExchange2_Customer_Model_Resource_Mysql4_Setup extends Mage_Customer_Model_Entity_Setup{
}

Magento: How can I add two or more static Blocks on category page

I am creating category page and i want to add two static blocks to it. While I was going through CMS/Static Blocks, I realized I can Only add One Static Block to any page. I couldn't find anything where i can add 2 or more static blocks. Is there a way i can add two or more such static blocks in a single category page.
If you want to add static block from Catalog->Manage Categories, then as you know you can call 1 static block at a time, but by using simple trick, you can call as many static blocks as you want.
Call 1 static block from admin panel Catalog->Manage Categories. Then call other static blocks from static block, which you are calling from category.
I hope this will help you.
First add new field into category.I have create a new field name "landing_page_2". I have created and extension for that works...
Step1:Create config.xml
Under: app\code\local\Amit\Catmattribute\etc
<?xml version="1.0"?>
<config>
<modules>
<Amit_Catmattribute>
<version>0.1.0</version>
</Amit_Catmattribute>
</modules>
<global>
<helpers>
<catmattribute>
<class>Amit_Catmattribute_Helper</class>
</catmattribute>
</helpers>
<models>
<catmattribute>
<class>Amit_Catmattribute_Model</class>
<resourceModel>catmattribute_mysql4</resourceModel>
</catmattribute>
</models>
<resources>
<categoryattribute1394603225_setup>
<setup>
<module>Amit_Catmattribute</module>
<class>Mage_Catalog_Model_Resource_Eav_Mysql4_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</categoryattribute1394603225_setup>
<categoryattribute1394603225_write>
<connection>
<use>core_write</use>
</connection>
</categoryattribute1394603225_write>
<categoryattribute1394603225_read>
<connection>
<use>core_read</use>
</connection>
</categoryattribute1394603225_read>
</resources>
</global>
</config>
step2:Create mysql4-install-0.1.0.php under:app\code\local\Amit\Catmattribute\sql\categoryattribute1394603225_setup
<?php
$installer = $this;
$installer->startSetup();
$installer->addAttribute("catalog_category", "landing_page_2", array(
"type" => "int",
"backend" => "",
"frontend" => "",
"label" => "CMS Block 2",
"input" => "select",
"class" => "",
"source" => "catalog/category_attribute_source_page",
"global" => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'group' => 'Display Settings',
"visible" => true,
"required" => false,
"user_defined" => false,
"default" => "",
"searchable" => false,
"filterable" => false,
"comparable" => false,
"visible_on_front" => false,
"unique" => false,
"note" => ""
));
$installer->endSetup();
Step3:create Data.php
app\code\local\Amit\Catmattribute\Helper
<?php
class Amit_Catmattribute_Helper_Data extends Mage_Core_Helper_Abstract
{
}
Step4:Amit_Catmattribute.xml under app/etc/modules/
<?xml version="1.0"?>
<config>
<modules>
<Amit_Catmattribute>
<active>true</active>
<codePool>local</codePool>
<version>0.1.0</version>
</Amit_Catmattribute>
</modules>
</config>
Copy view.php from app/code/core/Mage/Catalog/Block/Category/
to app/code/local/Mage/Catalog/Block/Category/
add new function
public function getCmsBlocktwoHtml()
{
if (!$this->getData('cms_block_html_2')) {
$html = $this->getLayout()->createBlock('cms/block')
->setBlockId($this->getCurrentCategory()->getLandingPage2())
->toHtml();
$this->setData('cms_block_html_2', $html);
}
return $this->getData('cms_block_html_2');
}
app\design\frontend\your package\your template\template\catalog\category\view.ptml
below code add after <?php echo $this->getCmsBlockHtml() ?>
<?php echo $this->getCmsBlocktwoHtml()?>
Hope it will be works.The section will manage fro madmin
You can put the following code in .phtml file to call static block
<?php $app = Mage::app(); ?>
<?php echo $app->getLayout()
->createBlock('cms/block')
->setBlockId('your_block_id')->toHtml(); ?>
What you can do is create the two required static blocks from cms>static blocks (eg:st1 and st2) and an another static block that will include both these static blocks (eg: dual_block).
In the dual_block static block you can insert widget, choose widget type as CMS Static Block then select the required block. You can similarly add other blocks as well. Make the required formatting to display the blocks as required.
Then in the required category, click on display settings tabs, select display mode as static block only and in CMS Block select dual_block static block. Then save the category and now you have two static blocks displayed in the category page.
Hope it helps!!

Categories