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
Related
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
I am new in CAKEPHP and I want to fetch my post which is posted by me or login user only. How to fetch those posts? I don't have any idea.
This is the post controller code:
<?php
class PostsController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session','Paginator');
public $paginate = array(
'limit' => 10,
'order' => array(
'Post.id' => 'desc'
)
);
public function index(){
$this->Paginator->settings = $this->paginate;
// Pagination Code Limit define to top
// similar to findAll(), but fetches paged results
$data = $this->Paginator->paginate();
$this->set('posts', $data);
}
public function add(){
if($this->request->is('post')){
$this->Post->create();
$this->request->data['Post']['user_id'] = $this->Auth->user('id');
if($this->Post->save($this->request->data)){
$this->Session->setFlash(__('Your Post is saved!!'));
return $this->redirect(array('action' => 'index' ));
}
$this->Session->setFlash(__('Unable to post data.'));
}
}
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
public function view($id = null){
if(!$id){
throw new NotFoundException(__('Invalid Post'));
}
$post = $this->Post->findById($id);
if(!$post){
throw new NotFoundException(__('Invalid Post'));
}
$this->set('post',$post);
}
public function delete($id){
if($this->request->is('get')){
throw new MethodNotAllowedException();
}
if($this->Post->delete($id)){
$this->Session->setFlash(__('Post Deleted Sucessfully!!'));
}else{
$this->Session->setFlash(
__('The post with id: %s could not be deleted.')
);
}
return $this->redirect(array('action' => 'index'));
}
}
?>
And my model is:
<?php
class Post extends AppModel {
public $validate = array(
'title' => array(
'rule'=> 'notEmpty'
),
'body' => array(
'rule'=> 'notEmpty'
)
);
}
?>
I want to fetch the posts which is posted by me or the user who are login , rather the full data.
Please help me. Thanks !
Add conditions when you are fetching the posts-
$condition = array(
'conditions' => array('posts.user_id' => $this->Auth->user('id')),
)
$this->Paginator->settings = array(
'conditions' => $conditions,
);
CakePHP Pagination
You need to make following changes in your controller to fetch your and logged in user posts
First of all add Auth component
public $components = array('Session','Paginator','Auth');
Secondly fetch your user id
$your_id (This is your user Id)
And at last your put following condition in paginator
public $paginate = array(
'limit' => 10,
'conditions' => array('posts.user_id' => $this->Auth->user('id'),'posts.user_id' => $your_id),
'order' => array(
'Post.id' => 'desc'
)
);
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);
Is there a way to avoid persisting datas with Symfony2? Here is my example:
I have a user and a experience entity with one form. My experience entity is binded with user with cascade={persist}. So when a user fill his email address and his experience, both entities are created and binded.
My question is how to avoid to send user informations to the database if his email address already exists?
Here is my function:
public function participeAction(Request $request)
{
$type = new EcoActorsType();
$form = $this->createForm($type);
$form->handleRequest($request);
if ($form->isValid())
{
$data = $form->getData();
$doctrine = $this->getDoctrine();
$em = $doctrine->getManager();
$email = $data->getUserActor();
$email = $email->getEmail();
$is_email = $em
->getRepository('Mobility\PublicBundle\Entity\UserActor')
->findOneBy(array(
'email' => $email
));
if ($is_email == null)
{
$em->persist($data);
$em->flush();
}
else
{
????
}
$url = $this->generateUrl('public.frontpages.participe');
return $this->redirect($url);
}
return array(
'form' => $form->createView()
);
}
Here is my data object:
object(Mobility\PublicBundle\Entity\EcoActors)[905]
private 'id' => null
private 'title' => string 'test experience' (length=15)
private 'type' => int 0
private 'start' => string 'test start' (length=10)
private 'arrival' => string 'test arrival' (length=12)
private 'description' => string 'test test test' (length=14)
private 'game' => boolean false
private 'useractor' =>
object(Mobility\PublicBundle\Entity\UserActor)[898]
private 'id' => null
private 'email' => string 'test#test.fr' (length=12)
private 'ges' => int 2
Finally it was simple. I just setted the object with the one which was already in the data base.
Here is the new code:
public function participeAction(Request $request)
{
$type = new EcoActorsType();
$form = $this->createForm($type);
$form->handleRequest($request);
if ($form->isValid())
{
$data = $form->getData();
$doctrine = $this->getDoctrine();
$em = $doctrine->getManager();
$email = $data->getUserActor();
$email = $email->getEmail();
$is_email = $em
->getRepository('Mobility\PublicBundle\Entity\UserActor')
->findOneBy(array(
'email' => $email
));
if ($is_email == null)
{
$em->persist($data);
$em->flush();
}
else
{
$data->setUseractor($is_email);
$em->persist($data);
$em->flush();
}
$url = $this->generateUrl('public.frontpages.participe');
return $this->redirect($url);
}
return array(
'form' => $form->createView()
);
}
$existingUser = $em->getRepository( "you entity shortname AcmeBundle:Entity" )->findOneByEmail( $email );
if ( $existingUser !== null )
{
//User exists
}else
{
//User doesn't exist
}
On the database integrity side, you can use the #UniqueConstraint to have the schema assign the column as unique.
/**
* #Entity
* #Table(name="UserActor",uniqueConstraints={#UniqueConstraint(name="email_idx", columns={"email"})})
*/
class UserActor
{
// ...
}
On the Controller side, you use the findOneBy helper functions with Doctrine (the default repository class will generate special find functions for each column in your Entity, such as findOneByEmail)
$user = $this->getDoctrine()
->getRepository('MobilityPublicBundle:UserActor')->findOneByEmail($email);
if ($user) {
// User exists
} else {
// User doesn't exist
}
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;
}