I am currently working on a paypal checkout using paypal and https://github.com/srmklive/laravel-paypal. I'm using the express checkout which I modified it a little bit to fit the requirements of the my project. During testing it is working in a couple of tries, paypal show and payment executes properly but when I tried to run the exact same code. I get this error I don't know what it means.
I tried to check my routes if it all of the errors happens to my routes but all of it are working properly. I also tried dump and die like dd("check") just to check if its really going to my controller and it does. I did this in the method "payCommission" (this where the I think the error happens)
This is my route for the controller
api.php
Route::get('service/commissionfee/payment' , 'api\service\ExpressPaymentController#payCommission');
Route::get('paypal/ec-checkout-success', 'api\service\ExpressPaymentController#payCommissionSuccess');
ExpressPaymentController.php
<?php
namespace App\Http\Controllers\api\service;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Srmklive\PayPal\Services\ExpressCheckout;
class ExpressPaymentController extends Controller
{
protected $provider;
public function __construct()
{
try {
$this->provider = new ExpressCheckout();
}
catch(\Exception $e){
dd($e);
}
}
public function payCommission(Request $request)
{
$recurring = false;
$cart = $this->getCheckoutData($recurring);
try {
$response = $this->provider->setExpressCheckout($cart, $recurring);
return redirect($response['paypal_link']);
} catch (\Exception $e) {
dd($e);
return response()->json(['code' => 'danger', 'message' => "Error processing PayPal payment"]);
}
}
public function payCommissionSuccess(Request $request)
{
$recurring = false;
$token = $request->get('token');
$PayerID = $request->get('PayerID');
$cart = $this->getCheckoutData($recurring);
// ? Verify Express Checkout Token
$response = $this->provider->getExpressCheckoutDetails($token);
if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
if ($recurring === true) {
$response = $this->provider->createMonthlySubscription($response['TOKEN'], 9.99, $cart['subscription_desc']);
if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
$status = 'Processed';
} else {
$status = 'Invalid';
}
} else {
// ? Perform transaction on PayPal
$payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
$status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
}
return response()->json(['success' => "payment complete"]);
}
}
private function getCheckoutData($recurring = false)
{
$data = [];
$order_id = 1;
$data['items'] = [
[
'name' => 'Product 1',
'price' => 9.99,
'qty' => 1,
],
];
$data['return_url'] = url('api/paypal/ec-checkout-success');
// !
$data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
$data['invoice_description'] = "Commission Fee payment";
$data['cancel_url'] = url('/');
$total = 0;
foreach ($data['items'] as $item) {
$total += $item['price'] * $item['qty'];
}
$data['total'] = $total;
return $data;
}
}
Error I am getting
Object of class Illuminate\Routing\Redirector could not be converted to string
Thank you in advance
you may just go to the config/paypal.php and edit
'invoice_prefix' => env('PAYPAL_INVOICE_PREFIX', 'Life_saver_'),
you may use _ underline in this like Life_saver_, dont forget use underline at the end too.
I am trying to create order with multiple products using below code. code work fine, but one issue is occurring. I don't know why that adding more than one product create an order with just one product and all quantity summed to this.
<?php
namespace Magecomp\Cenpos\Controller\Index;
use Magento\Framework\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Controller\ResultFactory;
class Display extends \Magento\Framework\App\Action\Action
{
protected $context;
protected $directory_list;
protected $cartRepositoryInterface;
protected $cartManagementInterface;
protected $_orderRepositoryInterface ;
/**
* #var \Magento\Sales\Model\Order\Email\Sender\OrderSender
*/
protected $orderSender;
/**
* #var \Magento\Checkout\Model\Session $checkoutSession
*/
protected $checkoutSession;
protected $_messageManager;
protected $_encryptor;
protected $_scopeConfig;
protected $logger;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\App\Filesystem\DirectoryList $directory_list,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Product $product,
\Magento\Framework\Data\Form\FormKey $formkey,
\Magento\Quote\Model\QuoteFactory $quote,
\Magento\Quote\Model\QuoteManagement $quoteManagement,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Sales\Model\Service\OrderService $orderService,
\Magento\Customer\Model\Session $currentCustomer,
\Magento\Checkout\Model\Cart $cart,
\Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface,
\Magento\Quote\Api\CartManagementInterface $cartManagementInterface,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender,
\Magento\Framework\Encryption\EncryptorInterface $encryptor,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
//\Magento\Sales\Api\OrderRepositoryInterface $orderRepositoryInterface
) {
$this->directory_list = $directory_list;
$this->_storeManager = $storeManager;
$this->_product = $product;
$this->_formkey = $formkey;
$this->quote = $quote;
$this->quoteManagement = $quoteManagement;
$this->customerFactory = $customerFactory;
$this->customerRepository = $customerRepository;
$this->orderService = $orderService;
$this->_currentCustomer = $currentCustomer;
$this->_cart = $cart;
$this->cartRepositoryInterface = $cartRepositoryInterface;
$this->cartManagementInterface = $cartManagementInterface;
$this->checkoutSession = $checkoutSession;
$this->orderSender = $orderSender;
$this->_encryptor = $encryptor;
$this->_scopeConfig = $scopeConfig;
//$this->_orderRepositoryInterface = $orderRepositoryInterface;
$this->_messageManager = $context->getMessageManager();
parent::__construct($context);
}
public function saveShipping() {
if(isset($_POST['carrier_code']))
{
$_SESSION['carrier_code'] = $_POST['carrier_code'];
}
return true;
}
public function execute()
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
$shippingAddress = $cart->getQuote()->getShippingAddress();
$shippingAddressData = $shippingAddress->getData();
$Response = $_GET;
if($Response['message'] == "Approved" && $Response['result'] == "0") {
$store=$this->_storeManager->getStore();
$websiteId = $this->_storeManager->getStore()->getWebsiteId();
$customer=$this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($shippingAddressData['email']);// load customet by email address
if(!$customer->getEntityId()){
//If not avilable then create this customer
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($shippingAddressData['firstname'])
->setLastname($shippingAddressData['lastname'])
->setEmail($shippingAddressData['email'])
->setPassword($shippingAddressData['email']);
$customer->save();
$customer= $this->customerRepository->getById($customer->getEntityId());
}
//init the quote
$cart_id = $this->cartManagementInterface->createEmptyCart();
$cart = $this->cartRepositoryInterface->get($cart_id);
$cart->setStore($store);
// if you have already had the buyer id, you can load customer directly
$customer= $this->customerRepository->getById($customer->getEntityId());
$cart->setCurrency();
$cart->assignCustomer($customer); //Assign quote to customer
$productInfo = $this->_cart->getQuote()->getAllItems();
//add items in quote
foreach($productInfo as $item){
$product=$this->_product->load($item->getProductId());
$product->setPrice($item->getPrice());
$cart->addProduct(
$product,
intval($item->getQty())
);
}
$addressData = array(
'firstname' => $shippingAddressData['firstname'],
'lastname' => $shippingAddressData['lastname'],
'street' => $shippingAddressData['street'],
'city' => $shippingAddressData['city'],
'postcode' => $shippingAddressData['postcode'],
'telephone' => $shippingAddressData['telephone'],
'country_id' => $shippingAddressData['country_id'],
'region_id' => $shippingAddressData['region_id'],
'region' => $shippingAddressData['region'],
);
//set shipping and billing address
$quote = $this->quote->create();
$cart->getBillingAddress()->addData($addressData);
$cart->getShippingAddress()->addData($addressData);
if(isset($_SESSION['carrier_code'])) {
$shipping_method = $_SESSION['carrier_code'];
} else {
$session = $this->_objectManager->get('Magento\Checkout\Model\Session');
$shipping_method = $session->getQuote()->getShippingAddress()->getShippingMethod();
}
$shippingAddress = $cart->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod($shipping_method);
unset($_SESSION['carrier_code']);
$cart->setPaymentMethod('cenpos'); //payment method
//#todo insert a variable to affect the invetory
$cart->setInventoryProcessed(false);
$card_type_code = "VI";
$cart->getPayment()->importData(
[
'method' => 'cenpos',
'cc_type' => $card_type_code,
'cc_number' => '4893772408728522',
'cc_cid' => '341',
'cc_exp_month' => '02',
'cc_exp_year' => '2022'
]
);
// Collect total and save
$cart->collectTotals();
// Submit the quote and create the order
$cart->save();
$cart = $this->cartRepositoryInterface->get($cart->getId());
$order_id = $this->cartManagementInterface->placeOrder($cart->getId());
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderRepository = $objectManager->create('Magento\Sales\Model\Order')->load($order_id);
$orderRepository->save();
$orderRepository->setEmailSent(true);
$this->checkoutSession->setForceOrderMailSentOnSuccess(true);
$this->orderSender->send($orderRepository, true);
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$resultRedirect->setUrl('http://m2gymtest.tpesonline.com/checkout/onepage/success');
return $resultRedirect;
}
}
}
Is there any problem in script? Or can it be server issue as the issue starts occurring after server changes.It was working properly before some days.
Use \Magento\Catalog\Model\ProductFactory $product instead of \Magento\Catalog\Model\Product $product in __construct() argument.
And Use
$product = $this->_product->create()->setStoreId($storeId)->load($item->getId());
to load the product instead of
$product=$this->_product->load($item->getProductId());
Hope this will help .
I have an update post form, where I need to update the name of the post in posts table and the associated text within the text table. I can't seem to get it to work at all.
Model - Post.php
public function text()
{
return $this->hasOne('Text');
}
Model - Text.php
public function post()
{
return $this->belongsTo('Post');
}
Controller - PostController.php
public function updateQuestionForm($id)
{
$post = Post::find($id);
$input = Input::all();
$rules = array(
'text' => 'required',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::back()->withErrors($validation)->withInput();
} else {
$post->title = Input::get('title');
$post->save();
$text = $post->text();
$text->text = Input::get('text');
$post->text()->save($text);
$message = "Post updated";
return Redirect::to('question/'.$post->id.'/'.$post->slug.'/')->with('message', $message);
}
}
I've been scouring the webs and potching with my code for hours now and can't seem to figure out why this isn't working.
I have a template library which scans a template.html for {#tags} and then runs the function associated to the tag to create data for that {#tag}'s content and then replaces {#tag} for the content generated, so I can have widget like parts to my template.
On my account/access page I have a login form and a registration form, now when the template library calls the widget_register() function, the form validation doesn't seem to do anything, the data is posted as I can see from the profiler, but the form validation doesn't seem to do anything with it
Account Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Account extends CI_Controller {
public function index()
{
$this->load->helper('url');
#redirect('/');
}
public function access()
{
$this->load->helper('url');
#if($this->auth->loggedin()) redirect('/');
$this->template->compile_page();
}
public function widget_register($template)
{
$this->output->enable_profiler(TRUE);
$this->load->helper('url');
if($this->auth->loggedin()) redirect('/');
if ($this->input->post('register_submit'))
{
$this->load->model('auth_model');
$this->form_validation->set_rules('register_nickname', 'Nickname', 'required|min_length[3]|max_length[75]');
$this->form_validation->set_rules('register_email_address', 'Email Address', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('register_confirm_email_address', 'Confirm Email Address', 'required|valid_email|matches[register_email_address]');
$this->form_validation->set_rules('register_password', 'Password', 'required|min_length[5]');
$this->form_validation->set_rules('register_confirm_password', 'Confirm Password', 'required|min_length[5]|matches[register_password]');
if($this->form_validation->run() !== false)
{
echo 'validation successful';
$nickname = $this->input->post('register_nickname');
$email = $this->input->post('register_email_address');
$generate_salt = $this->auth->generate_keys();
$salt = $generate_salt['1'];
$this->load->library('encrypt');
$generate_password = $salt . $this->input->post('register_password');
$password = $this->encrypt->hash($generate_password);
$generate_series_key = $this->auth->generate_keys();
$user_series_key = $generate_series_key['1'];
$this->db->query('INSERT INTO users (nickname, email, password, salt, register_date) VALUES ( "'.$nickname.'", "'.$email.'", "'.$password.'", "'.$salt.'", "'.time().'")');
}
else
{
echo 'invalid';
echo validation_errors();
}
}
$this->load->helper('form');
$view_data = array();
$view_data['form'] = form_open('account/access');
$view_data['input_nickname'] = form_input(array('name' => 'register_nickname', 'value' => set_value('register_nickname'), 'id' => 'register_nickname', 'class' => 'common_input', 'size' => '55'));
$view_data['input_email'] = form_input(array('name' => 'register_email_address', 'value' => set_value('register_email_address'), 'id' => 'register_email_address', 'class' => 'common_input', 'size' => '55'));
$view_data['input_confirm_email'] = form_input(array('name' => 'register_confirm_email_address', 'value' => '', 'id' => 'register_confirm_email_address', 'class' => 'common_input', 'size' => '55'));
$view_data['input_password'] = form_password(array('name' => 'register_password', 'value' => '', 'id' => 'register_password', 'class' => 'common_input', 'size' => '55'));
$view_data['input_confirm_password'] = form_password(array('name' => 'register_confirm_password', 'value' => '', 'id' => 'register_confirm_password', 'class' => 'common_input', 'size' => '55'));
$view_data['form_submit'] = form_submit('register_submit', 'Register');
$view_data['/form'] = form_close();
$view_data['validation_errors'] = validation_errors('<div class="error-box">', '</div>');
return $this->parser->parse(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/'.$template.'.html', $view_data, TRUE);
}
function widget_login()
{
$this->load->helper('url');
// user is already logged in
if ($this->auth->loggedin())
{
return $this->load->view(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/login/user.html', '', TRUE);
}
if($this->input->post('register'))
{
redirect('authentication/register');
}
// form submitted
if ($this->input->post('login_email_address') && $this->input->post('login_password'))
{
$this->load->library('form_validation');
$this->load->model('auth_model');
$this->form_validation->set_rules('login_email_address', 'Email Address', 'required|valid_email');
$this->form_validation->set_rules('login_password', 'Password', 'required|min_length[4]');
if($this->form_validation->run() !== false)
{
// validation passed verify from db
$remember = $this->input->post('remember') ? TRUE : FALSE;
if($remember == 'remember');
// check user exists and return user data
$user_data = $this->auth_model->user_exists($this->input->post('email_address'), TRUE);
if($user_data != FALSE)
{
// compare passwords
if ($this->auth_model->check_password($this->input->post('password'), $this->input->post('email_address')))
{
$this->auth->login($user_data->uid, $remember);
redirect('/');
}
else { $this->form_validation->set_custom_error('Incorrect password'); }
}
else { $this->form_validation->set_custom_error('There are no users with that email address'); }
}
}
// show login form
$this->load->helper('form');
$view_data = array();
$view_data['form'] = form_open();
$view_data['input_email'] = form_input('login_email_address', set_value('login_email_address'), 'id="login_email_address"');
$view_data['input_password'] = form_password('login_password', '', 'id="login_password"');
$view_data['input_remember'] = form_checkbox('remember', 'rememberme');
$view_data['form_submit'] = form_submit('login_submit', 'Login');
$view_data['register_button'] = form_submit('register', 'Register');
$view_data['/form'] = form_close();
$view_data['validation_errors'] = validation_errors('<div class="error-box">', '</div>');
return $this->parser->parse(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/login/login.html', $view_data, TRUE);
}
function logout()
{
$this->load->helper('url');
$this->session->sess_destroy();
$this->load->helper('cookie');
delete_cookie('aws_session');
delete_cookie('aws_autologin_cookie');
redirect('/');
}
}
and the Template library
class Template {
private $settings;
private $_ci;
private $_controller = ''; # Controller in use
private $_method = ''; # Method in use
private $_is_mobile = FALSE; # Is the User agent a mobile?
private $cache_lifetime = '1';
private $page_output = "";
private $partials = array();
private $spts = array(); # Static page tags
function __construct()
{
$this->_ci =& get_instance();
$this->settings = $this->_ci->settings->settings;
$this->_controller = $this->_ci->router->fetch_class();
$this->_method = $this->_ci->router->fetch_method();
$this->_ci->load->library('user_agent');
$this->_is_mobile = $this->_ci->agent->is_mobile();
log_message('debug', "Template Class Initialized");
}
function build_page()
{
$page = $this->_ci->load->view(FCPATH.'themes/'.$this->settings['system_settings']['theme'].'/pages/'.$this->settings['page_settings']['template'].'.html', '', TRUE);
$this->page_output .= $page;
}
# MAIN PAGE FUNCTIONS END ------------------------------------------------------------------------------------------
public function check_static_tags()
{
if(preg_match_all('/{#[A-Z]{1,75}}/', $this->page_output, $matches))
{
$this->spts = $matches['0'];
$this->spts = array_diff($this->spts, array('{#CONTENT}')); # removes stp_content from array list
return TRUE;
}
return FALSE;
}
# Convert static tags
public function convert_static_tags()
{
foreach($this->spts as $key => $static_tag)
{
$static_tag = str_replace(array('{','}'), '', $static_tag);
$this->partials[$static_tag] = $this->build_widget($static_tag);
}
}
# Convert widget tags
function column_widget_tags()
{
if(preg_match_all('/{#COLUMN_[0-9]{1,11}}/', $this->page_output, $matches))
{
if(isset($this->settings['page_settings']['widgets']))
{
$columns = unserialize($this->settings['page_settings']['widgets']);
}
foreach($columns as $column_id => $widgets)
{
if(count($columns[$column_id]) > '0') // if the column contains widgets
{
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] = '';
foreach($widgets as $key => $widget_id)
{
// build the widget and add it to the $this->page_bits['column_id'] variable for replacing later in the compiler
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] .= $this->build_widget($widget_id);
}
}
else
{
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] = '';
}
}
}
}
# Build Widget
function build_widget($widget_id)
{
if(is_numeric($widget_id))
{
$widget_query = $this->_ci->db->query('SELECT * FROM widgets WHERE id = "'.$widget_id.'"'); # BIND STATEMENTS
}
elseif(preg_match('/#[A-Z]{1,75}/', $widget_id))
{
$widget_query = $this->_ci->db->query('SELECT * FROM widgets WHERE tag = "'.$widget_id.'"'); # BIND STATEMENTS
}
else
{
show_error('Could not get widget from database: '.$widget_id);
}
if($widget_query->num_rows() > 0)
{
$widget_info = $widget_query->row_array();
// loads widgets parent controller, builds the widget (class method) and returns it
$this->_ci->load->controller($widget_info['controller'], $widget_info['controller']);
$method_name = 'widget_'.$widget_info['method'];
$complete_widget = $this->_ci->$widget_info['controller']->$method_name($widget_info['template']);
return $complete_widget;
}
else
{
show_error('The requested widget could not be loaded: '.$widget_id);
}
}
# Replace Partials
function replace_partials()
{
$this->_ci->load->library('parser');
$this->page_output = $this->_ci->parser->parse_string($this->page_output, $this->partials, TRUE);
}
## METADATA
public function prepend_metadata($line)
{
array_unshift($this->_metadata, $line);
return $this;
}
# Put extra javascipt, css, meta tags, etc after other head data
public function append_metadata($line)
{
$this->_metadata[] = $line;
return $this;
}
# Set metadata for output later
public function set_metadata($name, $content, $type = 'meta')
{
$name = htmlspecialchars(strip_tags($name));
$content = htmlspecialchars(strip_tags($content));
// Keywords with no comments? ARG! comment them
if ($name == 'keywords' AND ! strpos($content, ','))
{
$content = preg_replace('/[\s]+/', ', ', trim($content));
}
switch($type)
{
case 'meta':
$this->_metadata[$name] = '<meta name="'.$name.'" content="'.$content.'" />';
break;
case 'link':
$this->_metadata[$content] = '<link rel="'.$name.'" href="'.$content.'" />';
break;
}
return $this;
}
# Embed page into layout wrapper
function layout()
{
$this->_ci->load->helper('html');
$this->append_metadata(link_tag('themes/'.$this->settings['system_settings']['theme'].'/css/layout.css')); # default stylesheet
$this->append_metadata('<link rel="shortcut icon" href="/favicon2.ico" />'); # default favicon
$template['template.title'] = $this->settings['page_settings']['title']; # Page title, can be overidden by the controller ?
$template['template.metadata'] = implode("\n\t\t", $this->_metadata); # Metadata
$template['template.body'] = $this->page_output; # The page
return $this->_ci->parser->parse(FCPATH.'assets/layout/L6_layout_wrapper.html', $template, TRUE);
}
# Run all functions to build page and set in output class
function compile_page($content_data = '')
{
$this->partials['#CONTENT'] = $content_data;
$this->build_page();
$this->column_widget_tags();
if($this->check_static_tags())
{
$this->convert_static_tags();
$this->replace_partials();
}
$output = $this->layout();
$this->_ci->output->set_header('Expires: Sat, 01 Jan 2000 00:00:01 GMT');
$this->_ci->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
$this->_ci->output->set_header('Cache-Control: post-check=0, pre-check=0, max-age=0');
$this->_ci->output->set_header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
$this->_ci->output->set_header('Pragma: no-cache');
# Let CI do the caching instead of the browser
#$this->_ci->output->cache($this->cache_lifetime);
$this->_ci->output->append_output($output);
}
}
Sorry for the incredibly long post, I'm really stumped here and didn't want to miss any code out, thanks in advance!
I have to Sort order by Customer Groups in magento 1.7.0.2, I try to follow magento wiki:
http://www.magentocommerce.com/wiki/5_-_modules_and_development/admin/sort_order_by_customer_groups
But it doesn't works.
I copy app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php to app/code/local/Mage/Adminhtml/Block/Sales/Order/Grid.php to not touch magento core.
I add this code to this function
protected function _prepareColumns(){
$this->addColumn('customer_group_id', array(
'header'=> Mage::helper('customer')->__('Customer Group'),
'width' => '80px',
'index' => 'group_id',
'renderer' => new Mage_Adminhtml_Block_Sales_Order_Renderer_CustomerGroup(),
'type' => 'options',
'options' => Mage_Adminhtml_Block_Sales_Order_Renderer_CustomerGroup::getCustomerGroupsArray(),
));
// now the code original
}
Second, in the same file I add this override function
protected function _addColumnFilterToCollection($column) {
if ($this->getCollection()) {
$field = ( $column->getFilterIndex() ) ? $column->getFilterIndex() : $column->getIndex();
if ($column->getFilterConditionCallback()) {
call_user_func($column->getFilterConditionCallback(), $this->getCollection(), $column);
}
else {
$cond = $column->getFilter()->getCondition();
if ($field && isset($cond)) {
if (in_array('NULL', array_values($cond))) {
$this->getCollection()->addFieldToFilter($field, array('null' => true));
}
else {
$this->getCollection()->addFieldToFilter($field, $cond);
}
}
}
}
return $this;
}
third, in the Grid.php I modify this function:
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$collection->getSelect()->joinLeft(
array('ce'=>'customer_entity'),
'ce.entity_id=main_table.customer_id',
array('ce.group_id')
);
$this->setCollection($collection);
return parent::_prepareCollection();
}
Now I create this file in app/code/local/Mage/Adminhtml/Block/Sales/Order/Renderer/CustomerGroup.php with this code:
class Mage_Adminhtml_Block_Sales_Order_Renderer_CustomerGroup
extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {
// Holds an associative array with customer_group_id and the associated label
private static $_customerGroups = array(); // "singleton"
public static function getCustomerGroupsArray() {
// Make sure the static property is only populated once
if (count(self::$_customerGroups) == 0) {
$customer_group = new Mage_Customer_Model_Group();
$customer_groups = $customer_group->getCollection()->toOptionHash();
self::$_customerGroups = $customer_groups;
}
return self::$_customerGroups;
}
// Transforms the customer_group_id into corresponding label
public function render(Varien_Object $row)
{
$val = $this->_getValue($row);
$customer_groups = self::getCustomerGroupsArray();
return isset($customer_groups[$val]) ? $customer_groups[$val] : false;
}
}
And I have this error:
:5:{i:0;s:92:"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'customer_group_id' in 'where clause'";i:1;s:5645:"#0 MyProjectFolder\lib\Varien\Db\Statement\Pdo\Mysql.php(111): Zend_Db_Statement_Pdo->_execute(Array)
Thanks in advance !
I found the solution in magento forum, someone gives me the right solution:
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$collection->getSelect()->join(
array('oe'=>'sales_flat_order'),
'oe.entity_id=main_table.entity_id',
array('oe.customer_group_id')
);
$this->setCollection($collection);
return parent::_prepareCollection();
}