I have this code in my controller:
/**
* #Secure(roles="IS_AUTHENTICATED_FULLY")
* #Route("/rpni/registro/producto/1/guardar", name="productoGuardarPasoUno")
* #Method("POST")
*/
public function guardarPaso1Action(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$response['success'] = false;
$status = 400;
if ($request->isXmlHttpRequest()) {
$productoSolicitudRequest = $request->request->get('productoSolicitud');
$entProductoSolicitud = $em->getRepository("AppBundle:ProductoSolicitud")->find($session->get('productoSolicitudId'));
$entProducto = $em->getRepository("AppBundle:Producto")->find($productoSolicitudRequest['producto']['nombre']);
$entCondicionProducto = $em->getRepository("AppBundle:CondicionProducto")->find($productoSolicitudRequest['condicion_producto']);
$entFinalidadProducto = $em->getRepository("AppBundle:FinalidadProducto")->find($productoSolicitudRequest['finalidad_producto']);
$entProcedenciaProducto = $em->getRepository("AppBundle:ProcedenciaProducto")->find($productoSolicitudRequest['procedencia_producto']);
$entSolicitudUsuario = $em->getRepository("AppBundle:SolicitudUsuario")->find($session->get('solicitudUsuarioId'));
if ($entProductoSolicitud)
{
$entProductoSolicitud->setProducto($entProducto);
$entProductoSolicitud->setCondicionProducto($entCondicionProducto);
$entProductoSolicitud->setFinalidadProducto($entFinalidadProducto);
$entProductoSolicitud->setProcedenciaProducto($entProcedenciaProducto);
$entProductoSolicitud->setSolicitudUsuario($entSolicitudUsuario);
try {
$em->flush();
} catch (\Exception $e) {
$response['error'] = $e->getMessage();
return new JsonResponse($response, $status);
}
} else {
$newEntProductoSolicitud = new Entity\ProductoSolicitud();
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $newEntProductoSolicitud);
if ($formProductoSolicitud->isValid())
{
try {
$em->persist($newEntProductoSolicitud);
$em->flush();
$session->set('productoSolicitudId', $newEntProductoSolicitud->getId());
$session->set('productoId', $entProducto->getId());
$response['success'] = true;
// Debug: remover cuando se termine el Bundle
$response['productoSolicitudId'] = $session->get('productoSolicitudId');
$response['productoId'] = $session->get('productoId');
$status = 200;
} catch (Exception $ex) {
$response['error'] = $ex->getMessage();
return new JsonResponse($response, $status);
}
} else {
$response['error'] = $this->get('translator')->trans('formularioNoValido');
$response['formError'] = $this->getFormErrors($formProductoSolicitud);
return new JsonResponse($response, $status);
}
}
return new JsonResponse($response, $status);
}
}
Which I'm trying to use for create and for update purposes. When I send the form through Ajax I get this response from Symfony2:
{
"success":false,
"error":"formularioNoValido",
"formError":{
"producto":{
"nombre":[
]
},
"lote":[
],
"procedencia_producto":[
],
"finalidad_producto":[
],
"condicion_producto":[
]
}
}
And nothing else to give me a clue. The weird part is that checking Post tab in Firebug give me this output:
Parameters application/x-www-form-urlencodedDo not sort
productoSolicitud[_token] wC_MAeVs7ZAGSpkvLYux6RKrLq46aivxXxiCZr6pNeU
productoSolicitud[condici... 1
productoSolicitud[finalid... 1
productoSolicitud[lote] 11
productoSolicitud[procede... 1
productoSolicitud[product... 4
Source
productoSolicitud%5Bproducto%5D%5Bnombre%5D=4&productoSolicitud%5Bprocedencia_producto%5D=1&productoSolicitud%5Bfinalidad_producto%5D=1&productoSolicitud%5Bcondicion_producto%5D=1&productoSolicitud%5Blote%5D=11&productoSolicitud%5B_token%5D=wC_MAeVs7ZAGSpkvLYux6RKrLq46aivxXxiCZr6pNeU
See the image below:
So, where the error is? Why form is not valid? Any clue? Advise?
If I'm not mistaken, your action only returns that response from this else statement :
else {
$newEntProductoSolicitud = new Entity\ProductoSolicitud();
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $newEntProductoSolicitud);
if ($formProductoSolicitud->isValid())
{
try {
$em->persist($newEntProductoSolicitud);
$em->flush();
$session->set('productoSolicitudId', $newEntProductoSolicitud->getId());
$session->set('productoId', $entProducto->getId());
$response['success'] = true;
// Debug: remover cuando se termine el Bundle
$response['productoSolicitudId'] = $session->get('productoSolicitudId');
$response['productoId'] = $session->get('productoId');
$status = 200;
} catch (Exception $ex) {
$response['error'] = $ex->getMessage();
return new JsonResponse($response, $status);
}
} else {
$response['error'] = $this->get('translator')->trans('formularioNoValido');
$response['formError'] = $this->getFormErrors($formProductoSolicitud);
return new JsonResponse($response, $status);
}
}
I find it weird that you're checking your form's validity right after you created it from a new instance of ProductoSolicitud, is that really what you want to do ? Shouldn't you make this validity check in the case you got some data from the request ?
Maybe something like this :
if ($entProductoSolicitud)
{
$entProductoSolicitud->setProducto($entProducto);
$entProductoSolicitud->setCondicionProducto($entCondicionProducto);
$entProductoSolicitud->setFinalidadProducto($entFinalidadProducto);
$entProductoSolicitud->setProcedenciaProducto($entProcedenciaProducto);
$entProductoSolicitud->setSolicitudUsuario($entSolicitudUsuario);
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $entProductoSolicitud);
if ($formProductoSolicitud->isValid()) {
try {
$em->flush();
} catch (\Exception $e) {
$response['error'] = $e->getMessage();
return new JsonResponse($response, $status);
}
}
}
But I might have just misunderstood the problem :S
Well, since I found where the issue was I'll answer myself so others won't make the same mistake. At my code I never tell the form to handle the request so there is where the issue is. The code in the else turns in to this:
} else {
$newEntProductoSolicitud = new Entity\ProductoSolicitud();
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $newEntProductoSolicitud);
$formProductoSolicitud->handleRequest($request);
if ($formProductoSolicitud->isValid())
{
...
} catch (Exception $ex) {
$response['error'] = $ex->getMessage();
return new JsonResponse($response, $status);
}
} else {
....
}
}
return new JsonResponse($response, $status);
}
}
That's all, happy coding!!
Related
There are 3 queues in redis.
If I insert a data at a same time with different browsers, both requests are accepted.
I get 2 duplicated records. Any helps?
For example, the first request is on the 1st queue.
At the second request, 2nd queue is searched for finding the data.
But the data doesn't exist in the queue.
The second request is inserted on the queue.
Is it understandable?
public function save($evt_no, $type = "redis") {
$name = '';
$res = true;
try{
$headers = getallheaders();
$bodys = $_REQUEST;
$session = $_SESSION;
foreach ($_FILES as $fileKey=>$fileVal) {
if ($fileVal['error'] == 0) {
try {
$uploaded_row = $this->fileL->upload('queueEventParticipant', $fileKey, array() ,'queue');
} catch (\Exception $ex) {
throw $ex;
}
$bodys['file'][_return_numeric($fileKey)] = $uploaded_row;
}
}
$data = array(
'header' => $headers,
'body' => $bodys,
'session' => $session
);
$data['body']['evt_no'] = $evt_no;
$data = json_encode($data);
if($type == "redis"){
$name = $this->attendQueueRedisService->setNewRsvp($data);
} else {
throw new \Exception("No exist");
}
} catch (\Exception $ex){
log_message("error", $ex->getMessage());
throw $ex;
}
if($res){
return $name;
} else {
return "Error";
}
}
class AttendQueueRedisService extends CI_Model {
private $redisClient;
private $redisConfig;
const PREFIX_DONE = 'done_';
const PREFIX_ERROR = 'error_';
public function __construct() {
parent::__construct();
if ($this->load->config('redis', true, true)) {
$this->redisConfig = $this->config->config['redis'];
}
$this->redisClient = new Redis();
$this->redisClient->connect($this->redisConfig['hostname'], $this->redisConfig['port']);
$this->redisClient->auth($this->redisConfig['auth']);
$this->redisClient->select($this->redisConfig['queue']);
}
public function setNewRsvp($data) {
$key = uniqid('rsvp_'.gethostname().'_',true).':redis';
$this->redisClient->set($key, $data, 60 * 30);
return $key;
}
}
In add to cart function can be placed discount, discounts are made via xxx-hashid. i figure out that problem is when user want cheat and type random xxx-123456 my system crash.
hashid is from Ivan Akimov.
is possible to achiev, when hashID (userID) doesnt exist function return code isnt valid but without crash ?
public function getIdByHash($hashid) {
$response = ['valid' => false];
if ($hashid){
$response['valid'] = true;
$hashid = explode("PMX-",$hashid)[1];
$hashids = new Hashids("",6);
return $hashids->decode($hashid)[0];
}
if ($hashid){
$response ['valid'] = false;
return $hashids = "PMX-"."dGRLrb";
}
}
You could try :
public function getIdByHash($hashid) {
$response = ['valid' => false];
if ($hashid){
$response['valid'] = true;
try {
$hashid = explode("PMX-",$hashid)[1];
$hashids = new Hashids("",6);
return $hashids->decode($hashid)[0];
} catch(\Exception $e) {
$response ['valid'] = false;
}
}
return $hashids = "PMX-"."dGRLrb";
}
I'm setting up a rest-API on my server, and I want to update a table (i.e "comp_holding_stock"). but every time I test to post new data it returns "No item found"
Here is my controller
public function create_comp_holding_stock(){
$returnArr['status'] = '0';
$returnArr['response'] = '';
try {
if (!$this->input->post()) {
$returnArr['response'] = "Only POST method is allowed";
} else {
$holding_stock_data = array(
'comp_id' => $this->input->post('comp_id'),
'customer_id' => $this->input->post('customer_id'),
'quantity' => $this->input->post('quantity'),
'date' => date('Y-m-d H:i:s')
);
if (!isset($holding_stock_data)) {
$returnArr['response'] = "Some Parameters are missing";
} else {
$customer = $this->Customer->save_holding_stock($holding_stock_data);
if (!$customer) {
$returnArr['response'] = 'No items found';
} else {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
}
}
}
} catch (Exception $ex) {
$returnArr['response'] = "Error in connection";
$returnArr['error'] = $ex->getMessage();
}
$response = json_encode($returnArr, JSON_PRETTY_PRINT);
echo $response;
}
And here is my model below
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$success = $this->db->insert('comp_holding_stock', $holding_stock_data);
return $success;;
}
what am i doing wrong? what is the best approach to this scenarios
I would recommend try to check if you have load model in your controller.
And in your model try to do this.
public function save_holding_stock($holding_stock_data, $comp_id=FALSE)
{
if(!$comp_id == -1 || !$this->exists($comp_id))
{
if($this->db->insert('comp_holding_stock', $holding_stock_data))
{
$holding_stock_data['comp_id'] = $this->db->insert_id();
return TRUE;
}
return FALSE;
}
$this->db->where('comp_id', $comp_id);
return $this->db->update('comp_holding_stock', $holding_stock_data);
}
Try these changes in your code
In your controller,
$customer = $this->Customer->save_holding_stock($holding_stock_data);
$save_status = $this->db->affected_rows();
if ($save_status>0) {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
} else {
$returnArr['response'] = 'No items found';
}
In your model,
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$this->db->insert('comp_holding_stock', $holding_stock_data);
}
I was working in one Laravel Project using 92Five App. when access user List. its goto Something Went Wrong Page. Its Display Array to string conversion Error in Error Log.
In User Controller Following Functions are Defined.
Error :
[2016-08-09 13:13:12] log.ERROR: Something Went Wrong in User
Repository - getAllUsersData():Array to string conversion [] []
My Code :
public function getAllUsersData()
{
try{
$users = array();
$tempUsers = \User::all()->toArray();
$users = $this->getGroupBaseRole($tempUsers);
return $users;
}
catch (\Exception $e)
{
\Log::error('Something Went Wrong in User Repository - getAllUsersData():'. $e->getMessage());
throw new SomeThingWentWrongException();
}
}
public function getGroupBaseRole($groupMembersInfo) {
$data = [];
if(!empty($groupMembersInfo) && isset($groupMembersInfo)) {
foreach($groupMembersInfo as $user)
{
$banned = false;
$suspended = false;
$loginAttempt = 0;
$usersThrottle = \Throttle::where('user_id',$user['id'])->get()->toArray();
// print_r($usersThrottle); exit;
if(sizeof($usersThrottle) != 0)
{
foreach($usersThrottle as $userThrottle)
{
if($userThrottle['banned'] == true)
{
$banned = true;
}
if($userThrottle['suspended'] == true)
{
$suspended = true;
}
$loginAttempt = $loginAttempt + $userThrottle['attempts'];
}
$user['banned'] = $banned;
$user['suspended'] = $suspended;
$user['loginAttempt'] = $loginAttempt;
}
else
{
$user['banned'] = false;
$user['suspended'] = false;
$user['loginAttempt'] = 0;
}
$groupUser = \Sentry::findUserById($user['id']);
$groups = $groupUser->getGroups()->toArray();
if(sizeof($groups)!=0)
{
$user['role'] =$groups[0]['name'];
}
else
{
$user['role'] = '';
}
$data[] = $user;
}
}
return $data;
}
It seeems getGroupBaseRole() method accepts string, but you're trying to pass an array $tempUsers as first argument.
I'm doing a little page that lists all files that are in google drive. In the first time I do the authentication and save the refresh token + user id and email and then I list all the files. To get the information I do this:
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$list=$files->getItems();
$result = array_merge($result,$list);
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
And it works, but if the user refresh the page, I have do refresh the access token (getting the refresh token from db) and then proceed to do the same as above. In this case that code gives me an error because this time I get an associative array when I do:
$files = $service->files->listFiles($parameters);
To make it work I need to change the code to:
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$list=$files['items'];
$result = array_merge($result,$list);
$pageToken = $files['nextPageToken'];
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
This shouldn't happen but I have no idea what's wrong.
From the relevant php source of the class, I guess I found what makes you trouble.
Look at Google_DriveService.php:
// ~Line 119
public function listFiles($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) { // THIS CALL HERE
return new Google_FileList($data);
} else {
return $data;
}
}
It checks if you want to work with objects, or not: $this->useObjects().
This method is defined in the super class, Google_ServiceResource.php:
// ~Line 180
public function useObjects() {
global $apiConfig;
return (isset($apiConfig['use_objects']) && $apiConfig['use_objects']);
}
This tells me, that when you configure your service, you will have to set 'use_object' to true.