How to use KnpPaginatorBundle to paginate results for a search form? - symfony-2.8

I'm working on a Symfony 2 project and I used KnpPaginatorBundle the first page works correctly but the second one shows me this Error : " The controller must return a response (null given). Did you forget to add a return statement somewhere in your controller? " i didn't understand this please help me
this is my controller:
public function searchAction(Request $request) {
$search_form = $this->createForm(new SearchInterventionBatimentType());
if ($request->isMethod('post')) {
$search_form->handleRequest($request);
if ($search_form->isValid()) {
$data = $search_form->getData();
$from = $data['from'];
$to = $data['to'];
$intervenant= $data['intervenant'];
$type= $data['type'];
$batiment = $data['batiment'];
$em = $this->getDoctrine()->getManager();
$intervention = new InterventionBatiment();
if(is_null($intervenant) && is_null($type) && is_null($batiment)) {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByDate($from,$to);
} elseif(is_null($type) && is_null($batiment)) {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByDateAndIntervenant($from,$to,$intervenant);
} elseif (is_null($intervenant) && is_null($batiment)) {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByDateAndType($from,$to,$type);
} elseif (is_null($intervenant) && is_null($type)) {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByDateAndBatiment($from,$to,$batiment);
} elseif (is_null($batiment)) {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByDateAndIntervenantAndType($from,$to,$type,$intervenant);
} else {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByAll($from,$to,$type,$intervenant,$batiment);
}
$paginator= $this->get('knp_paginator');
$result= $paginator->paginate(
$intervention, /* query NOT result */
$request->query->getInt('page', 1)/*page number*/,
$request->query->getInt('limit', 8)/*limit per page*/
);
return $this->render(
'SecteurBundle:InterventionBatiment:recherche.html.twig',
array('interventions' => $result,'form' => $search_form->createView())
);
}
}
}

the controller should always need to send a response.
In your case you need to send a response if the form is not valid
if ($search_form->isValid()) {
}
return your response here too (if the form is not valid)

Related

Validator not validating the request in Laravel 8

I am inserting the data. The data is being entering quite fine but whenever I enter a letter the entry is done but that entry is converted to '0'.
This is my controller store function:
public function store(GuidanceReportRequest $request)
{
$stats = GuidanceReport::where('user_id', $request->user_id)->whereDate('created_at', now())->count();
if ($stats > 0) {
Session::flash('warning', 'Record already exists for current date');
return redirect()->route('reports.index');
}
if ((!empty($request->call_per_day[0]) && !empty($request->transfer_per_day[0])) ||
(!empty($request->call_per_day[1]) && !empty($request->transfer_per_day[1])) || (!empty($request->call_per_day[2])
&& !empty($request->transfer_per_day[2]))
) {
foreach ($request->category as $key => $value) {
$catgeory_id = $request->category[$key];
$call_per_day = $request->call_per_day[$key];
$transfer_per_day = $request->transfer_per_day[$key];
if (!empty($catgeory_id) && !empty($call_per_day) && !empty($transfer_per_day)) {
GuidanceReport::create([
"user_id" => $request->user_id,
"categories_id" => $catgeory_id,
"call_per_day" => $call_per_day,
"transfer_per_day" => $transfer_per_day,
]);
}
}
} else {
GuidanceReport::create($request->except('category', 'call_per_day', 'transfer_per_day'));
}
Session::flash('success', 'Data Added successfully!');
return redirect()->route('reports.index');
}
This is my Validation Request code
public function rules()
{
$rules = [];
$request = $this->request;
if ($request->has('transfer_per_day')) {
if (!empty($request->transfer_per_day)) {
$rules['transfer_per_day'] = "numeric";
}
}
if ($request->has('call_per_day')) {
if (!empty($request->call_per_day)) {
$rules['call_per_day'] = "numeric";
}
}
if ($request->has('rea_sign_up')) {
if (!empty($request->rea_sign_up)) {
$rules['rea_sign_up'] = "numeric";
}
}
if ($request->has('tbd_assigned')) {
if (!empty($request->tbd_assigned)) {
$rules['tbd_assigned'] = "numeric";
}
}
if ($request->has('no_of_matches')) {
if (!empty($request->no_of_matches)) {
$rules['no_of_matches'] = "numeric";
}
}
if ($request->has('leads')) {
if (!empty($request->leads)) {
$rules['leads'] = "numeric";
}
}
if ($request->has('conversations')) {
if (!empty($request->conversations)) {
$rules['conversations'] = "numeric";
}
}
return $rules;
}
Although I check the type in which request is being sent from controller and recieved from the request validation and it is Object. So how can I solve the issue.

Yii2 signup without saving session data

I have registration form in my Yii2 advanced application. In my application only admin can register users. But when I register new user, admin session data are destroyed and new user's session data are set. What I am trying is not to change session data when I register new user. Admin user is still should be set to session data. How to solve this problem. This is my action in controller:
public function actionSignup()
{
$model = new SignupForm();
if(Yii::$app->user->can('admin'))
{
if (($response = self::ajaxValidate($model)) !== false)
return $response;
if (self::postValidate($model))
{
try
{
$trans = Yii::$app->db->beginTransaction();
if ($user = $model->signup()) {
Yii::$app->getUser()->login($user);
}
//tagidan tushgan odamining child_left, child_right tini o'zgartirish
$under = UserModel::findOne($user->id_parent_under);
if ($under->id_child_left == 0)
$under->id_child_left = $user->id;
else
$under->id_child_right = $user->id;
$under->update(false);
ChildrenBinaryModel::insertNewUser($user);
ChildrenClassicModel::insertNewUser($user);
$parents = ChildrenBinaryModel::find()->with('user')->where(["id_child" => $user->id])->orderBy(['depth' => SORT_ASC])->all();
$c_user = $user;
foreach($parents as $p)
{
$p_user = $p->user;
if ($p_user->id_child_left == $c_user->id)
$p_user->ball_left += 100;
else
$p_user->ball_right += 100;
$p_user->update(false);
$c_user = $p_user;
}
$trans->commit();
}
catch(\Exception $e)
{
$trans->rollBack();
return $this->renderContent($e->getMessage());
}
return $this->render('index');
}
return $this->render('signup', [
'model' => $model,
]);
}else{
throw new ForbiddenHttpException;
}
}
Checkout the documentation for \yii\web\User::login(). When this is run in your code by calling Yii::$app->getUser()->login($user), the session data is set to match your $user.
If it's always the admin user that's signing up new users, I'm not sure you even need to run the login method.
I have solved this problem. In order to make answer clearly and simple I will show you default signup action in site controller (Yii2 advanced template):
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->user->enableSession = false &&
Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
Only I have done was adding this
Yii::$app->user->enableSession = false
inside the if statement

how to add an image to product in prestashop

i have a pragmatically added product in my code , the product is added to presta correctly but not about its image .
here is some part of my code that i used :
$url= "localhost\prestashop\admin7988\Hydrangeas.jpg" ;
$id_productt = $object->id;
$shops = Shop::getShops(true, null, true);
$image = new Image();
$image->id_product = $id_productt ;
$image->position = Image::getHighestPosition($id_productt) + 1 ;
$image->cover = true; // or false;echo($godyes[$dt][0]['image']);
if (($image->validateFields(false, true)) === true &&
($image->validateFieldsLang(false, true)) === true && $image->add())
{
$image->associateTo($shops);
if (! self::copyImg($id_productt, $image->id, $url, 'products', false))
{
$image->delete();
}
}
but my product have not any image yet
the problem is in copyImg method ...
here is my copyImg function :
function copyImg($id_entity, $id_image = null, $url, $entity = 'products')
{
$tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
$watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
switch ($entity)
{
default:
case 'products':
$image_obj = new Image($id_image);
$path = $image_obj->getPathForCreation();
break;
case 'categories':
$path = _PS_CAT_IMG_DIR_.(int)$id_entity;
break;
}
$url = str_replace(' ' , '%20', trim($url));
// Evaluate the memory required to resize the image: if it's too much, you can't resize it.
if (!ImageManager::checkImageMemoryLimit($url))
return false;
// 'file_exists' doesn't work on distant file, and getimagesize make the import slower.
// Just hide the warning, the traitment will be the same.
if (#copy($url, $tmpfile))
{
ImageManager::resize($tmpfile, $path.'.jpg');
$images_types = ImageType::getImagesTypes($entity);
foreach ($images_types as $image_type)
ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'],
$image_type['height']);
if (in_array($image_type['id_image_type'], $watermark_types))
Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
}
else
{
unlink($tmpfile);
return false;
}
unlink($tmpfile);
return true;
}
can anybody help me ?
You have 2 issues:
You are passing 5th parameter (with value) to copyImg, while the function does not have such.
Your foreach ($images_types as $image_type) loop must include the Hook as well (add open/close curly braces).
foreach ($images_types as $image_type)
{
ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'], $image_type['height']);
if (in_array($image_type['id_image_type'], $watermark_types))
Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
}
You should also check if the product is imported correctly, expecially the "link_rewrite" and if the image is phisically uploaded in the /img/ folder.

Laravel4: WhereHas Eloquent Issue (nested). callback function error

I tried doing a search function where the only field would be an <input type='text' /> it'll be stripped into an array() then passed to a whereLoop.
static function generateSearch($fields, $queryString)
{
return function($query) use($queryString, $fields)
{
foreach($fields as $field) {
$query = $query->orWhere($field, 'like', $queryString);
}
$query = $query->whereHas('category', function($_query) use ($queryString)
{
$_query->where('name','like',$queryString);
});
};
}
public static function search($query)
{
$searchBits = explode(' ', $query);
$query = Lead::with(array('user', 'category'));
$ctr = 0;
if(Category::whereIn('name', $searchBits)->count() != 0) {
$query = $query->whereHas('category', function($query) use ($searchBits)
{
$ctr = 0;
foreach($searchBits as $bit) {
$bit = "%".$bit."%";
$callback = "orWhere";
$queryFunc = Lead::generateSearch(array('name'), $bit);
if($ctr == 0) {
$callback = "where";
}
$query = $query->$callback($queryFunc);
}
});
}else {
foreach($searchBits as $bit) {
$bit = "%".$bit."%";
$callback = "orWhere";
$queryFunction = Lead::generateSearch(array('name', 'website', 'name', 'email'), $bit);
if($ctr == 0) {
$callback = "where";
}
$query = $query->$callback($queryFunction);
$ctr++;
}
}
$query = $query->orderBy('id','desc');
return $query;
}
Category only has ONE row as of the moment: its - "hot"
if i type in any keyword, it'll directly go to generateSearch()
but if i type in "hot", it'll send an error
Call to undefined method
Illuminate\Database\Query\Builder::category()
does anybody know what's up?
found the error. after looking deep within the callstack. i should not have added the
$query = $query->whereHas('category', function($_query) use ($queryString)
{
$_query->where('name','like',$queryString);
});
inside the generateSearch() or i should create another function for it. its being called by category callback as well.

CakePHP Auth Component Using 2 Tables

CakePHP Version 1.2.5
I would like a single user to have multiple email addresses.
I would like a single user to have a single password.
I would like users to log in using any of their multiple email addresses and their single password.
I have created a users table with an id and a password field.
I have created a user_email_addresses table with an id field a user_id field and an email_address field.
Question:
How do I modify the auth component minimally to look for the "username" in this case, "email_address", in the user_email_addresses table and the "password" in the users table?
Seems as though modifying the identify method in the auth component might do it. But I think modifying the auth component directly is a bad idea - any ideas on how to extend and still possibly modify the identify method? http://cakebaker.42dh.com/2009/09/08/extending-cakephps-core-components/ or possibly nominate a different authenticate object?
Starting line 774:
function identify($user = null, $conditions = null) {
if ($conditions === false) {
$conditions = null;
} elseif (is_array($conditions)) {
$conditions = array_merge((array)$this->userScope, $conditions);
} else {
$conditions = $this->userScope;
}
if (empty($user)) {
$user = $this->user();
if (empty($user)) {
return null;
}
} elseif (is_object($user) && is_a($user, 'Model')) {
if (!$user->exists()) {
return null;
}
$user = $user->read();
$user = $user[$this->userModel];
} elseif (is_array($user) && isset($user[$this->userModel])) {
$user = $user[$this->userModel];
}
if (is_array($user) && (isset($user[$this->fields['username']]) || isset($user[$this->userModel . '.' . $this->fields['username']]))) {
if (isset($user[$this->fields['username']]) && !empty($user[$this->fields['username']]) && !empty($user[$this->fields['password']])) {
if (trim($user[$this->fields['username']]) == '=' || trim($user[$this->fields['password']]) == '=') {
return false;
}
$find = array(
$this->userModel.'.'.$this->fields['username'] => $user[$this->fields['username']],
$this->userModel.'.'.$this->fields['password'] => $user[$this->fields['password']]
);
} elseif (isset($user[$this->userModel . '.' . $this->fields['username']]) && !empty($user[$this->userModel . '.' . $this->fields['username']])) {
if (trim($user[$this->userModel . '.' . $this->fields['username']]) == '=' || trim($user[$this->userModel . '.' . $this->fields['password']]) == '=') {
return false;
}
$find = array(
$this->userModel.'.'.$this->fields['username'] => $user[$this->userModel . '.' . $this->fields['username']],
$this->userModel.'.'.$this->fields['password'] => $user[$this->userModel . '.' . $this->fields['password']]
);
} else {
return false;
}
$model =& $this->getModel();
$data = $model->find(array_merge($find, $conditions), null, null, 0);
if (empty($data) || empty($data[$this->userModel])) {
return null;
}
} elseif (!empty($user) && is_string($user)) {
$model =& $this->getModel();
$data = $model->find(array_merge(array($model->escapeField() => $user), $conditions));
if (empty($data) || empty($data[$this->userModel])) {
return null;
}
}
if (!empty($data)) {
if (!empty($data[$this->userModel][$this->fields['password']])) {
unset($data[$this->userModel][$this->fields['password']]);
}
return $data[$this->userModel];
}
return null;
}
AuthComponent::identify() takes two parameters, $user and $conditions
if ($conditions === false) {
$conditions = null;
} elseif (is_array($conditions)) {
$conditions = array_merge((array)$this->userScope, $conditions);
} else {
$conditions = $this->userScope;
}
Looking at the above snippet, if you pass false as the $conditions, the method will execute with no model conditions.
Also, looking at the rest of the code, if you pass a $user value of type string, it won't execute most of the user-related code until it gets here:
} elseif (!empty($user) && is_string($user)) {
$model =& $this->getModel();
$data = $model->find(array_merge(array($model->escapeField() => $user), $conditions));
if (empty($data) || empty($data[$this->userModel])) {
return null;
}
}
Here it runs Model::escapeField(), with no parameters, which returns an escaped version of User.id (by default) and maps this field to the string that was passed in. It then merges this with the $conditions array and performs a Model::find().
It should be safe to say that if the string is the user's ID and there are no conditions it will find the person with that ID every time.
As such, you should be able to extend AuthComponent to do what you want like so:
// app/controllers/components/app_auth.php
<?php
App::import('Component', 'Auth');
class AppAuthComponent extends AuthComponent {
/**
* Custom user identification
*/
function identify($user=null, $conditions=null) {
// get the model AuthComponent is configured to use
$model =& $this->getModel(); // default is User
// do a query that will find a User record when given successful login data
$user = $model->find('first', array('conditions' => array(
'EmailAddress.' . $this->fields['username'] => $user[$this->userModel][$this->fields['username']],
'User.' . $this->fields['password'] => $user[$this->userModel][$this->fields['password']],
));
// return null if user invalid
if (!$user) {
return null; // this is what AuthComponent::identify would return on failure
}
// call original AuthComponent::identify with string for $user and false for $conditions
return parent::identify($user[$this->userModel][$model->primaryKey], false);
}
}
?>
You will have to replace all references to Auth with AppAuth in your application unless you follow this handy tip (the approach in the comments is nice).