I'm using modal and I just want to use dropdown select method in laravel 7 - laravel-7

This is my code in my Controller but I already try this method without using modal and it works.
public function create()
{
$department = Department::pluck('department', 'id');
return view('positions.create',compact('department'));
}
public function store()
{
$validator = Validator::make(Request::all(), [
'dep_id' => 'required',
'position' => 'required',
],
[
'dep_id.required' => 'Department Required',
'position.required' => 'Position Required',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
Position::create(Request::all());
Session::flash('message', 'Position Created Successfully');
return redirect()->back();
}
This is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Position extends Model
{
protected $guarded = [];
public function department(){
return $this->belongsTo('App\Department','dep_id','id');
}
}
This is my code in my create modal form, but I get this error:
Undefined variable: department
I want to use the modal form for my project.
<div class="modal-body">
#include('alert')
{!! Form::open(['method'=>'POST','action'=>'PositionController#store']) !!}
<div class="form-group">
<label>Department</label>
{!! Form::select('dep_id',$department,null,['class'=>'form-control','placeholder'=>'PLEASE SELECT']) !!}
</div>
<div class="form-group">
<label>Position</label>
{!! Form::text('position',null,['class'=>'form-control']) !!}
</div>
<div class="text-end">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
{!! Form::close() !!}
</div>

Related

Error occurs in the template of component EmployeeCreateComponent

I'm new to Angular and working on httpclient and httpservice project of CRUD application. While compiling with ng serve in VS code I get the following error:
error: ERROR in src/app/employee-create/employee-create.component.html:18:65 - error TS2554: Expected 1 arguments, but got 0.
employee-create.component.html
<div class="container custom-container">
<div class="col-md-12">
<h3 class="mb-3 text-center">Create Employee</h3>
<div class="form-group">
<input type="text" [(ngModel)]="employeeDetails.name" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="text" [(ngModel)]="employeeDetails.email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="text" [(ngModel)]="employeeDetails.phone" class="form-control" placeholder="Phone">
</div>
<div class="form-group">
<button class="btn btn-success btn-lg btn-block" (click)="addEmployee()">Create Employee</button>
</div>
</div>
</div>
employee-create component.ts
import { Component, OnInit, Input } from '#angular/core';
import { Router } from '#angular/router';
import { RestApiService } from "../shared/rest-api.service";
#Component({
selector: 'app-employee-create',
templateUrl: './employee-create.component.html',
styleUrls: ['./employee-create.component.css']
})
export class EmployeeCreateComponent implements OnInit {
#Input() employeeDetails = { name: '', email: '', phone: 0 }
constructor(
public restApi: RestApiService,
public router: Router
) { }
ngOnInit() { }
addEmployee() {
this.restApi.createEmployee(this.employeeDetails).subscribe((data: {}) => {
this.router.navigate(['/employees-list'])
})
}
}
The error is obvious in your template addEmployee() method on button click doesnt have any param.
(click)="addEmployee()"
But in your component you are passing dataEmployee param in addEmployee(dataEmployee) method (which looks like not in use).
Hence you can remove dataEmployee param from addEmployee() method.
addEmployee() { // <=== no dataEmployee param
this.restApi.createEmployee(this.employeeDetails).subscribe((data: {}) => {
this.router.navigate(['/employees-list'])
})
}
addEmployee() { // <=== dataEmployee Parameter this.restApi.createEmployee(this.employeeDetails).subscribe((data: {}) => {
this.router.navigate(['/employees-list'])
})
}
you are not passing a Parameter in Html file but you are trying to get parameter in ts that's why you are getting Error.

Why is this react component not displaying content loaded?

I'm working on this project and I want to display the content I got from the backend routes via axios to Showcase component. But the code doesn't give the output as expected the updated state console.log(cont) is working and no issue but it doesn't rendering contents.The app.js state is received by the component. I want to display the names. The child functional component as follows.
import React from 'react';
import {
Table,
Button
} from 'reactstrap';
function Showcase(props) {
const title = props.title;
const contents = props.contents;
let items_body = [];
items_body = contents.map(cont => {
console.log(cont)
if(cont.category === 'Men') {
return (
<div className="item_card" key={cont._id}>
<div className="itemC_right">
<div className="itemCR_topA">
<div className="itemCR_topA_title">{cont.name}</div>
</div>
</div>
</div>
)
}
else if(cont.category === 'Women') {
return (
<div className="lead content d-flex d-flex justify-content-center mb-3" key={cont.id}>
<div>Name : {cont.name}</div>
</div>
)
}
else if(cont.category === 'Kids') {
return (
<div className="lead content d-flex d-flex justify-content-center mb-3" key={cont.id}>
<div>Name : {cont.name}</div>
</div>
)
}
else
return (
null
)
})
return (
<div id="showcase">
<div id="showcase_card">
<div className="row">
<div className="col-sm-6 d-flex flex-row mt-1">
<h1 className="display-3 txt_secondary text-left" id="showcase_title">{title}</h1>
</div>
<div className="col-sm-6 d-flex flex-row-reverse mt-4">
<small className="txt_secondary text-right">Oreo is a online shopping store made just for you.</small>
</div>
</div>
<div>
{items_body}
</div>
</div>
</div>
)
}
export default Showcase;
The App.js class component
class App extends React.Component {
state = {
title: 'Oreo',
contents: []
}
changeState = (category,data) => {
this.setState({
title: category,
contents: data
})
}
handleNavigation = (e) => {
const option = e.target.innerHTML;
switch(option) {
case "Men":
axios.get('/api/items/men/2')
.then(res => {
this.changeState('Men',res.data);
// console.log(res.data)
})
break;
}
}
render() {
return (
<div>
<NavigationBar handleNavigation={this.handleNavigation} />
<Showcase title={this.state.title} contents={this.state.contents} />
<ItemWindow />
<BottomBar />
</div>
);
}
}
export default App;
In NavigationComponent.js when clicked on Men I'm sending it to App.js then it handles the click event. Why doesn't Showcase.js cannot show/render results? Help.
So I got rid of the if statements under the Showcase.js and could get my results. It seems that I was checking the category twice(in handleNavigation and here). I also added async and await as tonkalata's way.

How to get a value from a form to make a query in AdonisJs?

I'm coding a search form to get some data from database
I don't know what am i doing wrong. The page just refreshes and nothing happens.
1- I have a form with a input called "term"
2- My route: Route.get('/telefone', 'TelefoneController.show')
MY CONTROLLER
async show ({ params, request, response, view }) {
const term = request.input('term');
const nome = await Telefone.query().where('atendente', 'LIKE',
'%'+term+'%').fetch()
console.log(nome);
return view.render('telefone', {
nome: nome,
})
}
MY HTML
<div class="container d-flex">
<form action="{{ route('/telefone')}}" method="get" class="col-sm-8">
<div class="form-group">
<label for="campotel">Buscar Nome</label>
<input type="text" name="term" class="form-control" id="campotel" placeholder="Digite o nome do funcionário">
</div>
<button type="submit" class="btn btn-success float-right">Buscar</button>
</form>
</div>
DB STRUCTURE
class TelefoneSchema extends Schema {
up () {
this.create('telefones', (table) => {
table.increments()
table.string('ramal')
table.string('voip')
table.string('atendente')
table.integer('id_departamento')
.unsigned()
.references('id')
.inTable('departamentos')
.onUpdate('CASCADE')
.onDelete('CASCADE')
table.integer('id_polo_telefone')
.unsigned()
.references('id')
.inTable('polos')
.onUpdate('CASCADE')
.onDelete('CASCADE')
table.timestamps()
})
}
down () {
this.drop('telefones')
}
}
module.exports = TelefoneSchema
page just refresh and nothing happens
I tried on my side without being able to reproduce the case.
But I have some information that might perhaps help you:
When the query returns no value the result is null. -> make sure your db have values
My test code (work fine):
My controller:
'use strict'
const Telefone = use('App/Models/Telefone')
class TelefoneController {
async show ({ params, request, response, view }) {
const term = request.input('term')
console.log(term)
const result = await Telefone.query().where('atendente', 'like',
'%'+term+'%').fetch()
const nome = result.toJSON()
console.log(nome) // Return JSON array
return view.render('welcome', {
nome: nome,
})
}
}
module.exports = TelefoneController
My schema (I don't use all your datas) :
class TelefoneSchema extends Schema {
up () {
this.create('telefones', (table) => {
table.increments()
table.string('ramal')
table.string('voip')
table.string('atendente')
table.timestamps()
})
}
down () {
this.drop('telefones')
}
}
My view :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Hello Adonis</title>
</head>
<body>
<h1>Ramal : {{ nome[0].ramal }}</h1>
<div class="container d-flex">
<form action="{{ route('/telefone')}}" method="get" class="col-sm-8">
<div class="form-group">
<label for="campotel">Buscar Nome</label>
<input type="text" name="term" class="form-control" id="campotel" placeholder="Digite o nome do funcionário">
</div>
<button type="submit" class="btn btn-success float-right">Buscar</button>
</form>
</div>
</body>
</html>
I hope it might help you a little bit.

Force preact-router to reload a page completely

I have a page that contains a link to a secondary page that creates a record. Here is the problem I'm running into: If I fill out the fields on the secondary page, and return back to create another item, the previous data is still inside my text boxes.
I don't know if this is just how preact works. I thought that by calling route it would unmount the component, thus clearing state. I even tried adding unique keys to my routes (which I heard forces them to unmount).
I really am at wits end.
app.jsx
const App = () => (
<div>
<Header/>
<Router history={createHashHistory()}>
<Home path="/" />
<DisplayUsers key="displayUsers" path="/display-users"/>
<CreateUser key="createUser" path="/create-user"/>
</Router>
</div>
);
create-item.jsx
import { h, Component } from "preact";
import { route } from 'preact-router';
import { $post } from "app/services/ajax.jsx";
import Section from "app/components/section/section.jsx";
import UserList from "app/components/user-list/user-list.jsx";
class CreateUser extends Component {
constructor(props) {
super(props);
this.state = {
userName: "",
route: ""
};
}
handleSubmit = (event) => {
event.preventDefault();
$post("/api/users", this.state, () =>
{
route('/display-users');
}
);
}
handleChange = (event) => {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
return (
<Section title="New User">
<form onSubmit={this.handleSubmit}>
<div className="mat-field">
<label
htmlFor="userName"
className="mat-field__label">
User Name:
</label>
<input
type="text"
id="userName"
name="userName"
className="mat-field__input"
autoComplete="off"
autoFocus="autoFocus"
maxlength="30"
required
onChange={this.handleChange}/>
</div>
<div className="mat-field">
<label
htmlFor="route"
className="mat-field__label">
Route To:
</label>
<UserList
name="route"
onChange={this.handleChange}/>
</div>
{/* Buttons */ }
<div>
<input
type="submit"
value="Create"
className="mat-button mat-button--secondary mat-button--raised"/>
<a
href="/display-users"
className="mat-button">Cancel</a>
</div>
</form>
</Section>
);
}
}
export default CreateUser;

Using Automapper to map viewmodel to domain model returns nulls in POST action?

I have a entity model that records some employee information. I have a similar view model.
In my create action I create a new instance of the viewmodel and pass a few lists for dropdowns.
In my Create Post action I map using AutoMapper the returned view model to the entity model.
I am doing something wrong because the posted back data doesn't seem to contain any of the view model data. It just contains nulls.
Any ideas what I am doing wrong?
Controller
// GET: /TimeCreditEntries/Create
public ActionResult Create()
{
var Model = new TimeCreditEntryViewModel(); //Create a new viewmodel to hold the TimeCreditEntry
Model.StationList = new SelectList(getStations(), "StationId", "Code");
Model.AuthorisedEmployee = new SelectList(getEmployees(), "EmployeeId", "FullNameSurnameFirst");
Model.AuthorisedPayment = new SelectList(getPaymentTypes(), "PaymentTypeId", "Code");
return View(Model); //View is returned with model as parameter.
}
// POST: /TimeCreditEntries/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "TimeCreditEntryId,RecordedDate,TimeCreditDate,ShiftId,StationId,AuthorisingEmployeeId,AuthorisedEmployeeId,ModifiedDate")] TimeCreditEntryViewModel timeCreditEntry)
{
if (ModelState.IsValid)
{
Mapper.CreateMap<TimeCreditEntryViewModel, TimeCreditEntry>();
db.TimeCreditEntries.Add(Mapper.Map<TimeCreditEntryViewModel, TimeCreditEntry> (timeCreditEntry));
db.SaveChanges();
return RedirectToAction("Register"); }
ViewBag.AuthorisedEmployeeId = new SelectList(db.Employees, "EmployeeId", "Title", timeCreditEntry.AuthorisedEmployeeId);
ViewBag.AuthorisingEmployeeId = new SelectList(db.Employees, "EmployeeId", "Title", timeCreditEntry.AuthorisingEmployeeId);
ViewBag.ShiftId = new SelectList(db.Shifts, "ShiftId", "Code", timeCreditEntry.ShiftId);
return View(timeCreditEntry);
}
View
#model ATAS.Models.ViewModels.TimeCreditEntryViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<fieldset>
<legend>Request to use time credit</legend>
<div class="form-group">
<label class="col-md-2 control-label" for="AuthorisedEmployee">Who</label>
<div class="col-md-2">
#Html.DropDownListFor(model => model.AuthorisedEmployee, Model.AuthorisedEmployee, "Select Employee", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.AuthorisedEmployeeId)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TimeCreditDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.TimeCreditDate, new { #class = "datepicker", id = "vacation" })
#Html.ValidationMessageFor(model => model.TimeCreditDate)
</div>r
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="StationList">Where</label>
<div class="col-md-2">
#Html.DropDownListFor(model => model.StationList, Model.StationList, "Choose Station", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="Shift">Which</label>
<div class="col-md-2">
#Html.DropDownList("Shift", new SelectList(string.Empty, "Value", "Text"), new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button class="btn btn-default" type="reset">Cancel</button>
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</fieldset>
</div>
}
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.datepicker').datepicker()
$("#Shift").prop("disabled", true);
//Dropdownlist Selectedchange event
$("#StationList").change(function () {
$("#Shift").empty();
if ($("#StationList").val() != "") {
$.ajax({
type: 'POST',
url: '#Url.Action("GetShiftsByStation")', // we are calling json method
dataType: 'json',
data: { selectedValue: $("#StationList").val() },
// here we are get value of selected Station and passing same value as input to json method GetShifts.
success: function (shiftList) {
// states contains the JSON formatted list
// of states passed from the controller
$("#Shift").append('<option value="' + null + '">' + "Choose shift" + '</option>');
$.each(shiftList, function (i, shift) {
$("#Shift").append('<option value="' + shift.Value + '">' + shift.Text + '</option>');
// here we are adding option for shifts
$("#Shift").prop("disabled", false);
});
},
error: function (ex) {
alert('Failed to retrieve shifts.' + ex);
}
});
return false;
}
else {
$("#Shift").empty();
$("#Shift").prop("disabled", true);
}
})
});

Resources