Zendframework 2 ResultSet to array - php

I´m trying to create a dynamic list of checkboxes. I get the list of checkboxes by selecting them from my database. But now i get the error that i cannot use this list because of type ResultSet and not Array. How can I do this? Heres my code(I´m totally aware that its not good code)
my function for fetching and passing to the view
public function indexAction(){
$adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$input = new SearchModel($adapter);
$rowset = $input->getName();
$form = new SearchForm($rowset['name']);
$model = new ViewModel(array('form' => $form, 'input' => $rowset));
$model->setTemplate('search/index');
return $model;
}
My model action
public function getName(){
$sql = "SELECT * FROM benutzer";
$rowset = $this->adapter->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
return $rowset;
}
And my Form
public function __construct($name = null){
$this->add(array(
'type' => 'Zend\Form\Element\MultiCheckbox',
'name' => 'name',
'options' => array(
'label' => 'Sportart',
'value_options' => $name,
),
));
}

$rowset = $input->getName();
$name = '';
if ($rowset->count() > 0) {
$name = $rowset->current()->name;
}
$form = new SearchForm($name);
or
$rowset = $input->getName()->toArray();
$name = '';
if (isset($rowset[0]['name'])) {
$name = $rowset[0]['name'];
}
$form = new SearchForm($name);

Related

PrestaShop, Class not found in ModuleAdminController::getController

i'm trying to develop a PrestaShop module with controllers i placed, for example in:
/modules/mymodule/controllers/admin/myControlController.php
class MyControlController extends ModuleAdminController {
public function __construct() {
$this->module = 'mymodule';
$this->bootstrap = true;
$this->context = Context::getContext();
$token = Tools::getAdminTokenLite('AdminModules');
$currentIndex='index.php?controller=AdminModules&token='.$token.'&configure=mymodule&tab_module=administration&module_name=mymodule';
Tools::redirectAdmin($currentIndex);
parent::__construct();
}
public function showForm() {
die("hello");
}}
Controller works (construct method is called) if i call it form url
http://myshop.com/adminxxx/index.php?controller=MyControl&token=9faf638aa961468c8563ffb030b3c4a8
But i can't access methods of controller from main class of module:
ModuleAdminController::getController('MyControl')->showForm();
I received "Class not found" ever
Is that the correct method to access a control from outside?
Thanks!
If you want to show anything that concern a form you should use renderForm().
Your should try parent::showForm(); or $this->showForm();.
Here is an example of controller that can work :
require_once _PS_MODULE_DIR_.'modulename/models/ModuleNameLog.php';
require_once _PS_MODULE_DIR_.'modulename/modulename.php';
class AdminModuleNameLogController extends ModuleAdminController
{
protected $_defaultOrderBy = 'id_modulenamelog';
protected $_defaultOrderWay = 'DESC';
public function __construct()
{
$this->table = 'modulenamelog';
$this->className = 'ModuleNameLog';
$this->context = Context::getContext();
$this->lang = false;
$this->bootstrap = true;
$this->actions_available = array();
$this->actions = array();
$this->show_toolbar = false;
$this->toolbar_btn['new'] = array();
$this->tabAccess['add'] = '0';
$this->allow_export = true;
$this->requiredDatabase = true;
$this->page_header_toolbar_title = $this->l('Example Module Name logs');
$this->_select = 'SUM(a.quantity) as total_quantity';
$this->_group = ' GROUP BY a.id_product, a.id_product_attribute ';
$this->fields_list = array(
'id_product' => array(
'title' => $this->l('Product'),
'align' => 'center',
'callback' => 'getProductName',
),
'id_product_attribute' => array(
'title' => $this->l('Combination'),
'align' => 'center',
'callback' => 'getAttributeName',
),
'total_quantity' => array(
'title' => $this->l('Total Quantity'),
'align' => 'center',
),
);
$this->mod = new ModuleName();
$this->mod->cleanLogs();
$this->context = Context::getContext();
parent::__construct();
}
public function getProductName($id)
{
if (!empty($id)) {
$product = new Product($id, true, $this->context->cookie->id_lang);
return $product->name;
}
}
public function getAttributeName($id)
{
if (!empty($id)) {
$combination = new Combination($id);
$names = $combination->getAttributesName($this->context->cookie->id_lang);
$str = array();
if (!empty($names)) {
foreach ($names as $value) {
$str[] = $value['name'];
}
}
return implode(' - ', $str);
} else {
return '-';
}
}
public function postProcess()
{
if (Tools::isSubmit('purge_id')) {
// Do something here
$id = (int) Tools::getValue('purge_id');
Tools::redirectAdmin(self::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModuleNameLog').'&conf=4');
}
parent::postProcess();
}
public function renderList()
{
$carts = Db::getInstance()->executeS('SELECT ct.*, cs.`firstname`, cs.`lastname` FROM '._DB_PREFIX_.'cart ct LEFT JOIN '._DB_PREFIX_.'customer cs ON ct.id_customer = cs.id_customer WHERE 1 ORDER BY id_cart DESC LIMIT 0,2000');
$tpl = $this->context->smarty->createTemplate(_PS_MODULE_DIR_.'modulename/views/templates/admin/preform.tpl');
$tpl->assign(array(
'carts' => $carts,
));
$html = $tpl->fetch();
return $html.parent::renderList();
}
public function renderForm()
{
if (!$this->loadObject(true)) {
return;
}
$obj = $this->loadObject(true);
if (isset($obj->id)) {
$this->display = 'edit';
} else {
$this->display = 'add';
}
$array_submit = array(
array(
'type' => 'select',
'label' => $this->l('Cart :'),
'name' => 'id_cart',
'options' => array(
'query' => Db::getInstance()->executeS('SELECT * FROM '._DB_PREFIX_.'cart WHERE id_cart > 0 ORDER BY id_cart DESC LIMIT 0,500'),
'id' => 'id_cart',
'name' => 'id_cart',
),
),
array(
'type' => 'text',
'label' => $this->l('Quantity translation here'),
'hint' => $this->l('Description and translation here'),
'name' => 'quantity',
),
);
$this->fields_form[0]['form'] = array(
'tinymce' => false,
'legend' => array(
'title' => $this->l('Form title'),
),
'input' => $array_submit,
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default',
),
);
$this->multiple_fieldsets = true;
return parent::renderForm();
}
}

Multiple ListBoxField for predefined list

I have an Address DataObject:
class Address extends DataObject{
private static $db = array(
'Address' => 'varchar(255)',
);
private static $many_many = array(
'Countries' => 'Country'
);
public function getCMSFields() {
$fields = FieldList::create(TabSet::create('Root'));
$fields->addFieldsToTab('Root.Main', array(
TextField::create('Name'),
ListBoxField::create('Countries', 'Countries')->setMultiple(true)->setSource(Country::get()->map('ID', 'Name'))
));
return $fields;
}
}
And a Country dataObject:
class Country extends DataObject{
private static $belongs_many_many = array(
'Addresses' => 'Address',
);
private static $countries = array(
"AF" => array("Name"=>"Afghanistan","PhoneExtension"=>"+93"),...
);
public static function get($callerClass = null, $filter = "", $sort = "", $join = "", $limit = null, $containerClass = 'DataList') { $return = new ArrayList();
$i = 1; //if I do 0 it always populates the admin field.
foreach (self::$countries as $key => $value) {
$return->add(new ArrayData(array('ID' => $i, 'Acronym' => $key, 'Name' => $value['Name'])));
$i++;
}
return $return;
}
}
** UPDATED **
In the database this saves correctly however it doesn't return correctly in the CMS admin. What am I missing?

Phpunit test a method using a service

I'm trying to test a method which is using a service, and apparently it's not possible to test it like a normal method.
Does someone know what to do ?
I have this code for the moment :
namespace PlatformBundle\Tests;
use PlatformBundle\Controller\PaymentController;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class PaymentControllerTest extends WebTestCase
{
private $payment;
public function __construct() { parent::__construct(); $this->payment = new PaymentController(); }
public function testSendEmail()
{
$param = array(
'info' => array(
'email' => 'test#test.com', 'name' => 'test', 'fare' => 'test', 'id' => 'test'
)
);
$this->assertEquals(true, $this->invokeMethod($this->payment, 'sendEmail', $param));
}
/**
* Call protected/private method of a class.
*
* #param object &$object Instantiated object that we will run method on.
* #param string $methodName Method name to call
* #param array $parameters Array of parameters to pass into method.
*
* #return mixed Method return.
*/
public function invokeMethod(&$object, $methodName, array $parameters = array())
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
}
The controller where the method sendEmail is :
<?php
namespace PlatformBundle\Controller;
use PlatformBundle\Entity\Customer;
use PlatformBundle\Entity\Promocode;
use PlatformBundle\Entity\Transfer;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class PaymentController extends Controller
{
public function checkoutAction(Request $req)
{
if (! $req->isMethod('POST')) throw new AccessDeniedHttpException();
$info = $req->request->all();
$this->container->get('platform.formSecurity')->testAllInformation($info);
$this->saveCustomerIntoDb($info);
$info['payed'] = false;
$session = $req->getSession();
$session->set('info', $info);
$info['date'] = $this->container->get('platform.useful')->reverseDateFormat($info['date']);
return $this->render('PlatformBundle:Payment:checkout.html.twig', array(
'isIndex' => false,
'info' => $info,
'stripe' => $this->stripeConfig()
));
}
public function cancelAction(Request $req)
{
$req->getSession()->invalidate();
return $this->render('PlatformBundle:Payment:cancel.html.twig', array('isIndex' => false));
}
public function successAction(Request $req)
{
$session = $req->getSession();
$info = $session->get('info');
if ($info['payed']) {
$req->getSession()->invalidate();
if ($info === null) throw new Exception('Please contact us to make sure that the payment has been done and that your order has been taken into account.');
$this->saveTransferIntoDb($info);
$customer = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Customer')->findOneBy(array(
'email' => $info['email']
));
$transfer = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Transfer')->findOneBy(
array('customer' => $customer->getId()),
array('id' => 'desc'),
1
);
$info['id'] = $transfer->getId();
$info['date'] = $this->container->get('platform.useful')->reverseDateFormat($info['date']);
$this->sendEmail($info);
// if 5 payments done, send a promocode
if (is_int($customer->getPayments() / 5)) {
$this->createAndSendNewPromocode($customer);
}
return $this->render('PlatformBundle:Payment:success.html.twig', array(
'isIndex' => false,
'info' => $info
));
} else return new RedirectResponse('cancel');
}
private function sendEmail($info)
{
$mail = $this->container->get('platform.mail');
$mail->send(
$info['email'],
'You have ordered a transfer for Dublin',
$this->renderView('PlatformBundle:Mail:orderSucceed.html.twig', array('info' => $info)),
'info#dubair.ie'
);
$mail->send(
'info#airportcollections.net, info#dubair.ie, info#365onlineholidays.com',
'A customer ordered a transfer for Dublin',
$this->renderView('PlatformBundle:Mail:report.html.twig', array('info' => $info)),
'info#dubair.ie'
);
}
private function saveCustomerIntoDb($info)
{
// test if the customer already exist
$customersList = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Customer')
->findByEmail($info['email']);
$customerExists = (sizeof($customersList) == 1 ? true : false);
if ($customerExists) {
$customer = $customersList[0];
} else {
// Create the entity
$customer = new Customer();
// dateRegistration, country and ip are automatically created in the constructor
$customer->setEmail($info['email']);
$customer->setPayments(0);
}
$customer->setName($info['name']);
$customer->setPhone($info['phone']);
$em = $this->getDoctrine()->getManager();
$em->persist($customer);
$em->flush();
}
private function saveTransferIntoDb($info)
{
$customers = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Customer')
->findByEmail($info['email']);
$customer = $customers[0];
$customer->setPayments($customer->getPayments() + 1);
// make promocode outdated
if ($info['promocode'] != '') {
$promocode = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Promocode')
->findOneBy(array(
'value' => $info['promocode'],
'outdated' => 0,
'type' => 'short'
));
$promocode->setOutdated(1);
}
// test if transfer already exist
$transferList = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Transfer')->findBy(
array(
'customer' => $customer,
'pickup' => $info['pickup'],
'destination' => $info['destination'],
'pickupTime' => $info['pickupTime'],
'address' => $info['address']
), // criteria
array('pickup' => 'desc'), // sorting
5, // Limit
0 // Offset
);
// if transfer doesn't already exist, create it
if (sizeof($transferList) == 0) {
$transfer = new Transfer();
$transfer->setPickup($info['pickup']);
$transfer->setDestination($info['destination']);
$dateArray = explode('-', $info['date']);
$transfer->setDate(new \DateTime($dateArray[2].'-'.$dateArray[1].'-'.$dateArray[0]));
$transfer->setAddress($info['address']);
$transfer->setFlightTime($info['flightTime']);
$transfer->setPickupTime($info['pickupTime']);
$transfer->setSeats($info['seats']);
$transfer->setAirline($info['airline']);
$transfer->setFlight($info['flight']);
$transfer->setType($info['type']);
$transfer->setBags($info['bags']);
$transfer->setFare($info['fare']);
// join
$transfer->setCustomer($customer);
$em = $this->getDoctrine()->getManager();
$em->persist($transfer);
$em->flush();
}
}
private function createAndSendNewPromocode($customer)
{
$newPromocode = $this->container->get('platform.useful')->createRandomPassword();
$promocode = new Promocode();
$promocode->setValue($newPromocode);
$promocode->setType('short');
$promocode->setDiscount(10);
$em = $this->getDoctrine()->getManager();
$em->persist($promocode);
$em->flush();
$mail = $this->container->get('platform.mail');
$mail->send(
$customer->getEmail(),
'A promotional code for your next transfer on dubair.ie !',
$this->renderView('PlatformBundle:Mail:promocode.html.twig', array(
'customer' => $customer,
'promocode' => $newPromocode
)),
'info#dubair.ie'
);
}
private function stripeConfig()
{
$stripe = array(
"secret_key" => "xx",
"publishable_key" => "xx"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
return $stripe;
}
public function stripeChargeAction(Request $req)
{
$this->stripeConfig();
$info = $req->getSession()->get('info');
$amount = ($info['fare'] * 100);
$info['payed'] = true;
$req->getSession()->set('info', $info);
$token = $req->request->get('stripeToken');
$customer = \Stripe\Customer::create(array(
'email' => $req->request->get('email'),
'card' => $token
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'eur'
));
return new RedirectResponse('success');
}
}
thanks

ZF2 adding a limit to update with AbstractTableGateway

I'm using ZF2 TableGateway to update some data:
$this->update($data, array('id' => $id)));
I want to add a limit to this query, such as:
$this->update($data, array('id' => $id)))->limit(1);
This doesn't work however. Any ideas how to achieve this?
Thank you!
In You Controller use this:
import:
use Zend\Db\TableGateway\TableGateway
in main controller
public function updateuserAction() {
$form = new UserRegistration();
$request = $this->getRequest();
$id = $this->params()->fromRoute('id');
if(!$id) {
$this->redirect()->toUrl('/REDIRECT_URL');
}
if ($request->isPost()) {
$registeruser = new UserRegistrationModel();
$formValidator = new UserRegistrationValidator(); {
$form->setInputFilter($formValidator->getInputFilter());
$form->setData($request->getPost());
}
if ($form->isValid()) {
$data = $form->getData();
unset($data['submit']);
$this->getUsersTable()->update($data, array('uid' => $id));
return $this->redirect()->toUrl('/REDIRECT_URL');
}
$view = new ViewModel(array('form' => $form, 'action' => $this->params()->fromRoute('action')));
return $view;
}
else {
$form->setData($this->getUsersTable()->select(array('uid' => $id))->current());
}
$view = new ViewModel(array('form' => $form, 'id' => $id , 'rowset' => $this->getUsersTable()->select(array('uid' => $id))->current()));
return $view;
}
public function getUsersTable() {
if (!$this->RegisterUser) {
$article = $this->RegisterUser = new TableGateway(
'users', $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter')
);
}
return $this->RegisterUser;
}
//// Controller ends
and in View :
// to get id ( IN FORM )
$form->setAttribute('action', $this->url('user',
array('action' => 'updateuser', 'id' => $id)));
/REDIRECT_URL is your url to redirect user,
CHANGE UID to id from database table,
getUsersTable() is table gateway

Select element from other table on the form zf2

i have 2 table with ManyToOne relation on the database between client and sale and i want to select the id_client on the Sale Form . for that o used that .
SaleForm :
public function __construct(ClientTable $table)
{
parent::__construct('vente');
$this->setAttribute('method', 'post');
$this->clientTable = $table;
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(
array(
'name' => 'id_client',
'type' => 'Select',
'attributes' => array(
'id' => 'id_client'
),
'options' => array(
'label' => 'Catégory',
'value_options' => $this->getClientOptions(),
'empty_option' => '--- Sélectionnez une categorie---'
),
)
);
public function getClientOptions()
{
$data = $this->clientTable->fetchAll()->toArray();
$selectData = array();
foreach ($data as $key => $selectOption) {
$selectData[$selectOption["id"]] = $selectOption["nom_client"];
}
return $selectData;
}
}
SaleController:
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Caisse\Model\Sale;
use Caisse\Form\SaleForm;
class SaleController extends AbstractActionController
{
protected $saleTable;
protected $clientTable;
public function addAction()
{
$form = new SaleForm($this->clientTable);
$form->get('submit')->setValue('Ajouter');
$request = $this->getRequest();
if ($request->isPost()) {
$vente = new Sale();
$form->setInputFilter($sale->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$vente->exchangeArray($form->getData());
$this->getSaleTable()->saveSale($sale);
return $this->redirect()->toRoute('sale');
}
}
return array('form' => $form);
}
}
But every Time i had this issue:
Catchable fatal error: Argument 1 passed to
Caisse\Form\SaleForm::__construct() must be an instance of
Admin\Model\ClientTable, null given.
Is this the good method to do it, any reference for same example will be welcome.
Thank you
Inside your controller, function addAction, you never set the variable clientTable maybe you forgot to initialize it.
Like this
public function addAction()
{
$this->clientTable = $this->getServiceLocator()->get('Client\Model\ClientTable');
$form = new SaleForm($this->clientTable);
// ...
}
About
public function getClientOptions()
{
$data = $this->clientTable->fetchAll();
$selectData = array();
foreach ($data as $row) {
$selectData[$row->id] = $row->nom_client;
}
return $selectData;
}

Categories