Without Symfony, this is how I post excel data to database.
// Include PHPExcel_IOFactory
require_once ('../Classes/PHPExcel/IOFactory.php');
$inputFileName = 'abc.xls';
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Insert row data array into your database of choice here
}
Now with the ExcelBundle, I am stuck. The documentation doesn't help me at all in this task. I've tried every advice given in similar questions and I cant manage to do this.
Creating an object from a file like the example below doesn't work at all:
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject('file.xls');
How to achieve this task?
I worked this out as follows:
Make sure the path Liuggio/ExcelBundle/Controller/FakeController.php exists
Make sure you update the app/config config.yml and routing.yml are updated with the provided files (Liuggio/ExcelBundle/Tests/app)
Assuming that you are updating the product table, Update the FakeController as follows:
<?php
namespace Liuggio\ExcelBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Product;
class FakeController extends Controller
{
public function insertAction()
{
$data = [];
$appPath = $this->container->getParameter('kernel.root_dir');
$file = realpath($appPath . '/../web/excelFiles/abc.xls');
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($file);
$sheet = $phpExcelObject->getActiveSheet()->toArray(null, true, true, true);
$em = $this->getDoctrine()->getManager();
$data['sheet'] = $sheet;
//READ EXCEL FILE CONTENT
foreach($sheet as $i=>$row) {
if($i !== 1) {
$product = new Product();
$product->setProductCode($row['A']);
$product->setProductName($row['B']);
$product->setProductRetailPrice($row['C']);
$product->setProductCost($row['D']);
$product->setProductTax($tax);
$product->setCategory($category);
//... and so on
$em->persist($product);
$em->flush();
//redirect appropriately
}
}
$data['obj'] = $phpExcelObject;
return $this->render('excel/read.html.twig', ['data' => $data ] );
}
}
Related
I'm getting a "The value you selected is not a valid choice." error for an Ajax modified field when I submit a custom altered node/add form. An "Illegal choice error is also written to the log. This a Drupal 9 version of an app that I developed using Drupal 7 which worked. The Ajax functionality is working. Why? How do I fix it?
I believe the error is coming from some Symfony code. I'm dynamically modifying two "select" form elements. The first doesn't appear to have the problem. I'm doing the same thing for both form elements.
function bncreports_form_node_bnc_message_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
$form['actions']['submit']['#submit'][] = 'bncreports_node_bnc_message_form_submit';
$form['#title'] = t('Create Contact Us');
$user = User::load(\Drupal::currentUser()->id());
$district_id = $user->get('field_district')->value;
$form['field_first_name']['widget'][0]['value']['#default_value'] = $user->get('field_first_name')->value;
$form['field_last_name']['widget'][0]['value']['#default_value'] = $user->get('field_last_name')->value;
$form['field_email']['widget'][0]['value']['#default_value'] = $user->getEmail();
$form['field_email']['widget'][0]['value']['#attributes'] = ['onblur' => 'this.value=this.value.toLowerCase();'];
$form['field_phone']['widget'][0]['value']['#default_value'] = $user->get('field_phone')->value;
$form['field_district']['widget'][0]['value']['#default_value'] = $district_id;
if (isset($form['field_district']['widget']['#default_value']))
$form['field_district']['widget']['#default_value'] = $district_id; // wtf?
if ($user->hasRole('administrator') || $user->hasRole('bnc_operator') || $user->hasRole('ao_user')) {
$form['field_office']['#access'] = false;
$form['field_office_name']['#access'] = false;
$form['field_office_names']['#access'] = false;
$form['field_site_codes']['#access'] = false;
$form['field_district']['widget']['#ajax'] = [
'event' => 'change',
'callback' => 'bncreports_ajax_offices_and_user',
'wrapper' => ['ajax-wrapper-field-offices', 'ajax-wrapper-field-user'],
];
$form['field_offices']['#prefix'] = '<div id="ajax-wrapper-field-offices">';
$form['field_offices']['#suffix'] = '</div>';
$form['field_user']['#prefix'] = '<div id="ajax-wrapper-field-user">';
$form['field_user']['#suffix'] = '</div>';
$district_id = $form_state->hasValue('field_district')
? $form_state->getValue('field_district')[0]['value']
: false;
$form['field_offices']['widget']['#options'] = $district_id
? Functions::officeNames($district_id)
: [];
$form['field_user']['widget']['#options'] = $district_id
? ['_none' => '- Select a value -'] + Functions::districtUserLastandFirstNames($district_id)
: ['_none' => '- Select a value -'];
} else { // Alterations for court users only
$form['bnc_prefix']['#markup'] =
'<p>BNC User Support: ' . Constants::BNC_PHONE_NO
. ' ' . Constants::BNC_EMAIL . '</p>'
. '<p>AO Program and CM/ECF Contacts</p>'
. '<h4>Unable to find what you need? Send us a message.</h4>';
$form['bnc_prefix']['#weight'] = -1;
$form['field_offices']['#access'] = false;
$form['field_office_name']['#access'] = false;
$form['field_office_names']['#access'] = false;
$form['field_site_codes']['#access'] = false;
$form['field_user']['#access'] = false;
$form['field_non_user_name']['#access'] = false;
$form['field_non_user_phone']['#access'] = false;
$form['field_assigned_to']['#access'] = false;
$form['revision_information']['#access'] = false;
$office = $user->get('field_office')->value;
$form['field_district']['widget']['#default_value'] = $district_id;
$form['field_office']['widget']['#options'] = Functions::officeNames($district_id);
$form['field_office']['widget']['#default_value'] = $office;
$form['field_office_name']['widget'][0]['value']['#default_value'] = Functions::officeName($district_id, $office);
$form['#attached']['library'][] = 'bncreports/restricted_contact_log';
}
}
function bncreports_ajax_offices_and_user(array $form, FormStateInterface $form_state): AjaxResponse
{
$response = new AjaxResponse();
// Issue a command that replaces the elements 'field_offices' and 'field_user'
$response->addCommand(new ReplaceCommand('#ajax-wrapper-field-office', $form['field_offices']));
$response->addCommand(new ReplaceCommand('#ajax-wrapper-field-user', $form['field_user']));
return $response;
}
Problem is there are no allowed values for the field_user list. Solution is to use an allowed values function callback. This is done in Configuration synchronization for Field Storage. Set the allowed value function property and import. Need to provide uuid to override existing config.
In my hook_form_alter:
$_SESSION['selected_district_id'] = $district_id;
In my xxx.module:
function bncreports_allowed_values_function(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable): array
{
// NOTE: This is defined in Configuation synchronization for Field Storage (see node.field_user)
if ($entity->bundle() == 'bnc_message') { // Add a custom field_user options for BNC Message nodes.
$district_id = $_SESSION['selected_district_id'] ?? null;
return Functions::districtUserLastandFirstNames($district_id);
}
throw new Exception("Allowed values function for {$entity->bundle()} is not allowed.");
}
I have a mysql database blog with 21 posts in it.
I set $maxPerPage = '3'; So I get 7 pages, but from page 4 I get the following error:
OutOfRangeCurrentPageException: Page "4" does not exist. The currentPage must be inferior to "3"
Here's my code:
public function indexAction($page)
{
$maxPerPage = '3';
$currentPage = $page;
$entityManager = $this->getDoctrine()->getManager();
$queryBuilder = $entityManager->createQueryBuilder()
->select(array('u')) // string 'u' is converted to array internally
->from('AppBundle:Blog', 'u');
$adapter = new DoctrineORMAdapter($queryBuilder);
$pagerfanta = new Pagerfanta($adapter);
if (!$page) $currentPage = '1';
try {
$pagerfanta->setCurrentPage($currentPage);
}
catch(NotValidCurrentPageException $e) {
throw new NotFoundHttpException('Illegal page');
}
$pagerfanta->setMaxPerPage($maxPerPage); // 10 by default
//$textblog = $this->getDoctrine()
//->getRepository('AppBundle:Blog')
//->find($page);
return $this->render('textblog/blog.html.twig',array('pagerfanta' => $pagerfanta));
}
Can anyone help please?
Stupid me...
$pagerfanta->setMaxPerPage($maxPerPage);
This code should be before the 'if'
I have regular Drupal Commerce setup with installed Feeds, Feeds Tamper and Commerce Feeds modules.
Here is tiny piece of the CSV file I'm trying to import:
SKU,Title,Price,Sizes,Model
JKR122/1,Red T-Shirt,44,"42,44,46",JKR122
JKR122/2,Blue T-Shirt,44,"42,44,46",JKR122
Is it possible using Feeds Tamper, to explode "Sizes" column and import each as separate product. Probably it will be needed to append exploded size to SKU.
I'm no pro in Excel, so if it is possible to easily reformat this huge CSV file, please tell me how.
As problem had to be solved today, I wrote PHP-script which reformats my CSV:
I'll leave question opened, in case anuone knows if this can be done by "Drupal-way".
<?php
define('ATTR_SIZE', 'Sizes');
define('ATTR_SKU', 'SKU');
define('IMPORT_FILE', 'import_file.csv');
define('EXPORT_FILE', 'export_file.csv');
define('CSV_DELIMITER', ',');
// Open csv
if(!file_exists(IMPORT_FILE) || !is_readable(IMPORT_FILE))
die('Check file');
$header = NULL;
$all_rows = array();
if (($handle = fopen(IMPORT_FILE, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, CSV_DELIMITER)) !== FALSE) {
if (!$header)
$header = $row;
else
$all_rows[] = array_combine($header, $row);
}
fclose($handle);
}
// Process csv
$new_rows = array();
foreach ($all_rows as $key => $row) {
if (!empty($row[ATTR_SIZE])) {
$original_row = $row;
$sizes = explode(',', $row[ATTR_SIZE]);
foreach ($sizes as $size) {
$trimmed_size = trim($size);
if (!empty($trimmed_size)) {
$row = $original_row;
$row[ATTR_SIZE] = $trimmed_size; // Save size
$row[ATTR_SKU] = $row[ATTR_SKU] . '/' . $trimmed_size; // Modify SKU
$new_rows[] = $row; // Add new row
}
}
}
else {
$new_rows[] = $row;
}
}
// Save csv
$header = NULL;
$handle = fopen(EXPORT_FILE, 'w');
foreach ($new_rows as $fields) {
if (!$header) {
fputcsv($handle, array_keys($fields));
$header = TRUE;
}
fputcsv($handle, $fields);
}
fclose($handle);
I use phpexcel in my project, if i call my class by my function, excel file cannot open
I call my class:
$Model = loadModel('cpm','cpm',$this->registry);
My function:
function loadModel($com='',$class_name='',$registry=null) {
if (empty($com)){
$com = 'admin';
}
$filename = strtolower($class_name) . '.class.php';
$file = PATH_MODEL.DS.$com.DS.$filename;
if (file_exists($file) == false){
return false;
}
require_once($file);
if($registry != NULL){
$model = new $class_name($registry);
}else{
$model = new $class_name;
}
return $model;
}
When i change to
/*require_once($file);
if($registry != NULL){
$model = new $class_name($registry);
}else{
$model = new $class_name;
}*/
$model=true;
return $model;
it work. In my project, I use autoload:
function __autoload($class_name) {
/*** get the component from the url ***/
$com = (empty($_GET['com'])) ? '' : $_GET['com'];
if (empty($com)){
$com = 'admin';
}
$filename = strtolower($class_name) . '.class.php';
$file = PATH_MODEL.DS.$com.DS.$filename;
if (file_exists($file) == false){
return false;
}
requine_once ($file);
}
I am not sure it is reason.
I don't found any error in log.
Any help, thank.
I found that if I require(once) or include(once) file in controler, excel file will be can not open.
class excelController extends baseController {
public function index(){
require('abc.class.php');
$this->registry->template->show('excel', false);
}
}
It's probable that your autoloader is clashing with PHPExcel's autoloader. See section 3.2 of the developer documentation (entitled "Lazy Loader") for advice on registering your own autoloader with spl_autoload_register() so that the two can co-exist
I have a site that is using both WordPress and Opencart. The main site is built off of WP and then there is an OC site in a sub-directory.
I would like to bring the session data from OC into the wordpress site so I can have the Wishlist, Shopping Cart, Checkout, Login status and My Account info throughout the site.
Does anyone know what code I can add to WP to bring in this info?
Thanks again in advance,
Matt
There are already many articles regarding module development and export and session building in OpenCart.
Given your existing pages:
yoursite.com/wordpress
yoursite.com/wordpress/page.php (i.e. your page outside the shop),
yoursite.com/products/catalog/controller/common/header.php -and-
yoursite/products/catalog/view/theme/default/template/common/header.tpl
1. Create file headerXYZ.php using the following code and save it to the root directory of your main site (or other location of your choosing outside your OC shop).
<?php
// Config
require_once('shop/config.php');
// VirtualQMOD
require_once('shop/vqmod/vqmod.php');
$vqmod = new VQMod();
// VQMODDED Startup
require_once($vqmod->modCheck(DIR_SYSTEM . 'startup.php'));
// Application Classes
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/customer.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/affiliate.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/currency.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/tax.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/weight.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/length.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/cart.php'));
$myVar = array();
$myVar = array();
// Registry
$registry = new Registry();
// Loader
$loader = new Loader($registry);
$registry->set('load', $loader);
// Config
$config = new Config();
$registry->set('config', $config);
// Database
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);
// Url
$url = new Url($config->get('config_url'), $config->get('config_use_ssl') ? $config->get('config_ssl') :
$config->get('config_url'));
$registry->set('url', $url);
// Log
$log = new Log($config->get('config_error_filename'));
$registry->set('log', $log);
function error_handler($errno, $errstr, $errfile, $errline) {
global $log, $config;
switch ($errno) {
case E_NOTICE:
case E_USER_NOTICE:
$error = 'Notice';
break;
case E_WARNING:
case E_USER_WARNING:
$error = 'Warning';
break;
case E_ERROR:
case E_USER_ERROR:
$error = 'Fatal Error';
break;
default:
$error = 'Unknown';
break;
}
if ($config->get('config_error_display')) {
echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
}
if ($config->get('config_error_log')) {
$log->write('PHP ' . $error . ': ' . $errstr . ' in ' . $errfile . ' on line ' . $errline);
}
return true;
}
// Error Handler
set_error_handler('error_handler');
// Request
$request = new Request();
$registry->set('request', $request);
// Response
$response = new Response();
$response->addHeader('Content-Type: text/html; charset=utf-8');
$response->setCompression($config->get('config_compression'));
$registry->set('response', $response);
// Cache
$cache = new Cache();
$registry->set('cache', $cache);
// Session
$session = new Session();
$registry->set('session', $session);
// Language Detection
$languages = array();
$query = $db->query("SELECT * FROM " . DB_PREFIX . "language");
foreach ($query->rows as $result) {
$languages[$result['code']] = $result;
}
$detect = '';
if (isset($request->server['HTTP_ACCEPT_LANGUAGE']) && ($request->server['HTTP_ACCEPT_LANGUAGE'])) {
$browser_languages = explode(',', $request->server['HTTP_ACCEPT_LANGUAGE']);
foreach ($browser_languages as $browser_language) {
foreach ($languages as $key => $value) {
if ($value['status']) {
$locale = explode(',', $value['locale']);
if (in_array($browser_language, $locale)) {
$detect = $key;
}
}
}
}
}
if (isset($request->get['language']) && array_key_exists($request->get['language'], $languages) &&
$languages[$request->get['language']]['status']) {
$code = $request->get['language'];
} elseif (isset($session->data['language']) && array_key_exists($session->data['language'], $languages)) {
$code = $session->data['language'];
} elseif (isset($request->cookie['language']) && array_key_exists($request->cookie['language'], $languages)) {
$code = $request->cookie['language'];
} elseif ($detect) {
$code = $detect;
} else {
$code = $config->get('config_language');
}
if (!isset($session->data['language']) || $session->data['language'] != $code) {
$session->data['language'] = $code;
}
if (!isset($request->cookie['language']) || $request->cookie['language'] != $code) {
setcookie('language', $code, time() + 60 * 60 * 24 * 30, '/', $request->server['HTTP_HOST']);
}
$config->set('config_language_id', $languages[$code]['language_id']);
$config->set('config_language', $languages[$code]['code']);
// Language
$language = new Language($languages[$code]['directory']);
$language->load($languages[$code]['filename']);
$registry->set('language', $language);
// Document
$document = new Document();
$registry->set('document', $document);
// Customer
$registry->set('customer', new Customer($registry));
// Affiliate
$affiliate = new Affiliate($registry);
$registry->set('affiliate', $affiliate);
if (isset($request->get['tracking']) && !isset($request->cookie['tracking'])) {
setcookie('tracking', $request->get['tracking'], time() + 3600 * 24 * 1000, '/');
}
// Currency
$registry->set('currency', new Currency($registry));
// Tax
$tax = new Tax($registry);
$registry->set('tax', $tax);
// Weight
$registry->set('weight', new Weight($registry));
// Length
$registry->set('length', new Length($registry));
// Cart
$registry->set('cart', new Cart($registry));
// Front Controller
$controller = new Front($registry);
// Maintenance Mode
$controller->addPreAction(new Action('common/maintenance'));
// SEO URL's
$controller->addPreAction(new Action('common/seo_url'));
// Router
if (isset($request->get['route'])) {
$action = new Action($request->get['route']);
} else {
$action = new Action('common/home');
}
// Dispatch
$controller->dispatch($action, new Action('error/not_found'));
2. Now, include headerXYZ.php in page.php i.e. Place the statement below on line 1 at the very top of page.php
<?php require_once ('headerXYZ.php');?>
3. Finally, right after the opening body tag of your external page.php page add the following list of statements
<?php
require_once('shop/catalog/model/total/sub_total.php');
require_once('shop/catalog/language/english/total/sub_total.php');
require_once('shop/catalog/model/total/reward.php');
require_once('shop/catalog/model/total/shipping.php');
require_once('shop/catalog/model/total/coupon.php');
require_once('shop/catalog/model/total/tax.php');
require_once('shop/catalog/model/total/credit.php');
require_once('shop/catalog/language/english/total/credit.php');
require_once('shop/catalog/model/total/voucher.php');
require_once('shop/catalog/model/total/total.php');
require_once('shop/catalog/language/english/total/total.php');
foreach($myVar as $key=>$value)
{
$$key = $value;
}
require_once('shop/catalog/controller/common/header.php');
require_once('shop/catalog/view/theme/default/template/common/header.tpl');
?>
That's it... You're done! You should now have a fully functional header (with working cart, login, etc.) in your page located outside of your Opencart shop.
SIDE NOTE: You could also just plug the entire code (including the content of headerXYZ.php and the 13 require_once statements) directly into the your external page.
I was looking for something similar, what I did was to write same html/css for footer and header in both systems, after that, I wrote an additional Wordpress plugin to show user and cart info when user is logged in opencart.
https://github.com/saRca/op2wp