Validator not validating the request in Laravel 8 - 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.

Related

Custom directive to check the value of two or more fields

I tried my best to write a custom directive in Apollo Server Express to validate two input type fields.
But the code even works but the recording of the mutation already occurs.
I appreciate if anyone can help me fix any error in the code below.
This is just sample code, I need to test the value in two fields at the same time.
const { SchemaDirectiveVisitor } = require('apollo-server');
const { GraphQLScalarType, GraphQLNonNull, defaultFieldResolver } = require('graphql');
class RegexDirective extends SchemaDirectiveVisitor {
visitInputFieldDefinition(field) {
this.wrapType(field);
}
visitFieldDefinition(field) {
this.wrapType(field);
}
wrapType(field) {
const { resolve = defaultFieldResolver } = field;
field.resolve = async function (source, args, context, info) {
if (info.operation.operation === 'mutation') {
if (source[field.name] === 'error') {
throw new Error(`Find error: ${field.name}`);
}
}
return await resolve.call(this, source, args, context, info);
};
if (
field.type instanceof GraphQLNonNull
&& field.type.ofType instanceof GraphQLScalarType
) {
field.type = new GraphQLNonNull(
new RegexType(field.type.ofType),
);
} else if (field.type instanceof GraphQLScalarType) {
field.type = new RegexType(field.type);
} else {
// throw new Error(`Not a scalar type: ${field.type}`);
}
}
}
class RegexType extends GraphQLScalarType {
constructor(type) {
super({
name: 'RegexScalar',
serialize(value) {
return type.serialize(value);
},
parseValue(value) {
return type.parseValue(value);
},
parseLiteral(ast) {
const result = type.parseLiteral(ast);
return result;
},
});
}
}
module.exports = RegexDirective;

How can I seperate functions which are basically the same but use different states? Vue2/Vuex

Ive got a problem since i realized that I break the DRY(Dont repeat yourself) rule. So basically I have 2 modules(movies, cinemas) and few methods in them which look the same but use their module' state.
Example: Movies has 'movies' state. Cinemas has 'cinemas' state.
//cinemas.ts
#Mutation
deleteCinemaFromStore(id: string): void {
const cinemaIndex = this.cinemas.findIndex((item) => item.id === id);
if (cinemaIndex >= 0) {
const cinemasCopy = this.cinemas.map((obj) => {
return { ...obj };
});
cinemasCopy.splice(cinemaIndex, 1);
this.cinemas = cinemasCopy;
} else {
throw new Error("Provided id doesn't exist");
}
}
//movies.ts
#Mutation
deleteMovieFromStore(id: string): void {
const movieIndex = this.movies.findIndex((item) => item.id === id);
if (movieIndex >= 0) {
const moviesCopy = this.movies.map((obj) => {
return { ...obj };
});
moviesCopy.splice(movieIndex, 1);
this.movies = moviesCopy;
} else {
throw new Error("Provided id doesn't exist");
}
}
My struggle is: How can I seperate these methods into utils.ts if they have reference to 2 different states?
define another function that take the id, state and store context (this) as parameters :
function delete(id:string,itemsName:string,self:any){
const itemIndex= self[itemsName].findIndex((item) => item.id === id);
if (itemIndex>= 0) {
const itemsCopy = self[itemsName].map((obj) => {
return { ...obj };
});
itemsCopy.splice(itemIndex, 1);
self[itemsName] = itemsCopy;
} else {
throw new Error("Provided id doesn't exist");
}
}
then use it like :
//cities.ts
#Mutation
deleteCityFromStore(id: string): void {
delete(id,'cities',this)
}
//countries.ts
#Mutation
deleteCountryFromStore(id: string): void {
delete(id,'countries',this)
}

How to use KnpPaginatorBundle to paginate results for a search form?

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)

After successful login user is not logged into YII2 frontend

If I run the login function it prints User.
public function actionLogin(){
if ($model->load(Yii::$app->request->post()) && $model->login()) {
if (Yii::$app->user->isGuest) {
echo "guest";
} else {
echo "User";
}
return $this->redirect(['dashboard']);
}
After redirect If I run the dashboard function it prints guest.
public function actionDashboard()
{
if (Yii::$app->user->isGuest) {
echo "guest";
} else {
echo "User";
}
}
My Login model:
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
This is getUser function:
protected function getUser()
{
if ($this->_user === null) {
$this->_user = Customer::findByEmail($this->email);
}
return $this->_user;
}
Please help me to check in another function whether or not the user is logged in?
I successfully fixed this problem.
just change the backend/config/main.php or frontend/config/main.php
change this
'components' => [
'user' => [
'identityClass' => 'common\models\Customer', //or Any models you want
'enableAutoLogin' => true,
],
]

Codeception: acceptance test with selenium fails on "textarea"

I've got a function:
public function waitAndFill($element, $value, $timeOut = null)
{
$I = $this;
$I->_waitFor($element, $timeOut);
$I->fillField($element, $value);
$I->seeInField($element, $value);
}
And I use it like this:
$I->waitAndFill('#inputInfo', 'This is test info');
The textarea looks as follows
<textarea id="inputInfo"
name="company_description"
ng-model="company.company_description"
class="form-control"></textarea>
So, my test fails with this:
Step I see in field "#inputInfo","This is test info"
Fail Failed testing for 'This is test info' in company_description's value:
Failed asserting that an array contains 'This is test info'.
It works fine on <input> fields, but fails on <textarea>. Looks like it doesn't see any text at all.
This text is present on the screen shot made by the test.
What am I doing wrong?
It's a bug. The problem is this: $I->seeInField($element, $value); invokes $this->proceedSeeInField(array $elements, $value); which invokes a method getText() on the Facebook\WebDriver\Remote\RemoteWebElement object that it finds. If you read the documentation for Facebook\WebDriver\Remote\RemoteWebElement#getText() method it says that it returns the innerText for that element. So that's no bueno. To workaround this I removed the conditional for the textarea in this function.
protected function proceedSeeInField(array $elements, $value)
{
$strField = reset($elements)->getAttribute('name');
if (reset($elements)->getTagName() === 'select') {
$el = reset($elements);
$elements = $el->findElements(WebDriverBy::xpath('.//option[#selected]'));
if (empty($value) && empty($elements)) {
return ['True', true];
}
}
$currentValues = [];
if (is_bool($value)) {
$currentValues = [false];
}
foreach ($elements as $el) {
if ($el->getTagName() === 'textarea') {
$currentValues[] = $el->getText();
} elseif ($el->getTagName() === 'input' && $el->getAttribute('type') === 'radio' || $el->getAttribute('type') === 'checkbox') {
if ($el->getAttribute('checked')) {
if (is_bool($value)) {
$currentValues = [true];
break;
} else {
$currentValues[] = $el->getAttribute('value');
}
}
} else {
$currentValues[] = $el->getAttribute('value');
}
}
return [
'Contains',
$value,
$currentValues,
"Failed testing for '$value' in $strField's value: " . implode(', ', $currentValues)
];
}
You should change it to:
protected function proceedSeeInField(array $elements, $value)
{
$strField = reset($elements)->getAttribute('name');
if (reset($elements)->getTagName() === 'select') {
$el = reset($elements);
$elements = $el->findElements(WebDriverBy::xpath('.//option[#selected]'));
if (empty($value) && empty($elements)) {
return ['True', true];
}
}
$currentValues = [];
if (is_bool($value)) {
$currentValues = [false];
}
foreach ($elements as $el) {
if ($el->getTagName() === 'input' && $el->getAttribute('type') === 'radio' || $el->getAttribute('type') === 'checkbox') {
if ($el->getAttribute('checked')) {
if (is_bool($value)) {
$currentValues = [true];
break;
} else {
$currentValues[] = $el->getAttribute('value');
}
}
} else {
$currentValues[] = $el->getAttribute('value');
}
}
return [
'Contains',
$value,
$currentValues,
"Failed testing for '$value' in $strField's value: " . implode(', ', $currentValues)
];
}
Now it calls getAttribute('value') just like any other input element.
The is in file WebDriver.php