How to create Barcode on PDF in Magento 2.3.x - magento

I am trying to create Barcode in PDF file in Magento 2.3.x Version,
Below code was working in Magento 2.1.8
However this is throwing below error -
PHP Fatal error: Uncaught TypeError: Argument 1 passed to
Zend\Barcode\Renderer\Pdf::setResource() must be an instance of
ZendPdf\PdfDocument, instance of Zend\Barcode\Renderer\Pdf given,
called in /var/www/magento/app/code/MyCompany/Ups/Helper/Custom.php on
line 81
<?php
namespace Mycompany\Ups\Helper;
use Zend\Barcode\Barcode;
use Zend\Barcode\Renderer;
use Zend\Barcode\Renderer\Pdf;
class Custom extends \Magento\Framework\App\Helper\AbstractHelper
{
protected $_logger;
protected $_fontPath;
protected $_pdf;
public function __construct(
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Module\Dir\Reader $configReader,
Pdf $pdf
)
{
$this->_logger = $logger;
$this->_fontPath = $configReader->getModuleDir('etc', 'Mycompany_Ups') . '/lib/fonts/';
$this->_pdf = $pdf;
}
public function getOrderConfirmationPdf($order)
{
try {
$pdf = new \Zend_Pdf();
$page = new \Zend_Pdf_Page(\Zend_Pdf_Page::SIZE_A4);
$color1 = new \Zend_Pdf_Color_GrayScale(0.0); // (float number). 0.0 (black) - 1.0 (white)
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
$page->setFont($font,40);
$page->setFillColor($color1)->drawText('ORDER CONFIRMATION', 60, 720);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font,30.5);
$page->setFillColor($color1)->drawText('THIS IS NOT A SHIPPING LABEL', 60, 620);
$page->setFont($font,16.5);
$page->setFillColor($color1)->drawText('PLACE THIS INSIDE THE SHIPPING CARTON WITH THE', 75, 520);
$page->setFillColor($color1)->drawText('CONTROL BOARD', 220, 500);
$page->setFillColor($color1)->drawText('WRITE THE BELOW ORDER CONFIRMATION NUMBER ON', 65, 460);
$page->setFillColor($color1)->drawText('THE OUTSIDE OF THE SHIPPING CARTON', 125, 440);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
$page->setFont($font,15);
$page->setFillColor($color1)->drawText('(Order Confirmation Number: '.$order->getIncrementId().')', 145, 370);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font,30.5);
$page->setFillColor($color1)->drawText('THIS IS NOT A SHIPPING LABEL', 60, 100);
$pdf->pages[] = $page;
/* \Zend_Barcode::setBarcodeFont($this->_fontPath.'helvetica-normal.ttf');
$barcodeOptions = array('text' => $order->getIncrementId(),'barHeight' => 100,'factor'=> 2.1,'drawText' => TRUE, 'withChecksum' => TRUE, 'stretchText' => TRUE, 'withChecksumInText' => TRUE, 'barThickWidth' => 2, 'barThinWidth' => 2);
$rendererOptions = array('topOffset' => 530,'leftOffset' => 185);
$pdfWithBarcode = \Zend_Barcode::factory('code128', 'pdf', $barcodeOptions, $rendererOptions)->setResource($pdf,0)->draw();*/
Barcode::setBarcodeFont($this->_fontPath.'helvetica-normal.ttf');
$barcodeOptions = array('text' => 'ZEND-FRAMEWORK');
$rendererOptions = array();
$renderer = Barcode::factory('code128', 'pdf', $barcodeOptions, $rendererOptions);
$renderer->setResource($pdf, $page)->draw();
$pdf_str = $pdf->render();
//$pdf->save("/var/www/html/magento2/mage2/pub/From_Helper_".$order->getIncrementId().".pdf");
unset($pdf);
return $pdf_str;
} catch(Exception $e) {
mail("rdambare#test.com","ORDER CONFIRMATION PDF ERROR: ".$order->getIncrementId(),$e->getMessage);
return FALSE;
}
}
}
I am using this code in Helper in my custom module.
Any help would be appreciated. Thanks in advance.
Below is sample of PDF I want to generate.

Try this code
<?php
namespace MyCompany\Ups\Helper;
include_once '/var/www/magento/fpdf181/fpdf.php';
use \Magento\Framework\App\Helper\AbstractHelper;
use \Magento\Framework\App\Filesystem\DirectoryList;
use Zend\Config\Config;
use Zend_Barcode;
// use Zend_Barcode;
class Data extends AbstractHelper {
const LABEL_FOLDER = 'media/sales/order/labels/';
const FONT_FOLDER = 'media/fonts/';
protected $_filePointer = NULL;
protected $_directoryList;
protected $_logger;
protected $_fontPath;
protected $_rootDirectory;
public function __construct(\Magento\Framework\View\Element\Template\Context $context, \Psr\Log\LoggerInterface $custLogger, \Magento\Framework\Module\Dir\Reader $configReader, \Magento\Framework\Filesystem $filesystem, DirectoryList $directoryList) {
$this->_logger = $custLogger;
$this->_directoryList = $directoryList;
$this->_pubPath = $directoryList->getPath('pub');
$this->_rootDirectory = $filesystem->getDirectoryRead(DirectoryList::ROOT);
$this->_fontPath = $configReader->getModuleDir('etc', 'MyCompany_Ups') . '/lib/fonts/';
$this->_storeManager = $context->getStoreManager();
}
public function getOrderConfirmationPdf($order) {
try {
$pdf = new \Zend_Pdf();
$page = new \Zend_Pdf_Page(\Zend_Pdf_Page::SIZE_A4);
$color1 = new \Zend_Pdf_Color_GrayScale(0.0); // (float number). 0.0 (black) - 1.0 (white)
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
$page->setFont($font, 40);
$page->setFillColor($color1)->drawText('ORDER CONFIRMATION', 60, 720);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 30.5);
$page->setFillColor($color1)->drawText('THIS IS NOT A SHIPPING LABEL', 60, 620);
$page->setFont($font, 16.5);
$page->setFillColor($color1)->drawText('PLACE THIS INSIDE THE SHIPPING CARTON WITH THE', 75, 520);
$page->setFillColor($color1)->drawText('CONTROL BOARD', 220, 500);
$page->setFillColor($color1)->drawText('WRITE THE BELOW ORDER CONFIRMATION NUMBER ON', 65, 460);
$page->setFillColor($color1)->drawText('THE OUTSIDE OF THE SHIPPING CARTON', 125, 440);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
$page->setFont($font, 15);
$page->setFillColor($color1)->drawText('(Order Confirmation Number: ' . $order->getIncrementId() . ')', 145, 370);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 30.5);
$page->setFillColor($color1)->drawText('THIS IS NOT A SHIPPING LABEL', 60, 100);
$pdf->pages[] = $page;
Zend_Barcode::setBarcodeFont($this->_fontPath . 'helvetica-normal.ttf');
$barcodeConfig = array('text' => $order->getIncrementId(), 'barHeight' => 100, 'factor' => 2.1, 'drawText' => TRUE, 'withChecksum' => TRUE, 'stretchText' => TRUE, 'withChecksumInText' => TRUE, 'barThickWidth' => 2, 'barThinWidth' => 2);
$rendererConfig = array('topOffset' => 530, 'leftOffset' => 185);
$renderer = Zend_Barcode::factory('code128', 'pdf', $barcodeConfig, $rendererConfig)->setResource($pdf, 0);
$renderer->draw();
$pdf_str = $pdf->render();
$pdf->save("/var/www/magento/pub/media/sales/order/labels/From_Helper_" . $order->getIncrementId() . ".pdf");
unset($pdf);
return $pdf_str;
}
catch(Exception $e) {
mail("rdambare#test.com", "ORDER CONFIRMATION PDF ERROR: " . $order->getIncrementId(), $e->getMessage);
return FALSE;
}
}

Try https://github.com/picqer/php-barcode-generator
Install through composer:
composer require picqer/php-barcode-generator
Usage
Initiate the barcode generator for the output you want, then call the ->getBarcode() routine as many times as you want.
$generator = new Picqer\Barcode\BarcodeGeneratorHTML();
echo $generator->getBarcode('081231723897', $generator::TYPE_CODE_128);

Related

"An illegal choice is detected..." error with dynamic dropdown select list I Drupal8

I wrote this code for dynamic dropdown select list in hook_form_alter. Options are populated by an external DB.
function car2db_annuncio_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'node_annuncio_form') {
$options_type = car2db_annuncio_type_dropdown_options();
$form['field_marca']['#prefix'] = '<div id="field_marca">';
$form['field_marca']['#suffix'] = '</div>';
$form['field_tipologia']['widget']['#options'] = $options_type;
$form['field_tipologia']['widget']['#ajax'] = array(
'event' => 'change',
'callback' => 'car2db_annuncio_make_ajax_callback',
'wrapper' => 'field_marca',
'disable-refocus' => FALSE,
'progress' => [
'type' => 'throbber',
'message' => t('Verify...'),
]
);
}
}
function car2db_annuncio_type_dropdown_options() {
$connection = Database::getConnection('default', 'migrate');
$dropdown_type = ['none' => '- Seleziona - '];
$sql_type = "SELECT * FROM `car_type`";
$query_type = $connection->query($sql_type);
$res_type = $query_type->fetchAll();
foreach ($res_type as $row){
$key = $row->id_car_type;
$value = $row->name;
$dropdown_type[$key] = $value;
}
return $dropdown_type;
}
function car2db_annuncio_make_dropdown_options($key_type) {
$connection = Database::getConnection('default', 'migrate');
$dropdown_make = ['none' => '- Seleziona - '];
$sql_make = "SELECT * FROM `car_make` WHERE `id_car_type` = :tipo";
$query_make = $connection->query($sql_make, [':tipo' => $key_type]);
$res_make = $query_make->fetchAll();
foreach ($res_make as $row){
$Key_make = $row->id_car_make;
$Make_value = $row->name;
$dropdown_make[$Key_make] = $Make_value;
}
return $dropdown_make;
}
function car2db_annuncio_make_ajax_callback(array &$form, FormStateInterface $form_state) {
if ($selectedValue = $form_state->getValue('field_tipologia')) {
$selectedValue = (int) $selectedValue[0]['value'] ? (int) $selectedValue[0]['value'] : 0;
$options_marca = car2db_annuncio_make_dropdown_options($selectedValue);
$form['field_marca']['widget']['#options'] = $options_marca;
}
return $form['field_marca'];
}
Now, when click on "Save button", there is always "An illegal choice is detected...." error.
I also tried loading options into the hook_form alter, but it always returns an error.
Where am i wrong?
I remember this confusing the hell out of me back in the day when I first started playing with ajax forms in Drupal.
Hopefully I am remembering this correctly.
Basically, you have to move your logic for adding the dynamic options into the form build function (but in your case, it's the alter function).
When the ajax function is called, the form is still rebuilt and your alter function is called (and has the current form_state).
Your ajax function will just return the new form element.
Something like below (untested)
function car2db_annuncio_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'node_annuncio_form') {
$options_type = car2db_annuncio_type_dropdown_options();
$form['field_marca']['#prefix'] = '<div id="field_marca">';
$form['field_marca']['#suffix'] = '</div>';
$form['field_tipologia']['widget']['#options'] = $options_type;
$form['field_tipologia']['widget']['#ajax'] = array(
'event' => 'change',
'callback' => 'car2db_annuncio_make_ajax_callback',
'wrapper' => 'field_marca',
'disable-refocus' => FALSE,
'progress' => [
'type' => 'throbber',
'message' => t('Verify...'),
]
);
// Check selected value here.
if ($selectedValue = $form_state->getValue('field_tipologia')) {
$selectedValue = (int) $selectedValue[0]['value'] ? (int) $selectedValue[0]['value'] : 0;
$options_marca = car2db_annuncio_make_dropdown_options($selectedValue);
$form['field_marca']['widget']['#options'] = $options_marca;
}
}
}
function car2db_annuncio_type_dropdown_options() {
$connection = Database::getConnection('default', 'migrate');
$dropdown_type = ['none' => '- Seleziona - '];
$sql_type = "SELECT * FROM `car_type`";
$query_type = $connection->query($sql_type);
$res_type = $query_type->fetchAll();
foreach ($res_type as $row){
$key = $row->id_car_type;
$value = $row->name;
$dropdown_type[$key] = $value;
}
return $dropdown_type;
}
function car2db_annuncio_make_dropdown_options($key_type) {
$connection = Database::getConnection('default', 'migrate');
$dropdown_make = ['none' => '- Seleziona - '];
$sql_make = "SELECT * FROM `car_make` WHERE `id_car_type` = :tipo";
$query_make = $connection->query($sql_make, [':tipo' => $key_type]);
$res_make = $query_make->fetchAll();
foreach ($res_make as $row){
$Key_make = $row->id_car_make;
$Make_value = $row->name;
$dropdown_make[$Key_make] = $Make_value;
}
return $dropdown_make;
}
function car2db_annuncio_make_ajax_callback(array &$form, FormStateInterface $form_state) {
// Just return the form element (that has been rebuilt in the form_alter)
return $form['field_marca'];
}

Paypal displaying 400 error when copoun is applied

I am using paypal integration in my web application everything is working fine . Checkout is working properly but when i apply the coupon then the paypal throws the exception of 400 error. Below is my code
I am using the daryldecode/cart for the checkout. The only problem is when I apply the coupon and move forward towards the paypal
public function paywithPaypal(Request $request)
{
// dd($request->all());
if(Auth::guest()){
if(Session::has('user_id')){
$sessionUserId = Session::get('user_id');
echo $sessionUserId;
}
$checkEmail= User::where('email',$request->billing_email )->first();
if(empty($checkEmail)) {
$user = User::create( [
'first_name' => $request->billing_first_name,
'last_name' => $request->billing_last_name,
'email' => $request->billing_email,
'username' => $request->billing_first_name,
'password' => bcrypt( 123456 ),
'province' => $request->billing_state,
'city' => $request->billing_town,
'address' => $request->billing_address_1,
'role' => 'Member',
] );
$userId = $user->id;
}else{
$userId = $checkEmail->id;
}
}else{
//user login
$sessionUserId = $userId = Auth::user()->id;
}
$items = [];
\Cart::session($sessionUserId)->getContent()->each(function($item) use (&$items)
{
$items[] = $item;
});
$subtotal = \Cart::session($sessionUserId)->getSubTotal();
// dd($subtotal);
$line1 = $request->billing_address_1;
$line2 = $request->billing_address_2;
$fullname = $request->billing_first_name ." ". $request->billing_last_name;
$state = $request->billing_state;
$zip = $request->billing_zip;
$phone = $request->billing_phone;
$email = $request->billing_email;
$city = $request->billing_town;
//invoke new order
$order = new Orders ;
$order->id = $order->generateID('INV');
$saved_order_id = $order->id;
$shippingAddress= Paypalpayment::shippingAddress();
$shippingAddress->setLine1($line1)
->setLine2($line2)
->setCity($city)
->setState($state)
->setPostalCode($zip)
->setCountryCode("US")
->setPhone($phone)
->setRecipientName($fullname);
// ### Payer
// A resource representing a Payer that funds a payment
// Use the List of `FundingInstrument` and the Payment Method
// as 'credit_card'
$payer = Paypalpayment::payer();
$payer->setPaymentMethod("paypal");
$listitem = array();
$fees=HandlingFee::find(1);
$fee = $fees->fee;
$shipping = $request->shipping_fee;
foreach($items as $key=>$item){
$listitem[$key] = Paypalpayment::item();
$listitem[$key]->setName($item->name)
->setCurrency('USD')
->setQuantity($item->quantity)
->setPrice($item->price);
$item_detail = new Order_Item_Details;
$item_detail->order_id = $saved_order_id;
$item_detail->item_id = $item->id;
$item_detail->qty = $item->quantity;
$item_detail->save();
}
$itemList = Paypalpayment::itemList();
$itemList->setItems($listitem)
->setShippingAddress($shippingAddress);
$details = Paypalpayment::details();
$details->setShipping($shipping)
->setHandlingFee($fee)
//total of items prices
->setSubtotal($subtotal);
$grandTotal = $subtotal + $fee + $shipping;
//dd($grandTotal);
//Payment Amount
$amount = Paypalpayment::amount();
$amount->setCurrency("USD")
// the total is $17.8 = (16 + 0.6) * 1 ( of quantity) + 1.2 ( of Shipping).
->setTotal($grandTotal)
->setDetails($details);
//dd($amount);
// ### Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. Transaction is created with
// a `Payee` and `Amount` types
$transaction = Paypalpayment::transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber($saved_order_id)
->setCustom($request->shipping_service);
// dd($transaction);
// ### Payment
// A Payment Resource; create one using
// the above types and intent as 'sale'
$redirectUrls = Paypalpayment::redirectUrls();
$redirectUrls->setReturnUrl(url("/payments/success"))
->setCancelUrl(url("/payments/fails"));
$payment = Paypalpayment::payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
$order->status = 1;
$order->user_id = $userId;
$order->total = $grandTotal;
$order->subtotal = $subtotal;
$order->shipping = $shipping;
if($request->coupon_code == ""){
$order->isCoupon = 0;
}
else{
$order->isCoupon = 1;
}
$order->isBillingDetail = 1;
if($request->shipping_first_name <> ""){
$order->isShippingDetail = 1;
}
if($request->has('order_notes')){
$order->notes = $request->order_notes;
}
$order->save();
$order_billing = new Order_Billing_Details;
$order_billing->order_id = $order->id;
$order_billing->first_name = $request->billing_first_name ;
$order_billing->last_name = $request->billing_last_name ;
$order_billing->company = $request->billing_company_name ;
$order_billing->address_line_1 = $line1;
$order_billing->address_line_2 = $line2;
$order_billing->state = $state;
$order_billing->city = $city;
$order_billing->postal_code = $zip;
$order_billing->email = $email;
$order_billing->phone = $phone;
$order_billing->save();
if($request->shipping_first_name <> ""){
$order_shipping = new Order_Shipping_Details;
$order_shipping->order_id = $order->id;
$order_shipping->first_name = $request->shipping_first_name ;
$order_shipping->last_name = $request->shipping_last_name ;
$order_shipping->company = $request->shipping_company_name ;
$order_shipping->address_line_1 = $request->shipping_address_1 ;
$order_shipping->address_line_2 = $request->shipping_address_2 ;
$order_shipping->state = $request->shipping_state ;
$order_shipping->city = $request->shipping_town ;
$order_shipping->postal_code = $request->shipping_zip ;
$order_shipping->email = $email ;
$order_shipping->phone = $request->shipping_phone ;
$order_shipping->save();
}
else{
$order_shipping = new Order_Shipping_Details;
$order_shipping->order_id = $order->id;
$order_shipping->first_name = $request->billing_first_name ;
$order_shipping->last_name = $request->billing_last_name ;
$order_shipping->company = $request->billing_company_name ;
$order_shipping->address_line_1 = $line1;
$order_shipping->address_line_2 = $line2;
$order_shipping->state = $state;
$order_shipping->city = $city;
$order_shipping->postal_code = $zip;
$order_shipping->email = $email;
$order_shipping->phone = $phone;
$order_shipping->save();
}
try {
// ### Create Payment
// Create a payment by posting to the APIService
// using a valid ApiContext
// The return object contains the status;
//dd(Paypalpayment::apiContext());
$payment->create(Paypalpayment::apiContext());
// dd($payment);
$arrpayment = $payment->toArray();
$order = Orders::find($saved_order_id);
$order->paypal_invoice = $arrpayment['id'];
$order->save();
} catch (\PPConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData();
dd($ex);
return response()->json(["error" => $ex->getMessage()], 400);
}
catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData(); // Prints the detailed error message
}
$email=$request->billing_email;
$fees=HandlingFee::find(1);
$fee = $fees->fee;
$data=array(
'order' => $order,
'name' => $request->billing_first_name.' '.$request->billing_last_name,
'email'=>$email,
'fee'=>$fee,
'payPalLink' => $payment->getApprovalLink(),
);
Mail::send('email.placed', $data, function($message) use ($email) {
$message->subject('New Order Received');
$message->from('no-reply#blurack.com', 'BluRack');
$message->to($email);
});
$admins=DB::table('users')
->select('updates_email')
->where('receiving_updates',1)
->where(function($q) {
$q->where('role','Administrator')
->orWhere('role','Retailer');
})->get()->toArray();
// ->where('role','Administrator')
// ->orWhere('role','Retailer')
// dd($admins);
foreach($admins as $admin){
$admin_mail=$admin->updates_email;
//dd($admin_mail);
Mail::send('email.orderplaced',$data, function($message) use ($admin_mail) {
$message->subject('New Order Received');
$message->from('no-reply#blurack.com', 'BluRack');
$message->to($admin_mail);
});
}
return redirect($payment->getApprovalLink());
// return response()->json([$payment->toArray(), 'approval_url' => $payment->getApprovalLink()],
200);
}
I think the issue is with try catch problem?

How to Paginate the array in Laravel 5.3?

I am working on a web application, which searches for places/locations via /search route. On /search route it displays all the matched/searched locations BUT the locations are array based i want to paginate through it which i did but now the problem arises in the view. In the view i used
{!! $father->render() !!}
which renders the pagination but when i try to go to the 2nd it doesn't work.
Controller Code
{
public function paginate($items,$perPage)
{
$pageStart = \Request::get('page', 1);
// Start displaying items from this number;
$offSet = ($pageStart * $perPage) - $perPage;
// Get only the items you need using array_slice
$itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);
return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage,Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
}
/**
* When user submit the search form it will return all the locations.
*
* #return locations collection
*/
public function postSearch(Request $request)
{
$categoryid = $request->category_id;
$locationid = $request->location_id;
$validator = \Validator::make($request->all(), [
'category_id' => 'required',
'location_id' => 'required',
],
[
'category_id.required' => 'Select Category',
'location_id.required' => 'Select Location',
]);
if($validator->fails()) {
return back()->withInput()->withErrors($validator->errors());
}else{
$category = Category::where('id', $categoryid)->first();
if(!$category->locations->isEmpty()) {
$cities = Location::where('id', $locationid)->pluck('city');
$cityname = $cities[0];
$alllocations = [];
$ratecards = [];
$father = [];
$i = 0;
$filteredlocations = $category->locations->where('city', $cityname)->all();
foreach($filteredlocations as $location){
$alllocations[$i] = $location->getaddetails;
$ratecards[$i] = $location->ratecard;
$father[$i]['ad'] = $alllocations[$i];
$father[$i]['rate'] = $ratecards[$i];
$i++;
}
$perPage = 4;
$father = AdSearchController::paginate($father, $perPage);
$nothing = 1;
return view('ads', compact('father','nothing'));
}else {
//flag
$nothing = 0;
return view('ads', compact('nothing'));
}
}
}
}
Route::resource('/search', 'AdSearchController#postSearch'); This is the route.We are searching on this route.

Exporting and Importing Attributes in Magento

I would love a script or magento extension to allow me to export all the product attributes including values for drop down attributes. Importing would be good too, I've had a look but can't seem to find anything does anyone know how this can be done?
Update: I found a working script in stackexchange and the script worked exactly as it should. All credits to the original poster. I am just copy pasting his reply here for future reference. Link to the original thread: is here.
I've done this to export all attributes and their options (if it is a dropdown attribute) from the source website:
exportAttributes.php in root directory of source website:
<?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);
}
This will give a csv file [actually i used "|" to separate ;)]
paste this csv file in MAGENTO_ROOT/attribImport directory of the destination website, i.e. website to which attributes need to be imported:
now put the following code in MAGENTO_ROOT/attribImport** directory
of the destination website
<?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;
}
NOTE: Allthough exceptions have been handled, Backup your Database
before you import these attributes, to be on safer side. Happy
Importing!
Thanks to :
Programatically create attribute in Magento, useful for the “on the fly” import system
programmatically_adding_attributes_and_attribute_sets
Magento – Programmatically insert new attribute option
I would recommend Boris's uRapidFlow: http://www.unirgy.com/products/urapidflow/ It's one of the better Data Flow Import/Export modules available. Be aware however it does require IonCube Loader, but it is well worth it if you are moving data around a lot.

How to Use Captcha Plugin in CodeIgniter

I followed this page, and the code is not working as it should in my project. I've tried to find other tutorial on how to execute what I need, however, it does not work as it should in my project either. Is anyone able to direct me to a tutorial that explains in a detailed fashion on how to use Captcha plug-in properly in CodeIgniter?
Controller:
<?php
class Prova extends Controller
{
function prova()
{
parent :: Controller();
$this -> load -> plugin( 'captcha' );
$this->load->library('validation');
$rules['user'] = "required";
$rules['captcha'] = "required|callback_captcha_check";
$this->validation->set_rules($rules);
$fields['user'] = 'Username';
$fields['captcha'] = 'codice';
$this->validation->set_fields($fields);
if ($this->validation->run() == FALSE)
{
$expiration = time()-300; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
$vals = array(
//'word' => 'Random word',
'img_path' => './tmp/captcha/',
'img_url' => base_url().'tmp/captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '100',
'img_height' => '30',
'expiration' => '3600'
);
$cap = $this->captcha->create_captcha($vals);
//
$dati['image']= $cap['image'];
//mette nel db
$data = array(
'captcha_id' => '',
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
$this->load->view('captcha',$data);
}else{
echo "Captcha can't be made";
}
return $cap ['image'];
}
function captcha_check()
{
// Then see if a captcha exists:
$exp=time()-600;
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($this->input->post('captcha'), $this->input->ip_address(), $exp);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
$this->validation->set_message('_captcha_check', 'Codice di controllo non valido');
return FALSE;
}else{
return TRUE;
}
}
}
View:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?=$this->validation->error_string; ?>
<?=form_open('XXXXXXXXX type your controller'); ?>
<h5>Username</h5>
<?=$this->validation->user_error; ?>
<input type="text" name="user" value="<?php echo ($this->validation->user) ;?>" size="50" />
<br/>
<?=$image;?>
<br/>
<?=$this->validation->captcha_error; ?>
<input type="text" name="captcha" value="" />
<br/>
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
Captcha:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/*
Instructions:
Load the plugin using:
$this->load->plugin('captcha');
Once loaded you can generate a captcha like this:
$vals = array(
'word' => 'Random word',
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$cap = create_captcha($vals);
echo $cap['image'];
NOTES:
The captcha function requires the GD image library.
Only the img_path and img_url are required.
If a "word" is not supplied, the function will generate a random
ASCII string. You might put together your own word library that
you can draw randomly from.
If you do not specify a path to a TRUE TYPE font, the native ugly GD
font will be used.
The "captcha" folder must be writable (666, or 777)
The "expiration" (in seconds) signifies how long an image will
remain in the captcha folder before it will be deleted. The default
is two hours.
RETURNED DATA
The create_captcha() function returns an associative array with this data:
[array]
(
'image' => IMAGE TAG
'time' => TIMESTAMP (in microtime)
'word' => CAPTCHA WORD
)
The "image" is the actual image tag:
<img src="http://example.com/captcha/12345.jpg" width="140" height="50" />
The "time" is the micro timestamp used as the image name without the file
extension. It will be a number like this: 1139612155.3422
The "word" is the word that appears in the captcha image, which if not
supplied to the function, will be a random string.
ADDING A DATABASE
In order for the captcha function to prevent someone from posting, you will need
to add the information returned from create_captcha() function to your database.
Then, when the data from the form is submitted by the user you will need to verify
that the data exists in the database and has not expired.
Here is a table prototype:
CREATE TABLE captcha (
captcha_id bigint(13) unsigned NOT NULL auto_increment,
captcha_time int(10) unsigned NOT NULL,
ip_address varchar(16) default '0' NOT NULL,
word varchar(20) NOT NULL,
PRIMARY KEY `captcha_id` (`captcha_id`),
KEY `word` (`word`)
)
Here is an example of usage with a DB.
On the page where the captcha will be shown you'll have something like this:
$this->load->plugin('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/'
);
$cap = create_captcha($vals);
$data = array(
'captcha_id' => '',
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
echo 'Submit the word you see below:';
echo $cap['image'];
echo '<input type="text" name="captcha" value="" />';
Then, on the page that accepts the submission you'll have something like this:
// First, delete old captchas
$expiration = time()-7200; // Two hour limit
$DB->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND date > ?";
$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
echo "You must submit the word that appears in the image";
}
*/
/**
|==========================================================
| Create Captcha
|==========================================================
|
*/
function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
{
$defaults = array('word' => '', 'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200);
foreach ($defaults as $key => $val)
{
if ( ! is_array($data))
{
if ( ! isset($$key) OR $$key == '')
{
$$key = $val;
}
}
else
{
$$key = ( ! isset($data[$key])) ? $val : $data[$key];
}
}
if ($img_path == '' OR $img_url == '')
{
return FALSE;
}
if ( ! #is_dir($img_path))
{
return FALSE;
}
if ( ! is_really_writable($img_path))
{
return FALSE;
}
if ( ! extension_loaded('gd'))
{
return FALSE;
}
// -----------------------------------
// Remove old images
// -----------------------------------
list($usec, $sec) = explode(" ", microtime());
$now = ((float)$usec + (float)$sec);
$current_dir = #opendir($img_path);
while($filename = #readdir($current_dir))
{
if ($filename != "." and $filename != ".." and $filename != "index.html")
{
$name = str_replace(".jpg", "", $filename);
if (($name + $expiration) < $now)
{
#unlink($img_path.$filename);
}
}
}
#closedir($current_dir);
// -----------------------------------
// Do we have a "word" yet?
// -----------------------------------
if ($word == '')
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$str = '';
for ($i = 0; $i < 8; $i++)
{
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
$word = $str;
}
// -----------------------------------
// Determine angle and position
// -----------------------------------
$length = strlen($word);
$angle = ($length >= 6) ? rand(-($length-6), ($length-6)) : 0;
$x_axis = rand(6, (360/$length)-16);
$y_axis = ($angle >= 0 ) ? rand($img_height, $img_width) : rand(6, $img_height);
// -----------------------------------
// Create image
// -----------------------------------
// PHP.net recommends imagecreatetruecolor(), but it isn't always available
if (function_exists('imagecreatetruecolor'))
{
$im = imagecreatetruecolor($img_width, $img_height);
}
else
{
$im = imagecreate($img_width, $img_height);
}
// -----------------------------------
// Assign colors
// -----------------------------------
$bg_color = imagecolorallocate ($im, 255, 255, 255);
$border_color = imagecolorallocate ($im, 153, 102, 102);
$text_color = imagecolorallocate ($im, 204, 153, 153);
$grid_color = imagecolorallocate($im, 255, 182, 182);
$shadow_color = imagecolorallocate($im, 255, 240, 240);
// -----------------------------------
// Create the rectangle
// -----------------------------------
ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color);
// -----------------------------------
// Create the spiral pattern
// -----------------------------------
$theta = 1;
$thetac = 7;
$radius = 16;
$circles = 20;
$points = 32;
for ($i = 0; $i < ($circles * $points) - 1; $i++)
{
$theta = $theta + $thetac;
$rad = $radius * ($i / $points );
$x = ($rad * cos($theta)) + $x_axis;
$y = ($rad * sin($theta)) + $y_axis;
$theta = $theta + $thetac;
$rad1 = $radius * (($i + 1) / $points);
$x1 = ($rad1 * cos($theta)) + $x_axis;
$y1 = ($rad1 * sin($theta )) + $y_axis;
imageline($im, $x, $y, $x1, $y1, $grid_color);
$theta = $theta - $thetac;
}
// -----------------------------------
// Write the text
// -----------------------------------
$use_font = ($font_path != '' AND file_exists($font_path) AND function_exists('imagettftext')) ? TRUE : FALSE;
if ($use_font == FALSE)
{
$font_size = 5;
$x = rand(0, $img_width/($length/3));
$y = 0;
}
else
{
$font_size = 16;
$x = rand(0, $img_width/($length/1.5));
$y = $font_size+2;
}
for ($i = 0; $i < strlen($word); $i++)
{
if ($use_font == FALSE)
{
$y = rand(0 , $img_height/2);
imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color);
$x += ($font_size*2);
}
else
{
$y = rand($img_height/2, $img_height-3);
imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_path, substr($word, $i, 1));
$x += $font_size;
}
}
// -----------------------------------
// Create the border
// -----------------------------------
imagerectangle($im, 0, 0, $img_width-1, $img_height-1, $border_color);
// -----------------------------------
// Generate the image
// -----------------------------------
$img_name = $now.'.jpg';
ImageJPEG($im, $img_path.$img_name);
$img = "<img src=\"$img_url$img_name\" width=\"$img_width\" height=\"$img_height\" style=\"border:0;\" alt=\" \" />";
ImageDestroy($im);
return array('word' => $word, 'time' => $now, 'image' => $img);
}
/* End of file captcha_pi.php */
/* Location: ./system/plugins/captcha_pi.php */
The whole tutorial is in the captcha_pi file. The captcha tutorial in the wiki works on a different script (a class).
try this, CodeIgniter Captcha User Guide

Resources