problem in storing data form into database laravel - javascript

I am trying to store some data in to the database. I have NewMember form this form will have data to be store in 3 tables users, restaurants, and addresses. It is showing the error MethodNotAllowedHttpException in RouteCollection.php line 218:. If I use an insert query with default values it will insert it successfully.
this is NewMember form
#extends('layouts.app')
#section('content')
<style>
body {
background-color: #fff0e6;
}
</style>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
<h1><u><font color="990000" ;>Register new restaurant</font></u></h1>
</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="/restaurantmenus/">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="name" class="col-md-4 control-label">Restaurant name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name"
value="{{ old('name') }}">
</div>
</div>
<div class="form-group">
<label for="address" class="col-md-4 control-label">Address</label>
<div class="col-md-6">
<label for="name" class="col-md-4 control-label">City</label>
<select name="city" style="width: 150px" id="city" class="form-control">
<option value="Damascus">Damascus</option>
</select>
<br>
<label for="name" class="col-md-4 control-label">Region</label>
<select name="region" style="width: 150px" id="region" class="form-control">
<option value="111">111</option>
<option value="222">222</option>
</select>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Telephone</label>
<div class="col-md-6">
<input id="Telephone" type="text" class="form-control" name="Telephone"
value="{{ old('Telephone') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">About your restaurant</label>
<div class="col-md-6">
<textarea id="description" rows="4" cols="50" name="description"
value="{{ old('description') }}"
placeholder="Enter text here..." class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Email</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email"
value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Username</label>
<div class="col-md-6">
<input id="username" type="text" class="form-control" name="username"
value="{{ old('username') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password"
value="{{ old('password') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Confirm password</label>
<div class="col-md-6">
<input id="password2" type="password" class="form-control" name="password2"
value="{{ old('password2') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Kitchen</label>
<div class="col-md-6">
<select name="kitchen" id="kitchen" class="form-control">
<option value="111">111</option>
<option value="222">222</option>
</select>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Working time</label>
<div class="col-md-6">
<label for="name" class="col-md-4 control-label">Open</label>
<input id="open" style="width: 150px" type="time" class="form-control" name="open"
value="{{ old('open') }}">
<br>
<label for="name" class="col-md-4 control-label">Close</label>
<input id="close" style="width: 150px" type="time" class="form-control" name="close"
value="{{ old('close') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Delivery</label>
<label for="name">Yes</label>
<input id="delivery" type="checkbox" style="float: left;" name="delivery"
value="{{ old('delivery') }}">
<input id="price" style="width: 150px" style="float: left;" placeholder="Delivery price"
type="text" name="price" value="{{ old('price') }}">
</div>
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary"
style="background:#990000; border-color:#990000" ;>
<i class="fa fa-btn fa-user"></i> Register
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<br>
<br>
<footer>
#extends('layouts.footer')
</footer>
#endsection
this is the models
restaurant model it has one relationship with the addresses table (the restaurant has many addresses)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class restaurant extends Model
{
//
protected $fillable=['name','telephone' ,'description','delivery','DeliveryPrice','ownerName','ownerPhone', 'kitchen','open','close'];
public function addresses(){
return $this->hasMany('App/address');
}
}
?>
user model
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';//add
protected $fillable = [
'name', 'username','email', 'password','phone',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function restaurant(){
return $this->hasMany('App/restaurant');
}
}
}
addresses model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class address extends Model
{
//
protected $fillable=[
'city','region'
];
}
the controller
{
namespace App\Http\Controllers;
use App\address;
use App\restaurant;
use App\User;
use Illuminate\Http\Request;
use App\restaurant as restaurantAlias;
use App\Http\Requests;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use phpDocumentor\Reflection\DocBlock\Tags\Uses;
class restaurantController extends Controller
{
//
public function index()
{
$use=User::all();
$res=restaurant::all();
$add=address::all();
return view('NewMember',compact('use','res','add'));
}
public function create()
{
// $restaurant=restaurant::all();
// return view('restaurant.NewMember',compact($restaurant));
return view('NewMember');
}
/**
* #param $id
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function show()
{
// $restaurant1= restaurant::find($id);
// return view('restaurantmenus/',$restaurant1);
return view('restaurantmenus');
}
public function store(Request $request)
{
// taking the restaurant user information
$restaurantUser = new User();
$restaurantUser->email = $request->email;
$restaurantUser->username = $request->username;
$restaurantUser->type = 'restaurant';
$restaurantUser->password = Hash::make($request->password);
$restaurantUser->save();
//taking the restaurant information
$object = new restaurant();
$object->name = $request->name;
$object->telephone = $request->Telephone;
$object->description = $request->description;
$object->delivery = $request->delivery;
$object->DeliveryPrice = $request->DeliveryPrice;
$object->kitchen = $request->kitchen;
$object->open = $request->open;
$object->close = $request->close;
$object->user_id = $restaurantUser->id;
$object->$restaurantUser->save();
// dd($object->IDrestaurant);
// taking the restaurant address
$addr = new address();
$addr->city = $request->city;
$addr->region = $request->region;
$addr->restaurant_id = $object->id;
$addr->$object->$restaurantUser->save();
$idr = $object->IDrestaurant;
return redirect('/restaurantmenus/' . $idr);
}
}
}
the route I think the problem in the post route .csrf_token() is not allowing the post route to send the data to database. I'd tried to add the routes to $except in VerifyCsrfToken class but it did not work
Route::post('/NewMember','restaurantController#store');
Route::get('/NewMember','restaurantController#create');
Route::get('/restaurantmenus','restaurantController#show');

Related

Firebase Realtime database update

Hello guys my firebase real-time database update function is updating all the data with new data, I'm attaching the image of the database before the update
And after the update all the fields of A and B are changed into C, the source code is available below :
Frontend:
<form onsubmit="return false">
<input type="hidden" id="hiddenId">
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Course Code</label>
<input type="text" class="form-control uname-box" id="popupCourseCode" aria-describedby="emailHelp" placeholder="Course Code">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Course Title</label>
<input type="text" class="form-control uname-box" id="popupCourseTitle" aria-describedby="emailHelp" placeholder="Course Title">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Subject</label>
<input type="text" class="form-control uname-box" id="popupSubject" aria-describedby="emailHelp" placeholder="Subject">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Credits</label>
<input type="number" class="form-control uname-box" id="popupCredits" aria-describedby="emailHelp" placeholder="Credits">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Grades</label>
<input type="text" class="form-control uname-box" id="popupGrades" aria-describedby="emailHelp" placeholder="Grades">
</div>
</div>
</form>
Function:
function update() {
firebase.database().ref('academics').orderByKey().once('value', snap => {
snap.forEach((data) => {
var popupCourseCode = document.getElementById('popupCourseCode');
var popupCourseTitle = document.getElementById('popupCourseTitle');
var popupSubject = document.getElementById('popupSubject');
var popupCredits = document.getElementById('popupCredits');
var popupGrades = document.getElementById('popupGrades');
var updates = {
courseCode: popupCourseCode.value,
courseTitle: popupCourseTitle.value,
subject: popupSubject.value,
credits: popupCredits.value,
grade: popupGrades.value,
}
firebase.database().ref('academics/' + data.key).update(updates)
// alert('updated')
console.log(`Update FunctionKey!!!!!!!!!!!! >>>>>>>>> ${data.key}`)
})
// console.log(`Remove FunctionKey!!!!!!!!!!!! >>>>>>>>> ${data.key}`)
})
}
Please provide me a solution. Thanks in anticipation

Getting an error trying to update user profile in laravel

am working on a laravel project and I am working on a user update profile, I am getting an error when updating and I can't figure out the solution.
below is the error I am getting
Target class [App\Http\Controllers\UpdateProfileRequest] does not exist.
below is my route in web.php
Route::get('users/edit', 'UserController#edit')->name('users.edit');
Route::put('users/update', 'UserController#update')->name('users.update');
below is UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
//
public function edit()
{
return view('users.edit')->with('user', auth()->user());
}
public function update(UpdateProfileRequest $request)
{
$user = auth()->user();
$user->update([
'name' => $request->name,
'organization' => $request->organization,
'email' => $request->email,
'password' => $request->password
]);
return redirect()->back;
}
}
below is my UpdateProfileRequest
<?php
namespace App\Http\Requests\User;
use Illuminate\Foundation\Http\FormRequest;
class UpdateProfileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name'=>'required',
'organization'=>'required',
'email'=>'required',
'password'=>'required'
];
}
}
below is the edit.blade.php view
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<p class="card-text"><img src="{{ asset('img/logo1.jpg') }}" width="60" height="50" class="mx-auto d-block" alt="logo1"></p>
<hr style="width:50%", size="2", color=3490dc>
<div class="card">
<div style="text-align: center; background-color:#3490dc; color:white;" class="card-header"><i class="fa fa-user-circle" aria-hidden="true"></i> {{ __('My Profile') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('users.update') }}">
#csrf
#method('PUT')
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right"><i class="fa fa-user" style="color:#3490dc;"></i> {{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ $user->name }}" required autocomplete="name" autofocus>
</div>
</div>
<div class="form-group row">
<label for="organization" class="col-md-4 col-form-label text-md-right"><i class="fa fa-building-o" style="color:#3490dc;"></i> {{ __('Organization') }}</label>
<div class="col-md-6">
<input id="organization" type="text" class="form-control #error('organization') is-invalid #enderror" name="organization" value="{{ $user->organization }}" required autocomplete="organization" autofocus>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right"><i class="fa fa-envelope" style="color:#3490dc;"></i> {{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ $user->name }}" required autocomplete="email">
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right"><i class="fa fa-key" style="color:#3490dc;"></i> {{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right"><i class="fa fa-key" style="color:#3490dc;"></i> {{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Update') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<br/>
#include('footer')
#endsection
below is the link to the view in app.blade.php
<a class="dropdown-item" href="{{ route('users.edit') }}"
>
{{ __('My Profile') }}
</a>
<form id="edit-form" action="{{ route('users.edit') }}" style="display: none;">
#csrf
</form>
I will appreciate any help thanks in advance
You're missing a using.
Add use UpdateProfileRequest; at the top.
(this might not be the correct path, try hovering UpdateProfileRequest and looking for an Import class button)
You must use it on top of UserController class:
use App\Http\Requests\UpdateProfileRequest;

Ajax PHP Form Submission with Image and Text

I'm writing an app that allows my wife to add her recipes to a database i have set up. I have a form set up with both text and a file input for an image. It works fine and she can upload text and image to the database. Now, I'm trying to add a feature so that she can edit it. It's the same exact form only the data goes to a different PHP file for processing. When she clicks the "Edit" button it populates all the text inputs with the data pulled from the server and she can edit. She can also add a new photo if she wishes. Despite the fact that it's the same form, it will not upload the image. The text uploads fine, but the $_POST['recipeImage'] is always empty when I look at the object being sent to the server (recipeImage: "");
I am baffled and cannot see why this isn't working. Here is the code:
HTML FORM (IMAGE UPLOAD IS A BOTTOM):
<div id="editRecipeModal">
<div class="col-md-8">
<div class="card">
<form action="../PHP/modify_recipe.php" method="POST" role="form" class="form-horizontal" enctype="multipart/form-data" id="editRecipeForm" name="editRecipeForm">
<input class="form-control" type="hidden" value="" id="creatorIdEdit" name="creatorId">
<input class="form-control" type="hidden" value="" id="recipeIdEdit" name="recipeId" value="">
<div class="card-header card-header-text" data-background-color="purple">
<h4 class="card-title"><i class="far fa-edit"></i> Edit Recipe</h4>
</div>
<div class="card-content"
<div class="row">
<label class="col-sm-2 label-on-left">Recipe Name</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<input class="form-control" type="text" name="name" maxlength="150" id="editRecipeName" required>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Prep Time</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<input class="form-control" type="number" name="prepTime" id="editPrepTime" required>
<span class="help-block">Numbers Only. In minutes... ie: 120 Minutes</span>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Servings</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<input class="form-control" type="number" name="servings" id="editServings" required>
<span class="help-block">Numbers Only...</span>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Calories</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<input class="form-control" type="number" name="calories" id="editCalories" required>
<span class="help-block">Numbers Only</span>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Brief Description</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<textarea class="form-control" name="description" id="editBriefDescription" rows="5" required></textarea>
</div>
</div>
</div>
<hr>
<div class="row">
<label class="col-sm-2 label-on-left">Ingredients</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<textarea class="form-control" name="ingredients" id="editPasteIngredientsShow" rows="20" required></textarea>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Recipe Steps</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<textarea class="form-control" name="directions" id="editPasteStepsShow" rows="20" required></textarea>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 label-on-left">Search Tags</label>
<div class="col-sm-9">
<div class="form-group label-floating is-empty">
<label class="control-label"></label>
<input class="form-control" type="text" id="editTags" name="tags" required>
</div>
</div>
</div><br> <br> <br> <br>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-3">
<select class="selectpicker" data-style="btn btn-primary btn-round" title="vegOrVegan" data-size="7" id="vegOrVeganEditSelect">
<option disabled selected>Dietary Restrictions</option>
<option value="" name="">None</option>
<option value="T" name="T">Vegetarian</option>
<option value="VG" name="VG">Vegan</option>
</select>
<input type="hidden" id="vegOrVeganEdit" name="vegOrVegan">
</div>
<div class="col-lg-4 col-md-6 col-sm-3">
<select class="selectpicker" id="suggestedPairingEditSelect" data-style="btn btn-primary btn-round" title="Suggested Pairing" data-size="7">
<option disabled selected>Suggested Pairing</option>
<option value="" name="">None</option>
<option value="B" name="B">Beer</option>
<option value="WW" name="WW">White Wine</option>
<option value="RW" name="RW">Red Wine</option>
</select>
<input type="hidden" id="suggestedPairingEdit" name="suggestedPairing" value="">
</div>
<div class="col-lg-4 col-md-6 col-sm-3">
<select class="selectpicker" id="" data-style="btn btn-primary btn-round" title="Some Other Attributes" data-size="7">
<option disabled selected>Some Other Attributes</option>
<option value="" name="">None</option>
<option value="B" name="B">Beer</option>
<option value="WW" name="WW">White Wine</option>
<option value="WW" name="WW">Red Wine</option>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" style="text-align: center;">
</div>
</div>
<div class="row" style="width: 80%; margin: 0 auto;">
<div class="col-sm-4"></div>
<div class="col-sm-4" style="text-align: center;">
<div class="fileinput fileinput-new text-center" data-provides="fileinput">
<div class="fileinput-new thumbnail">
<img src="../assets/img/placeholder.jpg" alt="...">
</div>
<div class="fileinput-preview fileinput-exists thumbnail"></div>
<div>
<span class="btn btn-rose btn-round btn-file">
<span class="fileinput-new">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="file" name="recipeImage" id="recipeImageEdit" />
</span>
<i class="fa fa-times"></i> Remove
</div>
</div>
</div>
<div class="col-sm-4"></div>
</div>
<br><br>
<div class="row">
<div class="col-sm-2"></div>
<div class="col-sm-4" style=" text-align: center; margin: 0; padding: 0;"><button class="btn btn-primary btn-lg modRecButton" type="submit" id="submitRecipe">Submit Changes</button></div>
<div class="col-sm-4 closePanel" style="text-align: center; margin: 0; padding: 0;" id="closePanel"><button type="button" class="btn btn-default btn-lg">Cancel Changes</button>
</div>
<div class="col-sm-2"></div>
</div>
</div>
</form>
</div>
</div>
</div>
AJAX CODE
$(document).ready(function(e) {
$("#editRecipeForm").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "../PHP/modify_recipe.php",
type: "POST",
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(response) {
let parsedResponse = JSON.parse(response);
let newObject = parsedResponse[0]
if (parsedResponse == 'notModified') {
showErrorModal();
}else{
reBuildAfterObjectChange(newObject.recipeId, parsedResponse);
}
},
error: function() {
showErrorModal();
}
});
}));
});
PHP CODE
<?php
include 'db_operations.php';
if(isset($_POST['name'])&& isset($_POST['description']) && isset($_POST['ingredients'])&& isset($_POST['directions']) && isset($_POST['suggestedPairing']) && isset($_POST['prepTime']) && isset($_POST['servings']) && isset($_POST['calories']) && isset($_POST['vegOrVegan']) && isset($_POST['recipeId']) && isset($_POST['creatorId']))
{
$result = '';
$name = $_POST['name'];
$description = $_POST['description'];
$ingredients = $_POST['ingredients'];
$ingredients = str_replace(';', '-', $ingredients);
$ingredients = str_replace('\n', ';', $ingredients);
$directions = $_POST['directions'];
$directions = str_replace(';', '-', $directions);
$directions = str_replace('\n', ';', $directions);
$suggestedPairing = $_POST['suggestedPairing'];
$prepTime = $_POST['prepTime'];
$servings = $_POST['servings'];
$calories = $_POST['calories'];
$vegOrVegan = $_POST['vegOrVegan'];
$recipeId = $_POST['recipeId'];
$creatorId = $_POST['creatorId'];
$tags = $_POST['tags'];
$time=time();
$lastModified = (date("Y-m-d H:i:s", $time));
modifyRecipe_recipes($name, $description, $ingredients, $directions, $suggestedPairing, $prepTime, $servings, $calories, $vegOrVegan, $lastModified, $creatorId, $recipeId, $tags);
}
if(isset($_POST['recipeImage'])){
$size = $_FILES['recipeImage']['size'];
if($size > 0){
$tmp_dir = $_FILES["recipeImage"]["tmp_name"];
$tmpImg = $_FILES['recipeImage']['name'];
$ext = strtolower(pathinfo($tmpImg, PATHINFO_EXTENSION));
$recipeImage = rand(10000, 10000000).".".$ext;
move_uploaded_file($tmp_dir, "../userRecipeImages/".$recipeImage);
$sql = 'UPDATE recipes SET recipeImage = :recipeImage WHERE creatorId = :creatorId AND recipeId= :recipeId';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':creatorId', $creatorId, PDO::PARAM_STR);
$stmt->bindParam(':recipeImage', $recipeImage, PDO::PARAM_STR);
$stmt->bindParam(':recipeId', $recipeId, PDO::PARAM_STR);
$stmt->execute();
}
}
$modifiedRecipeDate = getLastModified_recipes($lastModified, $creatorId);
if ($modifiedRecipeDate === $lastModified) {
$newObject = getSingleRecipeById_recipes($recipeId, $creatorId);
echo json_encode($newObject);
}
else {
$result = "notModified";
echo json_encode($result);
}
?>
You obviously forgot to change $_POST['recipeImage'] to $_FILES['recipeImage']
Files are contained in the $_FILES global variable not $_POST
Change this
if(isset($_POST['recipeImage'])){
to
if(isset($_FILES['recipeImage'])){

check the angular form is valid in the controller

I am new to angularjs. I have searched for this problem but I found some solutions but none of them were working for me. So, I have a form which is
HTML
<div class=" row col-xs-12 col-md-12">
<div id="candidateInfoCorners" ng-show="showcandidateInfo">
<div class="col-xs-12 col-md-12 info-header">
<h>Candidate Information</h>
</div>
<form class="form-horizontal" role="form" name="Candidateform">
<div class="row">
<div class="col-md-6">
<label class="control-label col-sm-4 candidateNpInDaysLabelPosition" for="noticePeriod">Notice Period In Days :</label>
<div class="col-sm-4">
<input type="number" min="0" ng-model="candidate.noticePeriod" class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateNpInDaysInputPosition"
id="noticePeriod" placeholder="Noticeperiod" autocomplete="off" required="">
</div>
</div>
<div class="col-md-6">
<label class="control-label col-sm-4 candidateCTCLabelPosition" for="ctc">CCTC In Lakhs :</label>
<div class="col-sm-4">
<input type="number" min="0" decimal-places="" ng-model="candidate.ctc" class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition"
id="ctc" placeholder="CCTC" autocomplete="off" required="">
</div>
</div>
<div class="col-md-6">
<label class="control-label col-sm-4 candidateECTCLabelPosition" for="ectc">ECTC In Lakhs :</label>
<div class="col-sm-4">
<input type="number" min="0" decimal-places="" ng-model="candidate.ectc" class="form-control ng-pristine ng-valid-min ng-invalid ng-invalid-required ng-touched candidateECTCInputPosition"
id="ectc" placeholder="ECTC" autocomplete="off" required="">
</div>
</div>
<div class="col-md-6">
<label class="col-sm-4 control-label candidateCommunicatioLabelPosition" for="communication">Communication :</label>
<div class="col-sm-4">
<select class="selectpicker form-control ng-pristine ng-untouched ng-invalid ng-invalid-required candidateCommunicatioSelectPosition"
ng-model="candidate.communication" name="communication" id="communication" required="">
<option value="" selected="">Communication</option>
<option value="Good">Good</option>
<option value="Average">Average</option>
<option value="Poor">Poor</option>
</select>
</div>
</div>
</div>
</form>
</div>
</div>
Now, I have a controller where I am using this form like -
$scope.candidate = {
noticePeriod: '',
ctc: '',
ectc: '',
communication: ''
};
And using it like - $scope.candidate.noticePeriod while getting the value.
Now I don't have any submit for the form, this is going to happen on some another action .
$scope.updateDocument = function() {
//Here I want to check the Form is valid or not
//I tried
//$scope.candidateform.$valid but I am getting an error like
Cannot read property '$valid' of undefined
}
Both functions are in the same controller
Can any one help me with this?
You need to use ng-form
This is how I do it.
I make a parent property like
$scope.myforms = {
Candidateform: {}
};
//HTML will be
<ng-form name="myForms.CandidateForm">...</ng-form>
//TO VALIDATE I DO IT LIKE THIS
$scope.myForms.CandidateForm.$submitted = true // This will run the validators as well, this means form has been submitted.
//OR TO SUBMIT IT PROGRAMATICALLY
$scope.myForms.CandidateForm.$valid
You have some errors in your code, You name your form "Candidateform" and then in controller you are only using $scope.candidate. Change that to $scope.CandidateForm
function Controller($scope) {
$scope.master = {};
$scope.user = {
name: "",
email: ""
};
$scope.update = function(user) {
//$scope.master = angular.copy(user);
console.log($scope.master)
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html ng-app>
<div ng-app="demo1">
<div ng-controller="Controller">
<ng-form novalidate class="simple-form" name="master">
<legend>User Profile</legend>
<div class="control-group-error">
<label class="control-label" for="input-error">Name</label>
<div class="controls">
<input type="text" name="username" ng-model="user.name">
<span class="help-inline">Please correct the error</span>
</div>
<label>E-mail</label>
<input type="email" name="email" ng-model="user.email">
</div>
</ng-form>
<button class="btn btn-primary" ng-click="update(user)">Save</button>
<br />
<pre>{{master.$valid}}</pre>
</div>
</div>
</html>

Simplify angular controller posting to Firebase using AngularFire

I'm new to angular but picking it up quickly. I have this controller that works, based on demo code ive hacked together, but there has to be an easier cleaner way to get all the fields and post so if i want to add a new field i dont need to keep adding it in the various locations.
Heres the controller:
'use strict';
angular.module('goskirmishApp').controller('addEvent', function ($scope, fbutil, $timeout) {
// synchronize a read-only, synchronized array of messages, limit to most recent 10
$scope.messages = fbutil.syncArray('messages', {limit: 10});
// display any errors
$scope.messages.$loaded().catch(alert);
// provide a method for adding a message
$scope.addMessage = function(newEventName,newEventType,newStartDate,newStartTime,newEndDate,newEndTime,newEventDescription,newAddress,newPostcode,newTicketInformation,newBookLink) {
if( newEventName ) {
// push a message to the end of the array
$scope.messages.$add({
eventName: newEventName,
eventType: newEventType,
startDate: newStartDate,
startTime: newStartTime,
endDate: newEndDate,
endTime: newEndTime,
eventDescription: newEventDescription,
address: newAddress,
postcode: newPostcode,
ticketInformation: newTicketInformation,
bookLink: newBookLink
})
// display any errors
.catch(alert);
}
};
function alert(msg) {
$scope.err = msg;
$timeout(function() {
$scope.err = null;
}, 5000);
}
});
And the view:
<h2>Add Event</h2>
<p class="alert alert-danger" ng-show="err">{{err}}</p>
<form role="form">
<div class="form-group">
<label>Event Name</label>
<input class="form-control" type="text" ng-model="newEventName">
</div>
<div class="form-group">
<label>Event Type</label>
<select class="form-control" ng-model="newEventType">
<option value="" disabled selected>Game type</option>
<option value="milsim">Skirmish</option>
<option value="milsim">Special Event</option>
<option value="milsim">Weekender</option>
<option value="milsim">Milsim</option>
</select>
</div>
<div class="form-group">
<label>Start Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="newStartDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="newStartTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>End Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="newEndDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="newEndTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>Event Description</label>
<textarea class="form-control" rows="4" ng-model="newEventDescription"></textarea>
</div>
<div class="form-group">
<label>Address</label>
<input class="form-control" ng-model="newAddress">
</div>
<div class="form-group">
<label>Postcode</label>
<input class="form-control" ng-model="newPostcode">
</div>
<div class="form-group">
<label>Ticket Information</label>
<textarea class="form-control" rows="4" ng-model="newTicketInformation"></textarea>
</div>
<div class="form-group">
<label>Booking Link</label>
<input class="form-control" ng-model="newBookLink">
</div>
<button type="submit" class="btn btn-danger" ng-click="addMessage(newEventName,newEventType,newStartDate,newStartTime,newEndDate,newEndTime,newEventDescription,newAddress,newPostcode,newTicketInformation,newBookLink,newLat,newLong,newApproved);newEventName = null;newEventType = null;newStartDate = null;newStartTime = null;newEndDate = null;newEndTime = null;newEventDescription = null;newAddress = null;newPostcode = null;newTicketInformation = null;newBookLink = null;">Add Event</button>
</form>
Help is greatly appreciated!
Define all your input in a object that you will be directly send send to firebase
For example init in your controller this :
$scope.form = {};
After in your template just define your input as 'form attributes'.
<h2>Add Event</h2>
<p class="alert alert-danger" ng-show="err">{{err}}</p>
<form role="form">
<div class="form-group">
<label>Event Name</label>
<input class="form-control" type="text" ng-model="form.eventName">
</div>
<div class="form-group">
<label>Event Type</label>
<select class="form-control" ng-model="form.eventType">
<option value="" disabled selected>Game type</option>
<option value="milsim">Skirmish</option>
<option value="milsim">Special Event</option>
<option value="milsim">Weekender</option>
<option value="milsim">Milsim</option>
</select>
</div>
<div class="form-group">
<label>Start Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="form.startDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="form.startTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>End Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="form.endDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="form.endTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>Event Description</label>
<textarea class="form-control" rows="4" ng-model="form.eventDescription"></textarea>
</div>
<div class="form-group">
<label>Address</label>
<input class="form-control" ng-model="form.address">
</div>
<div class="form-group">
<label>Postcode</label>
<input class="form-control" ng-model="form.postcode">
</div>
<div class="form-group">
<label>Ticket Information</label>
<textarea class="form-control" rows="4" ng-model="form.ticketInformation"></textarea>
</div>
<div class="form-group">
<label>Booking Link</label>
<input class="form-control" ng-model="form.bookLink">
</div>
<button type="submit" class="btn btn-danger" ng-click="addMessage()">Add Event</button>
</form>
and directly in your addMessage function
$scope.addMessage = function() {
if( $scope.form.eventName ) {
// push a message to the end of the array
$scope.messages.$add($scope.form)
// display any errors
.catch(alert);
//Reset your form
$scope.form = {};
}
};

Categories

Resources