Quickbooks Webconnector Delays 10+ minutes before each import - quickbooks

I have a portal that we use to import invoices, customers and vendors into Quickbooks using web connector. The import is successful, however, after we submit each new entry their is a 10+ minute delay from the time we submit to the time the entry is imported into Quickbooks.
Please find my QWC File Code, Que Table and Logs.
QWClog File
below is my controller i use to import data in quickbooks
class QuickBooks extends CI_Controller
{
public function __construct()
{
parent::__construct();
// QuickBooks config
$this->load->config('quickbooks');
// Load your other models here...
//$this->load->model('yourmodel1');
//$this->load->model('yourmodel2');
//$this->load->model('yourmodel3');
}
/**
* Generate and return a .QWC Web Connector configuration file
*/
public function config()
{
$name = 'test_site Web Connect'; // A name for your server (make it whatever you want)
$descrip = 'test_site Web Connect'; // A description of your server
$appurl = 'https://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/qbwc'; // This *must* be httpS:// (path to your QuickBooks SOAP server)
$appsupport = $appurl; // This *must* be httpS:// and the domain name must match the domain name above
$username = $this->config->item('quickbooks_user'); // This is the username you stored in the 'quickbooks_user' table by using QuickBooks_Utilities::createUser()
$fileid = QuickBooks_WebConnector_QWC::fileID(); // Just make this up, but make sure it keeps that format
$ownerid = QuickBooks_WebConnector_QWC::ownerID(); // Just make this up, but make sure it keeps that format
$qbtype = QUICKBOOKS_TYPE_QBFS; // You can leave this as-is unless you're using QuickBooks POS
$readonly = false; // No, we want to write data to QuickBooks
$run_every_n_seconds = 60; // Run every 60 seconds (1 minute)
// Generate the XML file
$QWC = new QuickBooks_WebConnector_QWC($name, $descrip, $appurl, $appsupport, $username, $fileid, $ownerid, $qbtype, $readonly, $run_every_n_seconds);
$xml = $QWC->generate();
// Send as a file download
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="my-quickbooks-wc-file.qwc"');
print($xml);
exit;
}
/**
* SOAP endpoint for the Web Connector to connect to
*/
public function qbwc()
{
$user = $this->config->item('quickbooks_user');
$pass = $this->config->item('quickbooks_pass');
// Memory limit
ini_set('memory_limit', $this->config->item('quickbooks_memorylimit'));
// We need to make sure the correct timezone is set, or some PHP installations will complain
if (function_exists('date_default_timezone_set'))
{
// * MAKE SURE YOU SET THIS TO THE CORRECT TIMEZONE! *
// List of valid timezones is here: http://us3.php.net/manual/en/timezones.php
date_default_timezone_set($this->config->item('quickbooks_tz'));
}
// Build the database connection string
//$dsn = 'mysqli://devstagetest_site_qbuser:6Y_9aI#PBSrF#50.62.57.212/devstagetest_site_qb_database'; // dev
$dsn = 'mysqli://test_site_qbuser:r1R1aQ;gcE%;#50.62.57.212/test_site_qb_database'; // live
// Map QuickBooks actions to handler functions
$map = array(
QUICKBOOKS_ADD_CUSTOMER => array( array( $this, '_addCustomerRequest' ), array( $this, '_addCustomerResponse' ) ),
QUICKBOOKS_ADD_INVOICE => array( array( $this, '_invoice_add_request' ), array( $this, '_invoice_add_response' ) ),
QUICKBOOKS_ADD_VENDOR => array( array( $this, '_vendor_add_request' ), array( $this, '_vendor_add_response' ) ),
);
// Catch all errors that QuickBooks throws with this function
$errmap = array(
3070 => array( $this,'_quickbooks_error_stringtoolong'),
'InvoiceAdd' => array( $this,'_quickbooks_error_invoiceadd'),
'CustomerAdd' => array( $this,'_quickbooks_error_customeradd'),
'VendorAdd' => array( $this,'_quickbooks_error_vendoradd'),
500 => array( $this,'cust_not_exist'),
3100 => array( $this,'cust_already_exist'),
'*' => array( $this, '_catchallErrors' ),
);
// Call this method whenever the Web Connector connects
$hooks = array(
//QuickBooks_WebConnector_Handlers::HOOK_LOGINSUCCESS => array( array( $this, '_loginSuccess' ) ), // Run this function whenever a successful login occurs
);
// An array of callback options
$callback_options = array();
// Logging level
$log_level = $this->config->item('quickbooks_loglevel');
// What SOAP server you're using
//$soapserver = QUICKBOOKS_SOAPSERVER_PHP; // The PHP SOAP extension, see: www.php.net/soap
$soapserver = QUICKBOOKS_SOAPSERVER_BUILTIN; // A pure-PHP SOAP server (no PHP ext/soap extension required, also makes debugging easier)
$soap_options = array( // See http://www.php.net/soap
);
$handler_options = array(
'deny_concurrent_logins' => false,
); // See the comments in the QuickBooks/Server/Handlers.php file
$driver_options = array( // See the comments in the QuickBooks/Driver/<YOUR DRIVER HERE>.php file ( i.e. 'Mysql.php', etc. )
'max_log_history' => 32000, // Limit the number of quickbooks_log entries to 1024
'max_queue_history' => 1024, // Limit the number of *successfully processed* quickbooks_queue entries to 64
);
// Check to make sure our database is set up
if (!QuickBooks_Utilities::initialized($dsn))
{
// Initialize creates the neccessary database schema for queueing up requests and logging
QuickBooks_Utilities::initialize($dsn);
// This creates a username and password which is used by the Web Connector to authenticate
QuickBooks_Utilities::createUser($dsn, $user, $pass);
}
// Set up our queue singleton
QuickBooks_WebConnector_Queue_Singleton::initialize($dsn);
// Create a new server and tell it to handle the requests
// __construct($dsn_or_conn, $map, $errmap = array(), $hooks = array(), $log_level = QUICKBOOKS_LOG_NORMAL, $soap = QUICKBOOKS_SOAPSERVER_PHP, $wsdl = QUICKBOOKS_WSDL, $soap_options = array(), $handler_options = array(), $driver_options = array(), $callback_options = array()
$Server = new QuickBooks_WebConnector_Server($dsn, $map, $errmap, $hooks, $log_level, $soapserver, QUICKBOOKS_WSDL, $soap_options, $handler_options, $driver_options, $callback_options);
$response = $Server->handle(true, true);
}
function _invoice_add_request($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $version, $locale) {
$record = $this->db->query("SELECT * FROM qb_add_invoice WHERE id = '".$ID."'")->row();
if(count($record)>0){
$orderid = $record->orderID;
$uordername = $record->uordername;
$xplode_data = explode("_", $uordername);
$sendfrom = $record->sendfrom;
$notary_fee = $record->notary_fee;
$test_site_fee = $record->test_site_fee;
$orders_record = $this->db->query("SELECT * FROM orders WHERE orderID = '".$orderid."'")->row();
$Addr1 ='';
$Addr2 = '';
if($sendfrom == 'Notary'){
$notary_record = $this->db->query("SELECT * FROM notaryRegis WHERE notaryID = '".$orders_record->notaryID."'")->row();
if($notary_record->state > 0){
$stateRow = $this->db->query("select * from state where stateID = '".$notary_record->state."'")->row();
$stateName= $stateRow->stateName;
}
else {
$stateName= "";
}
$FullName = trim($notary_record->lastName).', '.trim($notary_record->firstName);
$Addr1 =$FullName;
$Addr2 = $notary_record->streetAddress;
$City = $notary_record->city;
$State = $stateName;
$PostalCode = $notary_record->zip;
$PONumber = $notary_record->lastName;
$Rate = number_format((float)$notary_fee, 2, '.', '');;
}
else if($sendfrom == 'Client'){
$client_record = $this->db->query("SELECT
cr. *,
zf.fee AS client_test_site_fee
FROM
customer_table cr
LEFT JOIN test_site_fees zf
ON(cr.serviceType = zf.type)
WHERE
cr.clientID = '".$orders_record->clientID."'")->row();
$FullName = trim($client_record->company).'-'.trim($client_record->firstName).' '.trim($client_record->lastName);
$Addr1 = substr($client_record->mailingAddress, 0, 39);
$Addr2 = '';
$City = $client_record->city;
$State = $client_record->state;
$PostalCode = $client_record->zip;
$PONumber = $orders_record->customerLastName;
$Rate = $notary_fee+$client_record->client_test_site_fee;
}
$TxnDate = explode(" ",$orders_record->RequestedAppointmentDate);
$TxnDate = $TxnDate[0];
if($TxnDate == '0000-00-00'){
$TxnDate = date('Y-m-d');
}else{
$TxnDate = date('Y-m-d', strtotime($TxnDate));
}
$RefNumber = $orders_record->escrowNumber;
$Bill = $orders_record->loanPackageType;
if($sendfrom == 'Client'){
/* $xml = '<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="13.0"?>
<QBXML>
<QBXMLMsgsRq onError="continueOnError">
<InvoiceAddRq requestID="' . $requestID . '">
<InvoiceAdd>
<CustomerRef>
<FullName>'.$FullName.'</FullName>
</CustomerRef>
<TxnDate>'.$TxnDate.'</TxnDate>
<RefNumber>' . $RefNumber.'</RefNumber>
<BillAddress>
<Addr1>'.$FullName.'</Addr1>
<Addr2>'.$Addr1.'</Addr2>
<City>'.$City.'</City>
<State>'.$State.'</State>
<PostalCode>'.$PostalCode.'</PostalCode>
<Country></Country>
</BillAddress>
<PONumber>'.$orders_record->customerLastName.'</PONumber>
<TermsRef>
<FullName>'.$FullName.'</FullName>
</TermsRef>
<DueDate>' . $TxnDate . '</DueDate>
<InvoiceLineAdd>
<ItemRef>
<FullName>Bill:test_site Fee</FullName>
</ItemRef>
<Rate>' . $Rate.'</Rate>
</InvoiceLineAdd>
</InvoiceAdd>
</InvoiceAddRq>
</QBXMLMsgsRq>
</QBXML>';
*/
$xml = '<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="2.0"?>
<QBXML>
<QBXMLMsgsRq onError="stopOnError">
<InvoiceAddRq requestID="' . $requestID . '">
<InvoiceAdd>
<CustomerRef>
<FullName>'.$FullName.'</FullName>
</CustomerRef>
<TxnDate>' . $TxnDate . '</TxnDate>
<RefNumber>' . $RefNumber.'</RefNumber>
<ShipAddress>
<Addr1>'.trim($orders_record->customerFirstName).' '.trim($orders_record->customerLastName).'</Addr1>
<Addr2>'.$orders_record->signingAddress.'</Addr2>
<City>'.$orders_record->city.'</City>
<State>'.$this->db->get_where('state', "stateID = $orders_record->state", 1)->row()->stateName.'</State>
<PostalCode>'.$orders_record->zip.'</PostalCode>
<Country></Country>
</ShipAddress>
<PONumber>'.$orders_record->customerLastName.'</PONumber>
<TermsRef>
<FullName>Net 30</FullName>
</TermsRef>
<DueDate>' . $TxnDate . '</DueDate>
<InvoiceLineAdd>
<ItemRef>
<FullName>test_site Fee</FullName>
</ItemRef>
<Rate>' . $Rate.'</Rate>
</InvoiceLineAdd>
</InvoiceAdd>
</InvoiceAddRq>
</QBXMLMsgsRq>
</QBXML>';
}
else if($sendfrom == 'Notary'){
$xml = '<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="2.0"?>
<QBXML>
<QBXMLMsgsRq onError="continueOnError">
<BillAddRq requestID="' . $requestID . '">
<BillAdd>
<VendorRef>
<FullName>' .$FullName.'</FullName>
</VendorRef>
<TxnDate>' . $TxnDate . '</TxnDate>
<DueDate>' . $TxnDate . '</DueDate>
<RefNumber>' . $RefNumber.'</RefNumber>
<TermsRef>
<FullName>Net 15</FullName>
</TermsRef>
<ExpenseLineAdd>
<AccountRef>
<FullName>Outside Services:Loan Signing Fee</FullName>
</AccountRef>
<Amount>' . $Rate.'</Amount>
</ExpenseLineAdd>
</BillAdd>
</BillAddRq>
</QBXMLMsgsRq>
</QBXML>';
}
/*$this->email->from('info#test_site.com');
$this->email->to('jaihind530#gmail.com');
$this->email->cc('shehrozasmat005#gmail.com');
$this->email->subject("test_site : invoice XML");
$this->email->message($xml);
$this->email->send();*/
// storing xml for the loging
return $xml;
}
else {
$this->db->query("DELETE from qb_add_invoice WHERE id = '".$ID."'");
return true;
}
}
public function _invoice_add_response($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $xml, $idents)
{
$this->db->query("UPDATE qb_add_invoice SET status=1, updated_at = '".date("Y-m-d H:i:s")."' WHERE id = '".$ID."'");
$record = $this->db->query("SELECT sendfrom,orderID FROM qb_add_invoice WHERE id = '".$ID."'")->row();
$orecord = $this->db->query("SELECT clientID,notaryID FROM orders WHERE orderID = '".$record->orderID."'")->row();
if($record->sendfrom == 'Notary'){
$crecord = $this->db->query("SELECT firstName,lastName FROM notaryRegis WHERE notaryID = '".$orecord->notaryID."'")->row();
}
else {
$crecord = $this->db->query("SELECT firstName,lastName FROM customer_table WHERE clientID = '".$orecord->clientID."'")->row();
}
return "";
}
function _quickbooks_error_invoiceadd($requestID, $user, $action, $ID, $extra, &$err, $xml, $errnum, $errmsg) {
$this->db->query("DELETE from qb_add_invoice WHERE id = '".$ID."'");
return false;
}
/**
* Issue a request to QuickBooks to add a customer
*/
public function _addCustomerRequest($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $version, $locale)
{
$qb_add_cust = $this->db->query("SELECT * FROM qb_add_cust WHERE id = '".$ID."'")->row();
$record = $this->db->query("SELECT * FROM customer_table WHERE clientID = '".$qb_add_cust->clientID."'")->row();
if(count($record)>0){
// Build the qbXML request from $data
$xml = '<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="2.0"?>
<QBXML>
<QBXMLMsgsRq onError="continueOnError">
<CustomerAddRq requestID="' . $requestID . '">
<CustomerAdd>
<Name>'.trim($record->company).'-'.trim($record->firstName).' '.trim($record->lastName).'</Name>
<CompanyName>' . trim($record->company) . '</CompanyName>
<FirstName>'.trim($record->firstName).'</FirstName>
<LastName>'.trim($record->lastName).'</LastName>
<BillAddress>
<Addr1>'.trim(substr($record->mailingAddress,0,39)).'</Addr1>
<Addr2></Addr2>
<City>'.trim($record->city).'</City>
<State>'.trim($record->state).'</State>
<PostalCode>'.trim($record->zip).'</PostalCode>
<Country></Country>
</BillAddress>
<Phone>'.$record->businessPhone.'</Phone>
<AltPhone></AltPhone>
<Fax></Fax>
<Email>'.$record->email.'</Email>
</CustomerAdd>
</CustomerAddRq>
</QBXMLMsgsRq>
</QBXML>';
// storing xml for the loging
return $xml;
}
else {
//$this->db->query("DELETE from qb_add_cust WHERE id = '".$ID."'");
return true;
}
}
/**
* Handle a response from QuickBooks indicating a new customer has been added
*/
public function _addCustomerResponse($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $xml, $idents)
{
$this->db->query("UPDATE qb_add_cust SET ListID = '".$idents['ListID']."' , status=1, updated_at = '".date("Y-m-d H:i:s")."' WHERE id = '".$ID."'");
$qb_add_cust = $this->db->query("SELECT * FROM qb_add_cust WHERE id = '".$ID."'")->row();
$record = $this->db->query("SELECT * FROM customer_table WHERE clientID = '".$qb_add_cust->clientID."'")->row();
return true;
}
function _quickbooks_error_customeradd($requestID, $user, $action, $ID, $extra, &$err, $xml, $errnum, $errmsg) {
$this->db->query("DELETE from qb_add_cust WHERE id = '".$ID."'");
return true;
}
function _vendor_add_request($requestID, $user, $action, $ID, $extra, & $err, $last_action_time, $last_actionident_time, $xml, $idents)
{
$qb_add_vendor = $this->db->get_where("qb_add_vendor", "id = $ID")->row();
/*$ins['request_id'] = $requestID;
$ins['import'] = $ID;
$ins['operation_xml'] = implode('==',$qb_add_vendor);
$ins['operation_type'] = 'pre_add_vendor_failed';
$this->db->insert('qb_operations_xml_response', $ins);*/
$record = $this->db->query("SELECT * FROM notaryRegis WHERE notaryID = '".$qb_add_vendor->notaryID."'")->row();
if(!empty($record)){
$pay = "";
$cell = $record->phone;
if($record->state > 0){
$stateRow = $this->db->query("select * from state where stateID = '".$record->state."'")->row();
$stateName= $stateRow->stateName;
}
else {
$stateName= "";
}
$address1 = str_replace('-', ' ',$record->streetAddress);
$address2 = '';
$city = $record->city;
$zip1 = $record->zip;
// Create and return a qbXML request
$xml = '<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="13.0"?>
<QBXML>
<QBXMLMsgsRq onError="StopOnError">
<VendorAddRq requestID="' . $requestID . '">
<VendorAdd>
<Name>' .trim($record->lastName).', '.trim($record->firstName).'</Name>
<CompanyName></CompanyName>
<FirstName>'.trim($record->firstName).'</FirstName>
<LastName>'.trim($record->lastName).'</LastName>
<VendorAddress>
<Addr1>'.trim($record->firstName).' '.trim($record->lastName).'</Addr1>
<Addr2>'.substr($address1,0, 35).'</Addr2>
<Addr3></Addr3>
<City>'.$city.'</City>
<State>'.$stateName.'</State>
<PostalCode>'.$zip1.'</PostalCode>
<Country></Country>
</VendorAddress>
<Phone>'.$cell.'</Phone>
<AltPhone></AltPhone>
<Fax></Fax>
<Email>'.$record->email.'</Email>
<VendorTaxIdent></VendorTaxIdent>
<IsVendorEligibleFor1099>true</IsVendorEligibleFor1099>
</VendorAdd>
</VendorAddRq>
</QBXMLMsgsRq>
</QBXML>';
// storing xml for the loging
return $xml;
}
else
{
$this->db->query("DELETE from qb_add_vendor WHERE id = '".$ID."'");
return "";
}
}
function _vendor_add_response($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $xml, $idents)
{
$this->db->query("UPDATE qb_add_vendor SET ListID = '".$idents['ListID']."' , status=1, updated_at = '".date("Y-m-d H:i:s")."' WHERE id = '".$ID."'");
$qb_add_vendor = $this->db->query("SELECT * FROM qb_add_vendor WHERE id = '".$ID."'")->row();
$ins['request_id'] = $requestID;
$ins['import'] = $ID;
$ins['operation_xml'] = implode('==', $qb_add_vendor);
$ins['operation_type'] = 'add_vendor_response';
$this->db->insert('qb_operations_xml_response', $ins);
$record = $this->db->query("SELECT * FROM notaryRegis WHERE notaryID = '".$qb_add_vendor->notaryID."'")->row();
return "";
}
function _quickbooks_error_vendoradd($requestID, $user, $action, $ID, $extra, &$err, $xml, $errnum, $errmsg)
{
$this->db->query("DELETE from qb_add_vendor WHERE id = '".$ID."'");
return false;
}
function _quickbooks_error_stringtoolong($requestID, $user, $action, $ID, $extra, &$err, $xml, $errnum, $errmsg)
{
if($action == "InvoiceAdd")
{
$sql1="DELETE from qb_add_invoice WHERE id = '".$ID."'";
}
if($action == "CustomerAdd")
{
$sql1="DELETE from qb_add_cust WHERE id = '".$ID."'";
}
if($action == "VendorAdd")
{
$sql1="DELETE from qb_add_vendor WHERE id = '".$ID."'";
}
return true;
}
/**
* Catch and handle errors from QuickBooks
*/
public function _catchallErrors($requestID, $user, $action, $ID, $extra, &$err, $xml, $errnum, $errmsg)
{
if($action == "InvoiceAdd")
{
$sql1="DELETE from qb_add_invoice WHERE id = '".$ID."'";
}
if($action == "CustomerAdd")
{
$sql1="DELETE from qb_add_cust WHERE id = '".$ID."'";
}
if($action == "VendorAdd")
{
$sql1="DELETE from qb_add_vendor WHERE id = '".$ID."'";
}
$this->db->query($sql1);
$admin_template = '<p>'.$errmsg.'</p>';
$this->email->from('info#test_site.com');
$this->email->to('adam#test_site.com');
$this->email->subject('test_site : Error to send in Quickbooks');
$this->email->message($admin_template);
$this->email->send();
return true;
}
function cust_already_exist($requestID, $user, $action, $ID, $extra, &$err, $xml, $errnum, $errmsg)
{
$qb_add_cust = $this->db->query("SELECT * FROM qb_add_cust WHERE id = '".$ID."'")->row();
$customer_table = $this->db->query("SELECT * FROM customer_table WHERE clientID = '" .$qb_add_cust->clientID."'")->row();
$this->db->query("UPDATE qb_add_cust SET status=1, updated_at = '".date("Y-m-d H:i:s")."' WHERE id = '".$ID."'");
return true;
}
function cust_not_exist($requestID, $user, $action, $ID, $extra, &$err, $xml, $errnum, $errmsg)
{
$this->db->query("DELETE from qb_add_invoice WHERE id = '".$ID."'");
return true;
}
/**
* Whenever the Web Connector connects, do something (e.g. queue some stuff up if you want to)
*/
public function _loginSuccess($requestID, $user, $hook, &$err, $hook_data, $callback_config)
{
return true;
}
}

Related

How to implement acl and authorization in Module.php in zf3

I am working on Album Application in zf3.I added acl functionality to the application like this:
AlbumController.php
class AlbumController extends AbstractActionController
{
protected $role;
public function onDispatch(\Zend\Mvc\MvcEvent $e)
{
$userSession = new Container('user');
if (!isset($userSession->email)) {
return $this->redirect()->toRoute('login');
}
else {
$this->role = $userSession->role;
parent::onDispatch($e);
}
}
public function checkPermission($role,$action)
{
if($role == 'admin'){
$acl = new Acl();
if ($acl->isAllowed('admin', 'AlbumController', $action)) {
return true;
}
}
return false;
}
public function editAction()
{
$action = 'edit';
$permission = $this->checkPermission($this->role,$action);
if (!$permission) {
$this->flashMessenger()->addMessage('<div class="alert alert- danger" role="alert"><b>You dont have the privilege to edit!!</b></div>');
return $this->redirect()->toRoute('album');
}
$id = (int) $this->params()->fromRoute('id', 0);
if (0 === $id) {
return $this->redirect()->toRoute('album', ['action' => 'add']);
}
try {
$album = $this->table->getAlbum($id);
} catch (\Exception $e) {
return $this->redirect()->toRoute('album', ['action' => 'index']);
}
$form = new AlbumForm();
$form->bind($album);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
$viewData = ['id' => $id, 'form' => $form];
if (! $request->isPost()) {
return $viewData;
}
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
$edit = $request->getPost('submit', 'Cancel');
if($edit == 'Cancel'){
$this->flashMessenger()->addMessage('<div class="alert alert-danger" role="alert"><b>Cancelled by User...!!</b></div>');
return $this->redirect()->toRoute('album');
}
if (! $form->isValid()) {
$this->flashMessenger()->addMessage('<div class="alert alert-danger" role="alert"><b>Failed to Update...!!</b></div>');
return $viewData;
}else{
$this->table->saveAlbum($album);
$this->flashMessenger()->addMessage('<div class="alert alert-success" role="alert"><b>Record Updated Successfully...!!</b></div>');
}
// Redirect to album list
return $this->redirect()->toRoute('album', ['action' => 'index']);
}
}
This is working perfectly fine,now i want to move the onDispatch function to Module.php but don't know how to implement it.Can someone please help me
Module.php
<?php
namespace Album;
use Album\Controller\AlbumController;
use Album\Model\Album;
use Album\Model\AlbumTable;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Album\Model\LoginTable;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return [
'factories' => [
AlbumTable::class => function($container) {
$tableGateway = $container->get(Model\AlbumTableGateway::class);
return new AlbumTable($tableGateway);
},
Model\AlbumTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
Model\LoginTable::class => function($container) {
$tableGateway = $container->get(Model\LoginTableGateway::class);
$table = new LoginTable($tableGateway);
return $table;
},
Model\LoginTableGateway::class => function ($container){
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
return new TableGateway('login', $dbAdapter, null, $resultSetPrototype);
}
],
];
}
public function getControllerConfig()
{
return [
'factories' => [
Controller\AlbumController::class => function($container) {
return new Controller\AlbumController($container->get(Model\AlbumTable::class));
},
Controller\LoginController::class => function($container) {
return new Controller\LoginController($container->get(Model\LoginTable::class));
},
Controller\LogoutController::class => function($container){
return new Controller\LogoutController($container->get(Model\LoginTable::class));
},
],
];
}
}
This is how I implemented it. In your Module.php, add a listener on EVENT_DISPATCH, with a closure as callback that will call your middleware class authorization :
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function onBootstrap(MvcEvent $e)
{
$app = $e->getApplication();
$eventManager = $app->getEventManager();
$serviceManager = $app->getServiceManager();
// Register closure on event DISPATCH, call your checkProtectedRoutes() method
$eventManager->attach(MvcEvent::EVENT_DISPATCH, function (MvcEvent $e) use ($serviceManager) {
$match = $e->getRouteMatch();
$auth = $serviceManager->get(Middleware\AuthorizationMiddleware::class);
$res = $auth->checkProtectedRoutes($match);
if ($res instanceof Response) {
return $res;
}
}, 1);
// Init ACL : could be improved
$this->initAcl($e);
}
You should have an AuthorizationMiddlewareFactory (call it as you want):
<?php
namespace MyModule\Factory;
use Interop\Container\ContainerInterface;
use MyModule\Middleware\AuthorizationMiddleware;
use Zend\Authentication\AuthenticationService;
use Zend\ServiceManager\Factory\FactoryInterface;
class AuthorizationMiddlewareFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$authService = $container->get(AuthenticationService::class);
$acl = $container->get('Acl'); // II init it in bootstrap(), could be improved
$response = $container->get('Response');
$baseUrl = $container->get('Request')->getBaseUrl();
$authorization = new AuthorizationMiddleware($authService, $acl, $response, $baseUrl);
return $authorization ;
}
}
And your AuthorizationMiddleware class:
<?php
namespace MyModule\Middleware;
use Symfony\Component\VarDumper\VarDumper;
use Zend\Authentication\AuthenticationService;
use Zend\Http\PhpEnvironment\Response;
use Zend\Permissions\Acl\Acl;
use Zend\Router\RouteMatch;
class AuthorizationMiddleware
{
private $authService ;
private $acl;
private $response;
private $baseUrl;
/**
* AuthorizationMiddleware constructor.
* #param AuthenticationService $authService
* #param Acl $acl
* #param Response $response
* #param $baseUrl
*/
public function __construct(AuthenticationService $authService, Acl $acl, Response $response, $baseUrl)
{
$this->authService = $authService;
$this->acl = $acl;
$this->response = $response;
$this->baseUrl = $baseUrl;
}
public function checkProtectedRoutes(RouteMatch $match)
{
if (! $match) {
// Nothing without a route
return null ;
}
// Do your checks...
}
It can be improved, but you have the idea... See also this Question and the answers: ZF3 redirection after ACL authorization failed

ZEND This result is a forward only result set, calling rewind() after moving forward is not supported

I have this error after this code to :
This result is a forward only result set, calling rewind() after moving forward is not supported.
Page.phtml :
foreach ($company as $key => $value)
{
foreach ($userfeature as $key => $data)
{
echo "<tr>";
if($value->site_id == $data->site_id)
{
echo "<td>".$value->party_code." ".$value->party_name. "</td>";
}
}
}
Controller.php
public function indexsiteuserAction()
{
$this->layout('layout/admin');
$compteAdmin[] = $this->admincompte();
$user_id = (int) $this->params()->fromRoute('id', 0);
if (!$user_id)
{
return $this->redirect()->toRoute('administrateur', array('action' => 'adduser'));
}
try
{
$user = $this->getUserTable()->getUser($user_id);
$userfeature = $this->getAdminUserFeatureTable()->afficheruserFeature($user_id);
}
catch (\Exception $ex)
{
return $this->redirect()->toRoute('administrateur', array('action' => 'indexuser'));
}
return new ViewModel(
array(
'user_id' => $user_id,
'user'=> $user,
'userfeature' => $userfeature,
'compteAdmin' => $compteAdmin,
'company' => $this->getCompanyTable()->fetchAll(),
));
}
Userfeaturetable.php
public function getUserFeature($user_id)
{
$user_id = (int) $user_id;
$rowset = $this->tableGateway->select(array('user_id' => $user_id));
$row = $rowset->current();
if (!$row)
{
throw new \Exception("Could not find row $user_id");
}
return $row;
}
companyTable.php
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet ;
}
Why do not I have the right to embed my two ' foreach ()' ?
Your need to buffer the result.
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
$resultSet->buffer();
return $resultSet ;
}

Default for text element in zf2 forms

How can I setup default for Text element in ZF2 Forms?
I tried the following:
In the view file. This does not get to data, and is not saved:
if($form->get('agencyName')->getValue() === '')
$form->get('agencyName')->setValue('Virtual Field Practicum');
This affects neither view, nor DB:
$this->add(array(
'name' => 'agencyName',
'options' => array(
'label' => 'Agency Name',
),
'attributes' => array(
'disabled' => 'disabled',
'value' => 'Virtual Field Practicum',
)
));
I also tried to modify entity in two ways, but it did not affect anything:
public function __construct()
{
//set default agency name
$this->agencyName = 'Virtual Field Practicum';
}
OR:
public function setAgencyName($agencyName)
{
if ($agencyName === '')
$this->agencyName = 'Virtual Field Practicum';
else
$this->agencyName = $agencyName;
return $this;
}
Edit 1
Adding my generic actions to the post:
1) This one is responsible to load the forms, and process non-ajax calls:
public function editTabAction()
{
$buildName = $this->params()->fromRoute('buildName', 'unknown');
if ($buildName == 'unknown') {
$buildName = $this->params()->fromPost('buildName', 'unknown');
if ($buildName == 'unknown') {
trigger_error('Could not retrieve build name for ' . $buildName . ' entity for this form!');
}
}
//extract parameter from dispatch command
$studEvalId = (int)$this->params()->fromRoute('studEvalId', 0);
if ($studEvalId == 0) {
//extract parameter from the form submission
$studEvalId = (int)$this->params()->fromPost('studEvalId', 0);
if ($studEvalId == 0) {
return $this->notFoundAction();
}
}
$data = $this->getEntity($buildName, $studEvalId);
// Get your ObjectManager from the ServiceManager
$objectManager = $this->getEntityManager();
// get from from FormElementManager plugin
//forms are defined in Module.php
$formName = $buildName . "Form";
$sl = $this->getServiceLocator();
$form = $sl->get('FormElementManager')->get($formName);
$form->setHydrator(new DoctrineHydrator($objectManager ));
$form->setObject($this->getEntityInstanceFromBuildName($buildName));
$form->bind($data);
//set class and Id for buttons like SaveChanges to reference it
$form->setAttribute('class', "studentFormsClass_$studEvalId");
$form->setAttribute('id', "studentFormsId_$studEvalId" . "_$buildName");
//set buildName to the form
$form->get('buildName')->setAttribute('value', $buildName);
$request = $this->getRequest();
if ($request->isPost()) {
$formValidatorName = "OnlineFieldEvaluation\Form\\" . $buildName . "FormValidator";
$formValidator = new $formValidatorName();
$form->setInputFilter($formValidator->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->savetodb($form->getData(), $buildName);
// Redirect to list of forms
return false;
} else {
foreach ($form->getMessages() as $messageId => $message) {
echo '<pre>';
echo "Validation failure '$messageId':";
print_r($message);
echo '</pre>';
}
}
}
$view = new ViewModel(array(
'studEvalId' => $studEvalId,
'buildName' => $buildName,
'form' => $form,
));
$view->setTemplate('online-field-evaluation/tabs/edit' . $buildName . '.phtml');
return $view;
}
2) This one is responsible for ajax calls:
public function validatepostajaxAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$buildName = $this->params()->fromRoute('buildName', 'unknown');
if ($buildName == 'unknown') {
$buildName = $this->params()->fromPost('buildName', 'unknown');
if ($buildName == 'unknown') {
trigger_error('Could not retrieve build name for ' . $buildName . ' entity for this form!');
}
}
//extract parameter from dispatch command
$studEvalId = (int)$this->params()->fromRoute('studEvalId', 0);
if ($studEvalId == 0) {
//extract parameter from the form submission
$studEvalId = (int)$this->params()->fromPost('studEvalId', 0);
if ($studEvalId == 0) {
return $this->notFoundAction();
}
}
$data = $this->getEntity($buildName, $studEvalId);
$objectManager = $this->getEntityManager();
$formName = $buildName . "Form";
$sl = $this->getServiceLocator();
$form = $sl->get('FormElementManager')->get($formName);
$form->setHydrator(new DoctrineHydrator($objectManager ));
$entityName = 'OnlineFieldEvaluation\Entity\\' . $buildName;
$form->setObject(new $entityName());
$form->bind($data);
//set class and Id for buttons like SaveChanges to reference it
$form->setAttribute('class', "studentFormsClass_$studEvalId");
$form->setAttribute('id', "studentFormsId_$studEvalId" . "_$buildName");
//set buildName to the form
$form->get('buildName')->setAttribute('value', $buildName);
$messages = array();
if ($request->isPost()) {
$formValidatorName = "OnlineFieldEvaluation\Form\\" . $buildName . "FormValidator";
$formValidator = new $formValidatorName();
$form->setInputFilter($formValidator->getInputFilter());
$form->setData($request->getPost());
if (!$form->isValid()) {
$errors = $form->getMessages();
foreach ($errors as $key => $row) {
if (!empty($row) && $key != 'submit') {
foreach ($row as $keyer => $rower) {
//save error(s) per-element that
//needed by Javascript
$messages[$key][] = $rower;
}
}
}
}
if (!empty($messages)) {
$response->setContent(
\Zend\Json\Json::encode(
array('status' => 'error',
'messages' => (array) $messages,
'buildName' => $buildName,
'studEvalId' => $studEvalId
)));
} else {
//save to db <span class="wp-smiley wp-emoji wp-emoji-wink" title=";)">;)</span>
$this->savetodb($form->getData(), $buildName);
$response->setContent(
\Zend\Json\Json::encode(
array(
'status' => 'success',
'messages' => 'Successfuly saved.',
'buildName' => $buildName,
'studEvalId' => $studEvalId
)
));
}
}
return $response;
}
To setup a default value for an element, simply do the following:
Open controller's action, that renders desired view
Instantiate a form, get the element by its name and do call setValue() on that
That looks like as following:
public function addAction()
{
$form = new YourAgencyForm();
$form->get('agencyName')->setValue('Virtual Field Practicum');
....
It's really that simple

change language with session in zend framework 2

I want make possible for user change the language of the webside. In the Module.php I wrote this:
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getServiceManager('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH, array($this, 'bootstrapSession'), 10);
$config = $this->getConfig();
\Locale::setDefault('de');
\Zend\Validator\AbstractValidator::setDefaultTranslator(
$e->getApplication()
->getServiceManager()
->get('translator')
);
if ($session->language !== NULL)
{
$e->getApplication()->getServiceManager()->get('translator')->setLocale($session->language);
}
public function bootstrapSession()
{
$config = $this->getConfig();
$sessionConfig = new Session\Config\SessionConfig();
$sessionConfig->setOptions($config['session']);
$sessionManager = new Session\SessionManager($sessionConfig);
$sessionManager->start();
var_dump($sessionManager);
Session\Container::setDefaultManager($sessionManager);
}
public function getServiceConfig()
{
var_dump('halloo');
return array(
'factories' => array(
'session' => function() {
$session = Session\Container::getDefaultManager()->getStorage();
return $session;
},
),
);
}
In the IndexController.php I want to change the language and get it after in the module. So that the language changes.
Here is my action:
public function enAction()
{
$session = $this->getServiceLocator()->get('session');
$session->language = 'en';
return $this->redirect()->toRoute('home');
}
The browser shows no error but the language doesn't change. Does someone see a error and can help me?
Module.php
public function onBootstrap(MvcEvent $e){
// session container
$sessionContainer = new \Zend\Session\Container('locale');
// test if session language exists
if(!$sessionContainer->offsetExists('mylocale')){
// if not use the browser locale
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
$sessionContainer->offsetSet('mylocale', \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']));
}else{
$sessionContainer->offsetSet('mylocale', 'en_US');
}
}
// translating system
$translator = $serviceManager->get('translator');
$translator ->setLocale($sessionContainer->mylocale)
->setFallbackLocale('en_US');
$mylocale = $sessionContainer->mylocale;
Controller
Just change the language from controller
/**
*
* #return \Zend\View\Model\ViewModel
*/
public function changelocaleAction(){
// disable layout
$result = new ViewModel();
$result->setTerminal(true);
// variables
$event = $this->getEvent();
$matches = $event->getRouteMatch();
$myLocale = $matches->getParam('locale');
$redirect = $matches->getParam('redirecturl', '');
// translate
$sessionContainer = new Container('locale');
switch ($myLocale){
case 'fr_FR':
break;
case 'en_US':
break;
default :
$myLocale = 'en_US';
}
$sessionContainer->offsetSet('mylocale', $myLocale);
// redirect
switch ($redirect){
case '':
$this->redirect()->toRoute('home');
break;
default :
$this->redirect()->toUrl(urldecode($redirect));
}
return $result;
}
From Zend Framework Multi Language Integration Steps

Zend framework $form->isValid($formData) Return invalid and I dont know why

I have a 2-steps-form (Fancy Name), but, when I submit this form, the validation return false all time, I debugged it and I receive all the parameters I want, but for some reason the isValid is false and get some error in the RadioButton element, this is the code:
This is the forms/Users.php
public function signup()
{
$contryModel = new Application_Model_Country();
$countries = $contryModel->getCountries();
foreach ($countries as $array)
{
if(isset($array['id_country'])){
$countryArr[$array['id_country']] = $array['country'];
}
}
array_unshift($countryArr, '-- Select Your Country --');
$name = new Zend_Form_Element_Text('Name');
$name->setLabel('Name')
->setRequired(true)
->addValidator('NotEmpty');
$lastname = new Zend_Form_Element_Text('LastName');
$lastname->setLabel('Last Name')
->setRequired(true)
->addValidator('NotEmpty');
$email = new Zend_Form_Element_Text('Email');
$email->setLabel('Email')
->setRequired(true)
->addValidator('NotEmpty');
$website = new Zend_Form_Element_Text('Website');
$website->setLabel('Website')
->setRequired(true)
->addValidator('NotEmpty');
$country = new Zend_Form_Element_Select('Country');
$country->setLabel('Country')
->setRequired(true)
->addValidator('NotEmpty')
->addMultiOptions($countryArr);
$city = new Zend_Form_Element_Select('City');
$city->setLabel('City')
->setRequired(true)
->addValidator('NotEmpty')
->addMultiOptions(array('-- Select Your City --'))
->setRegisterInArrayValidator(false)
->setAttrib('disabled',true);
$password = new Zend_Form_Element_Password('Password');
$password->setLabel('Password')
->setRequired(true)
->addValidator('NotEmpty');
$rpassword = new Zend_Form_Element_Password('RepeatPassword');
$rpassword->setLabel('Repeat Password')
->setRequired(true)
->addValidator('NotEmpty');
$why = new Zend_Form_Element_Textarea('Why');
$why->setRequired(true)
->addValidator('NotEmpty')
->setAttrib('cols', '50')
->setAttrib('rows', '4');
$job = new Zend_Form_Element_Text('Job');
$job->setLabel("Job")
->setRequired(true)
->addValidator('NotEmpty');
$boxes = new Application_Model_Colors();
$res = $boxes->getColors();
foreach($res as $colors){
$colorArr[$colors['id']]['color'] = $colors['color'];
$colorArr[$colors['id']]['overColor'] = $colors['overColor'];
}
$color = new Zend_Form_Element_Radio('color');
$color->setLabel('Color')
->addMultiOptions($colorArr)
->addValidator('NotEmpty');
$save = new Zend_Form_Element_Submit('Submit');
$save->setLabel('Save');
$this->addElements(array($name, $lastname, $email, $website, $password, $rpassword, $job, $country, $city, $color, $why, $save));
}
*This is a part of the view * where I format the Radios
<?php
foreach($this->form->color->options as $key=>$colors){
echo "<label><input type='radio' value='$key' name='color'><div class='registrationBoxes' style='background-color:#".$colors['color']."' data-color='".$colors['color']."' data-overColor='".$colors['overColor']."' value='".$colors['color']."'></div></label>";
}
?>
And here is the Controller
public function indexAction()
{
$form = new Application_Form_Users();
$form->signup();
$this->view->form = $form;
if($this->getRequest()->isPost())
{
$formData = $this->getRequest()->getPost();
if($form->isValid($formData))
{
$formData = $this->getRequest()->getPost();
$name = $formData['Name'];
$lastName = $formData['LastName'];
$email = $formData['Email'];
$website = $formData['Website'];
$password = $formData['Password'];
$rpassword = $formData['RepeatPassword'];
$job = $formData['Job'];
$country = $formData['Country'];
$city = $formData['City'];
$color = $formData['color'];
$why = $formData['Why'];
$date_create = date('Y-m-d H:i:s');
$position = new Application_Model_Country();
$latLong = $position->getLatLong($city);
if($password == $rpassword){
$data = array( 'name'=>$name,
'last_name'=>$lastName,
'email'=>$email,
'website'=>$website,
'password'=>md5($password),
'date_create'=>$date_create,
'job'=>$job,
'country'=>$country,
'city'=>$city,
'color'=>$color,
'why'=>$why,
'latitude'=>$latLong['latitude'],
'longitude'=>$latLong['longitude']
);
$add = new Application_Model_Users();
$res = $add->insertUser($data);
if($res){
$this->view->message = "Registration Successfuly.";
$this->_redirect("/contact");
}else{
$this->view->errorMessage = "We have a problem with your registration, please try again later.";
}
}else{
$this->view->errorMessage = "Password and confirm password don't match.";
$form->populate($formData);
}
} else {
$this->view->errorMessage = "There is an error on your registration, all fields are requried";
$form->populate($formData);
}
}
}
a die(var_dump()) return this:
array(12) {
["Name"]=>
string(9) "Some name"
["LastName"]=>
string(13) "Some lastName"
["Email"]=>
string(21) "Someemail#hotmail.com"
["Password"]=>
string(5) "Some "
["RepeatPassword"]=>
string(5) "Some "
["Website"]=>
string(12) "Some website"
["Job"]=>
string(8) "Some job"
["Country"]=>
string(1) "7"
["City"]=>
string(3) "434"
["color"]=>
string(1) "3"
["Why"]=>
string(10) "Emotional!"
["Submit"]=>
string(4) "Save"
}
As you can see, all the parameters are coming and with value, but for no reason the isValid is returning false, some idea guys?
Thanks.-
EDIT
This is a part of the Zend/form.php code required by Tonunu
public function __construct ($options = null)
{
if (is_array($options)) {
$this->setOptions($options);
} elseif ($options instanceof Zend_Config) {
$this->setConfig($options);
}
// Extensions...
$this->init();
$this->loadDefaultDecorators();
}
public function __clone ()
{
$elements = array();
foreach ($this->getElements() as $name => $element) {
$elements[] = clone $element;
}
$this->setElements($elements);
$subForms = array();
foreach ($this->getSubForms() as $name => $subForm) {
$subForms[$name] = clone $subForm;
}
$this->setSubForms($subForms);
$displayGroups = array();
foreach ($this->_displayGroups as $group) {
$clone = clone $group;
$elements = array();
foreach ($clone->getElements() as $name => $e) {
$elements[] = $this->getElement($name);
}
$clone->setElements($elements);
$displayGroups[] = $clone;
}
$this->setDisplayGroups($displayGroups);
}
public function setOptions (array $options)
{
if (isset($options['prefixPath'])) {
$this->addPrefixPaths($options['prefixPath']);
unset($options['prefixPath']);
}
if (isset($options['elementPrefixPath'])) {
$this->addElementPrefixPaths($options['elementPrefixPath']);
unset($options['elementPrefixPath']);
}
if (isset($options['displayGroupPrefixPath'])) {
$this->addDisplayGroupPrefixPaths(
$options['displayGroupPrefixPath']);
unset($options['displayGroupPrefixPath']);
}
if (isset($options['elementDecorators'])) {
$this->_elementDecorators = $options['elementDecorators'];
unset($options['elementDecorators']);
}
if (isset($options['elements'])) {
$this->setElements($options['elements']);
unset($options['elements']);
}
if (isset($options['defaultDisplayGroupClass'])) {
$this->setDefaultDisplayGroupClass(
$options['defaultDisplayGroupClass']);
unset($options['defaultDisplayGroupClass']);
}
if (isset($options['displayGroupDecorators'])) {
$displayGroupDecorators = $options['displayGroupDecorators'];
unset($options['displayGroupDecorators']);
}
if (isset($options['elementsBelongTo'])) {
$elementsBelongTo = $options['elementsBelongTo'];
unset($options['elementsBelongTo']);
}
if (isset($options['attribs'])) {
$this->addAttribs($options['attribs']);
unset($options['attribs']);
}
$forbidden = array('Options', 'Config', 'PluginLoader', 'SubForms',
'View', 'Translator', 'Attrib', 'Default');
foreach ($options as $key => $value) {
$normalized = ucfirst($key);
if (in_array($normalized, $forbidden)) {
continue;
}
$method = 'set' . $normalized;
if (method_exists($this, $method)) {
$this->$method($value);
} else {
$this->setAttrib($key, $value);
}
}
if (isset($displayGroupDecorators)) {
$this->setDisplayGroupDecorators($displayGroupDecorators);
}
if (isset($elementsBelongTo)) {
$this->setElementsBelongTo($elementsBelongTo);
}
return $this;
}
In order to check if your form is valid, you have to put your data into it, using this method !
$form->setData($formData)
and then you can ask for validation
$form->isValid()
So what you need is :
$formData = $this->getRequest()->getPost();
$form->setData($formData);
if($form->isValid()){
//Blablablabla
}

Resources