Phalcon framework, can't get data from modal to controller - php

public function searchStudent($student)
{
$db = Di::getDefault()->get('db');
$sql = 'SELECT * FROM students WHERE insurance_number = "'.$student['searchInsurenceNum'].'"';
$sth = $db->prepare($sql);
$sth->execute();
When i check here die(var_dump($sth->fetchAll())), i am getting array with data from database.
return $sth->fetchAll();
}
public function searchAction()
{
$request = new Request();
$response = new Response();
if ($request->isPost()) {
(new ContactsStorage())->searchStudent($request->getPost());
}
But in controller when i call fuction die(var_dump((new ContactsStorage())->searchStudent())), i am getting empty array .
$this->view->setVar('findData', (new ContactsStorage())->searchStudent());
}

Maybe your request is not a POST ? ($request->isPost())
by using this method you're allow to find your students only on POST request. Remove condition and try again.
If you have model Student which extends \Phalcon\Mvc\Model you can use magic static methods findBy{$FeildCamelCasedName} so there is no need to create extra repositories and even methods if you want to ge tsome entity by simple criteria:
$findData = Student::findByInsuranceNumber($in);
also you can find one element by such criteria by simply using magic method findFirstBy{$Field}

Related

Normal calling object inside Model VS fetchAll()

Im new to zendframework & zend db..any help will be great!!
(Normal Way)
Lets say i want to get data..so im using this
Inside Controller
$db = new Studentfinance_Model_DbTable_FeeItem();
$data =$this->db->getDate();
Inside Model
protected $_name = 'tbl_foo_foo';
protected $_primary = "foo_id";
public function getData() {
$db = Zend_Db_Table::getDefaultAdapter();
$selectData = $db->select()
->from(array('a'=>$this->_name))
->joinLeft(array('c'=>'tbl_bar'), 'c.idBar = a.id',array('DefinitionDesc','Status'))
->group('a.id')
$fc_cat = $db->fetchAll($selectData);
return($fc_cat);
}
For Above line of code...i understand the way its work..
But for below..i have a bit problem to understand..same concept..the purpose to get the data
inside controller/form
$feeCategoryDb = new Studentfinance_Model_DbTable_FeeCategory();
$listData = $feeCategoryDb->fetchAll();
i try to find function fetchAll()...but i dont find it inside Model FeeCategory...can someone explainn this
$feeCategoryDb->getData() already sets up the query and runs "fetchAll" and returns the results. So all you need to do is:
$feeCategoryDb = new Studentfinance_Model_DbTable_FeeCategory();
$listData = $feeCategoryDb->getData();

PHP Slim Get route placeholder in a container

Is it possible get the value of a route placeholder within a Slim container? I know I can access the placeholder by adding a third parameter to the request but I'd like to have it injected so I'm not assigning it on each request.
I've tried $app->getContainer('router') but I can't seem to find a method to actually pull the placeholder value.
Example:
$app = new Slim\App;
$c = $app->getContainer();
$c['Controller'] = function() {
$userId = // how do I get the route placeholder userId?
return new Controller($userId);
};
$app->get('/user/{userId}','Controller:getUserId');
class Controller {
public function __construct($userId) {
$this->userId = $userId;
}
public function getUserId($request,$response) {
return $response->withJson($this->userId);
}
}
Without some 'hacky' things this will not work because we have no access on the request object build by slim, while the controller get constructed. So I recommend you to just use the 3rd parameter and get your userid from there.
The 'hacky' thing would be todo the same, what slim does when you execute $app->run(), but if you really want todo this, here you'll go:
$c['Controller'] = function($c) {
$routeInfo = $c['router']->dispatch($c['request']);
$args = $routeInfo[2];
$userId = $args['userId'];
return new Controller($userId);
};
Note: slim3 also urldecoded this values so may do this as well urldecode($args['userId']) Source
create a container wrapper and a maincontroller then extend all your controller from your maincontroller, then you have access to the container.
here is how i solved this problem:
https://gist.github.com/boscho87/d5834ac1ba42aa3da02e905aa346ee30

Symfony2 entity manager get not working all the time

I found a strange issue in symfony2 (maybe is not strange and i did a mistake somewhere):
i'm trying to call an entity manager method that i defined in the entity class:
//Entity/organisation.php
/**
* #return string
*/
public function getApiUrl(){
return $this->api_url;
}
and i don't always get a return value for the same object
the call is made from a controller method:
private function addApiLog($organisationId, $callType, $eventInfo){
$em = $this->getEntityManager();
$organisation = $em->find('\WebAgenda\Entity\Organisation', $organisationId);
if (null === $organisation) {
die();
}
$apiUrl = $organisation->getApiUrl();
$apiKey = $organisation->getApiKey();
$fc = fopen("debug_api_log.txt", "a");
fwrite($fc, date("Y-m-d H:i:s")." - ".$callType." - ".$organisationId." - ".$organisation->getName()." - ".$apiUrl."\n");
fclose($fc);
if(trim($apiUrl)!='' && $apiUrl!='-'){
the 'addApiLog()' methos is called from different methods depending on the action and even though the organisationId that is passed to it is the same and i get the organisation object, sometimes the $organisation->getApiUrl() method doesn't return anything and the $organisation->getName(), always return the correct value: http://screencast.com/t/HQ2NuNfWSG9
What am I missing? Why i don't get values?
Thank you!
Replace $em = $this->getEntityManager();
With this $em = $this->getDoctrine()->getManager();
And then use your repository
$myRepo = $em->getRepository('NamespaceMyBundle:Organisation');
$organisation = $myRepo->find($organisationId);
You said the addApiLog() method is called from different methods depending on the action.
Maybe not all your methods have access to the Context ?

Testing 2 consecutive client requests in Symfony2

In Symfony2, I want to test a controller action with 2 subsequent requests if it behaves properly.
The first request will analyze the database and take appropriate action, the second request will also analyze the database and take a different action.
My code goes as follows:
protected function setUp() {
$this->_client = static::createClient();
$kernel = static::$kernel;
$kernel->boot();
$this->_em = $kernel->getContainer()->get('doctrine.orm.default_entity_manager');
$this->_em->beginTransaction();
}
public function testAddToCartWith2Posts() {
$this->addObjects(); // Initialize the database
$object = static::$kernel->getContainer()->get('doctrine')->getRepository('BaseBundle:Object')->findAll()[0];
$id = $object->getId();
$crawler = $this->_client->request('POST', '/cart/add/' . $id);
$crawler = $this->_client->request('POST', '/cart/add/' . $id);
$session = static::$kernel->getContainer()->get('session');
$cart = $session->get('cart');
$this->assertEquals($session->getId(), $cart->getSession());
$this->assertEquals(2, count($cart->getCartItems()));
}
The first request is able to read the list of objects. The second request is not.
The database becomes empty between requests. How could I fix this problem?

Zf2 and Doctrine Annotations give trouble to make a 'new' form

I am trying to create a form to create a new product.
In my Controller I have the follwoing code:
public function newAction() {
$repo = $this->getEntityManager()->getRepository('Swap\Entity\Product');
$builder = new AnnotationBuilder($this->getEntityManager());
$form = $builder->createForm($repo);
$config = $this->getModuleConfig();
if (isset($config['swap_form_extra'])) {
foreach ($config['swap_form_extra'] as $field) {
$form->add($field);
}
}
$form->setHydrator(new DoctrineHydrator($this->getEntityManager(), 'Swap\Entity\Product'));
$form->bind($repo);
return new ViewModel(array('form' => $form));
}
Now this gives me the follwing error:
Class "Swap\EntityRepository\Product" sub class of "Doctrine\ORM\EntityRepository" is not a valid entity or mapped super class.
I am not sure if this has anything to do with it: But when you want to edit an object in a form you can do:
$repo = $this->getEntityManager()->getRepository('Swap\Entity\Product');
$id = (int) $this->getEvent()->getRouteMatch()->getParam('id', '0');
$product = $repo->find(1);
$productNames = $this->getEntityManager()->getRepository('Swap\Entity\ProductGroup')->findAll();
$product->SetProductGroup($productNames);
$builder = new AnnotationBuilder($this->getEntityManager());
$form = $builder->createForm($product);
But not sure how to get the product in a form to create a new entity.
Any suggestions?
Forms are build around entities, not with repositories. There is a clear distinction between them in Doctrine: entities are objects that hold state, that are related to database tables and where you can create new ones, update existing ones and remove ones for. Repositories are helper classes. They help you to find entities. Usually you find one by id or find them all, but repositories help you also to find one or multiple entities via a specific property.
That said, the form builder requires entities. In both the edit as the new action, you want to build based on the entity. In the editAction, you do this (pseudo):
$product = findMyProductEntity();
$form = $builder->createForm($product);
In the newAction, you do this (pseudo):
$repository = findMyProductRepository();
$form = $builder->buildForm($repository);
In this case, you also need to inject the entity and not the repository. How? Simply, just use new:
public function newAction()
{
$product = new Swap\Entity\Product;
$builder = new AnnotationBuilder($this->getEntityManager());
$form = $builder->createForm($product);
// Rest of your code
}
You told it to build the form from an entity repository instance, and not an entity itself.
$form = $builder->createForm($repo); // $repo is not an entity!

Categories