Validation won't work using blade template - javascript

I'm trying to validate my form but when I hit the submit button it always refresh the page and didn't validate anything. So the first process start at the
accountDashboard.blade.php
#section ('content')
<div class = "row">
<div class = "col-xs-12 col-md-8">
<div class = "panel panel-default">
<div class = "panel-heading">
<h2>Account Dashboard</h2>
<hr>
</div>
<div class = "panel-body">
<button type = "button" class = "btn btn-info" id = "register">Register Employee</button>
<button type = "button" class = "btn btn-info" id = "searchEmployee">Search Employee</button>
<div class = "row">
<br>
<div class="col-md-10">
<div class = "panel panel-default">
<div class = "panel-body" style = "height: 500px" id = "accountBottomContainer">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
accountDashboard.blade.php (routes)
Route::get('/accountDashboard',
[
'uses' => '\App\Http\Controllers\AccountController#getAccountDashboard',
'as' => 'account.accountDashboard',
]);
As you can see above I have two button one for the register and searchRegister. For instance I hit #register button the blade template will append it on my second panel-body with the id of #accountBottomContainer. Script below of my javascript.
<script>
$(document).on("click", "#register", function ()
{
$.get("accountRegister", function (data)
{
$("#accountBottomContainer").empty();
$("#accountBottomContainer").append(data);
});
});
</script>
accountRegister.blade.php
This is my blade template that I will append from panel-body which works fine I'm just having problem with the validation.
<form class = "form-vertical" role = "form" method = "post" action = "{{ route ('account.accountRegister') }}">
<div class = "form-group {{ $errors->has('email') ? ' has-error' : '' }}">
<label for = "email" class = "control-label">Email Address</label>
<input type = "text" name = "email" class = "form-control" value = "{{ Request::old('email') ?: '' }}">
#if ($errors->has('email'))
<span class = "help-block">{{ $errors->first('email') }}</span>
#endif
</div>
<div class = "form-group {{ $errors->has('username') ? ' has-error' : '' }}">
<label for = "username" class = "control-label">Username</label>
<input type = "text" name = "username" class = "form-control" value = "{{ Request::old('username') ?: '' }}">
#if ($errors->has('username'))
<span class = "help-block">{{ $errors->first('username') }}</span>
#endif
</div>
<div class = "form-group {{ $errors->has('password') ? ' has-error' : '' }}">
<label for = "password" class = "control-label">Password</label>
<input type = "password" name = "password" class = "form-control">
#if ($errors->has('password'))
<span class = "help-block">{{ $errors->first('password') }}</span>
#endif
</div>
<div class = "form-group">
<button type = "submit" class = "btn btn-default">Sign Up</button>
</div>
<input type = "hidden" name = "_token" value = "{{ Session::token() }}">
</form>
Controller
public function postRegister(Request $request)
{
//VALIDATION
$this->validate($request, [
//This will be unique in users table
'email' => 'required|unique:users|email|max:255',
'username' => 'required|unique:users|alpha_dash|max:20',
'password' => 'required|min:6',
]);
User::create
([
'username' => $request->input('username'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
]);
return redirect()->route('account.accountRegister');
}
routes for accountRegister.blade.php
Route::get('/accountRegister',
[
'uses' => '\App\Http\Controllers\AccountController#getRegister',
'as' => 'account.accountRegister',
]);
Route::post('/accountRegister',
[
'uses' => '\App\Http\Controllers\AccountController#postRegister',
]);

<div class="form-group #if($errors->has('username')) has-error #endif">
<label for="username" class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="username" value="{{ Request::old('username') ?: '' }}" readonly="readonly" />
#if($errors->has('username'))
<span class="help-block">{{ $errors->first('username') }}</span>
#endif
</div>
</div>

Related

Dynamically save the Django form

I am trying not to use formset in my form. Instead of that, I'm trying to create the form dynamically and save all forms data in the DB.
I can create a dynamic form, but whenever I create multiple forms in "create order", it always saves the last forms data. For example, once I create 3 forms, and after saving the form, the table shows me only 3rd form data, which means it does not save all data together.
views.py
def create_order(request):
from django import forms
form = OrderForm()
if request.method == 'POST':
forms = OrderForm(request.POST)
if forms.is_valid():
po_id = forms.cleaned_data['po_id']
supplier = forms.cleaned_data['supplier']
product = forms.cleaned_data['product']
part = forms.cleaned_data['part']
order = Order.objects.create(
po_id=po_id,
supplier=supplier,
product=product,
part=part,
)
forms.save()
return redirect('order-list')
context = {
'form': form
}
return render(request, 'store/addOrder.html', context)
forms.py
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['supplier', 'product', 'part','po_id']
widgets = {
'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}),
'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}),
'part': forms.Select(attrs={'class': 'form-control', 'id': 'part'}),
}
HTML
<form action="#" method="post" id="form-container" novalidate="novalidate">
{% csrf_token %}
<div class="form">
<div class="form-group">
<label for="po_id" class="control-label mb-1">ID</label>
{{ form.po_id }}
</div>
<div class="form-group">
<label for="supplier" class="control-label mb-1">Supplier</label>
{{ form.supplier }}
</div>
<div class="form-group">
<label for="product" class="control-label mb-1">Product</label>
{{ form.product }}
</div>
<div class="form-group">
<label for="part" class="control-label mb-1">Part Name</label>
{{ form.part }}
</div>
</div>
<button id="add-form" type="button">Add Another Order</button>
<div>
<button id="payment-button" type="submit" class="btn btn-lg btn-success btn-block">
<span id="payment-button-amount">Save</span>
</button>
</div>
</form>
<script>
let poForm = document.querySelectorAll(".form")
let container = document.querySelector("#form-container")
let addButton = document.querySelector("#add-form")
let totalForms = document.querySelector("#id_form-TOTAL_FORMS")
let formNum = poForm.length-1
addButton.addEventListener('click', addForm)
function addForm(e){
e.preventDefault()
let newForm = poForm[0].cloneNode(true)
let formRegex = RegExp(`form-(\\d){1}-`,'g')
formNum++
newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`)
container.insertBefore(newForm, addButton)
totalForms.setAttribute('value', `${formNum+1}`)
}
</script>
What causes this problem? How can I fix it?

Laravel request()->all() doesn't get all inputs

Sending data via POST form. Why doesn't the controller see all of the values? I've been playing around with the validation, so even setting those to 'required' doesn't change anything...
Form snippet:
<form action="{{ Protocol::home() }}/offers/make" method="POST" id="sendOffer">
<div class="modal-body">
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Price -->
<div class="form-group" style="display:none;">
<label>{{ Lang::get('ads/show.lang_your_price') }}</label>
<input type="text" id="price_id" name="price" value="0">
<span class="help-block">{{ Lang::get('ads/show.lang_the_amount_required') }} <b>{{ Helper::getPriceFormat($ad->price, $ad->currency) }}</b></span>
</div>
<!-- location -->
<div class="form-group">
<label>location label</label>
<input type="text" placeholder="Andover MA" id="location_id" class="form-control" name="location_name">
</div>
<!-- Email Address -->
<div class="form-group">
<label>email label</label>
<input type="email" required="" placeholder="email" id="email_name" class="form-control" name="email_name">
</div>
<!-- Phone -->
<div class="form-group">
<label>phone label</label>
<input type="text" maxlength="12" placeholder="555-867-5309" id="friendNumber" class="form-control" name="phone_name">
</div>
<!--Time section-->
<div class="form-group">
<label>The time</label>
<input type="time" id="time_id" name="time_name"
min="9:00" max="18:00" required>
</div>
<!-- Post ID -->
<div class="form-group">
<label>{{ Lang::get('ads/show.lang_post_id') }} (for reference)</label>
<input type="text" readonly="" placeholder="{{ Lang::get('ads/show.lang_post_id') }}" id="postID" value="{{ $ad->ad_id }}" class="form-control" name="ad_id">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">{{ Lang::get('ads/show.lang_send_offer') }}</button>
</div>
</form>
Controller:
/**
* Make New Offer
*/
public function make(Request $request)
{
// Check ajax request
if ($request->ajax()) {
$rules = array(
'location_name' => '',
'email_name' => '',
'phone_name' => '',
'time_name' => '',
'ad_id' => 'required'
);
//run rules
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
// error
$response = array(
'status' => 'error',
'msg' => __(print_r($request->all())),
);
return Response::json($response);
}else{
// Get Inputs
$price = $request->get('price');
$location_name = $request->input('location_name');
$email_name = $request->input('email_name');
$phone_name = $request->input('phone_name');
$time_name = $request->input('time_name');
$ad_id = $request->input('ad_id');
$input = $request->all();
//let's figure it out:
dd($input);
// Success test
$response = array(
'status' => 'success',
'msg' => __('return/success.lang_offer_submitted'),
);
return Response::json($response);
Output in console (only showing price and ad_id for some reason):
array:2 [
"price" => "0"
"ad_id" => "1988726232"
]
Route:
// Make an Offer
Route::post('offers/make', 'Ads\OffersController#make');
The error was a result of me forgetting to include these fields in the ajax request smh
var _root = $('#root').attr('data-root');
var offerPrice = document.getElementById('offerPrice').value;
var postID = document.getElementById('postID').value;
var location_name = document.getElementById('location_name').value;
var email_name = document.getElementById('email_name').value;
var phone_name = document.getElementById('phone_name').value;
var time_name = document.getElementById('time_name').value;
$.ajax({
type: "POST",
url: _root + '/offers/make',
data: {
price: offerPrice,
ad_id: postID,
location_name: location_name,
email_name: email_name,
phone_name: phone_name,
time_name: time_name
},

Jasmine/Karma - Unit test for button enable in Angular 2

I am not much aware of Jasmine/Karma unit testing, Here i am testing reactive form button. If two fields having input my button will enable, this is normal functionality of my form. while unit testing for this functionality i am getting error like "Failed: Cannot read property 'nativeElement' of null". If any one knows please help me.
Here is my form.
<div class="grid" >
<div [formGroup]="orderUnitForm" >
<div class="form-group" [hidden]="searhPanel">
<div class="layer-types__layer-1" >
<div class="bx--row">
<div class="bx--col-md-12 bx--col-xs-12">
<select id="select-menu" class="bx--text-input" formControlName="ruleSelection" name="ruleSelection" (change)="onChange($event.target.value)" >
<option selected>{{defaultSearch}}</option>
<option *ngFor="let rule of rules" [value]="rule.id" >{{rule.name}}</option>
</select>
</div>
</div>
<div class="bx--row">
<!-- <div class="form-group" [ngClass]="{'has-error': displayMessage.orderingUnit }"> -->
<div class="bx--col-md-2 bx--col-xs-12" align="right">
<label for="orderingUnit" class="bx--label">Ordering Unit</label>
</div>
<div class="bx--col-md-10 bx--col-xs-12">
<input type="text" id="orderingUnit" placeholder="Ordering Unit" class="bx--text-input"
formControlName="orderingUnit" name="orderingUnit"
[attr.title]="orderingUnitTip" [attr.data-invalid]="displayMessage.orderingUnit ? '' : null">
<div class="bx--form-requirement" *ngIf="displayMessage.orderingUnit" >{{ displayMessage.orderingUnit }} </div>
</div>
</div>
<div class="bx--row">
<div class="bx--col-md-2 bx--col-xs-12" align="right">
<label for="orderReferenceNumber" class="bx--label">Order Reference Number</label>
</div>
<div class="bx--col-md-10 bx--col-xs-12">
<input type="text" class=" bx--text-input" id="orderReferenceNumber" placeholder="Order Reference Number"
formControlName="orderReferenceNumber" name="orderReferenceNumber"
[attr.title]="orderReferenceNumberTip" [attr.data-invalid]="displayMessage.orderReferenceNumber ? '' : null">
<div class="bx--form-requirement" *ngIf="displayMessage.orderReferenceNumber" >{{ displayMessage.orderReferenceNumber }} </div>
</div>
</div>
<div class="bx--col-md-1 bx--col-xs-4" >
<!-- <carbon-button type="primary" (click)="onInclude()">Include</carbon-button> -->
<button class="bx--btn bx--btn--primary" type="button" id="inc" (click)="onInclude()" [disabled]="!valid || !orderUnitForm.valid">Include</button>
</div>
</div>
</div>
Here is my test cases:
describe('SearchPanelComponent', () => {
let component: SearchPanelComponent;
let fixture: ComponentFixture<SearchPanelComponent>;
let includeBtn: HTMLElement;
let orderingUnit: HTMLElement;
let orderReferenceNumber: HTMLElement;
let el: HTMLElement;
let overlayContainerElement: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule,CarbonDatepickerModule, CarbonIconModule, StoreModule.forRoot({})],
declarations: [ SearchPanelComponent, ModalComponent, UploadsearchcriteriaComponent, ],
providers: [Store,StoreModule,CustomerorderService, ApiConnectorService, HttpClient, HttpHandler,ModalService]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SearchPanelComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should check include is enabled after inputs combinations', async(() => {
includeBtn = fixture.debugElement.query(By.css('button')).nativeElement;
fixture.whenStable().then(() => {
var inputElement = <HTMLInputElement>document.getElementById('orderingUnit');
inputElement.value = 'abc';
inputElement.dispatchEvent(new Event('input'));
var inputElement1 = <HTMLInputElement>document.getElementById('orderReferenceNumber');
inputElement1.value = 'abcdef';
inputElement1.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(includeBtn.getAttribute('ng-reflect-enabled')).toBe('true', 'Include button enabled should now be true');
});
}));
});

Nodemailer script does not execute when called from the website

I'm trying to use Nodemailer to send emails by clicking submit on a web form. The test strings of the embedded script are being printed, but after that the script fails with this message in the console:
ReferenceError: require is not defined
What's interesting is that I receive emails from this script when I run it directly from the terminal, but when I try to trigger it from my web form, I get this error.
Almost everywhere I've looked people present a script such as the one directly below as being the only thing needed to send emails using Nodemailer. Neither the Nodemailer website nor W3Schools make reference to anything else. What am I missing?
Thank you for your time,
-Joel
<script>
const myForm = document.getElementById('myForm');
console.log("Testing!");
myForm.addEventListener("click", () => {
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'angleritemailer#gmail.com',
pass: 'hammertime80'
}
});
const mailOptions = {
from: 'angleritemailer#gmail.com',
to: 'joelnashjobs#yahoo.com',
subject: 'hey',
text : 'text',
html: '<p>Your html here</p>'
}
transporter.sendMail(mailOptions, function(err, info) {
if (err)
console.log(err)
else
console.log(info);
});
});
</script>
<form" class = "col-sm-6" action = "/" method = "POST" id = "myForm">
<div class = "row form-row form-group">
<div class = "col-sm-5">
<input type = "text" class = "form-control-plaintext full-width" id = "name" placeholder = "Your name here">
</div>
<div class = "col-sm-2">
</div>
<div class = "col-sm-5 widen-slightly">
<input type = "text" class = "form-control-plaintext full-width" id = "staticEmail" placeholder = "email#example.com">
</div>
</div>
<div class = "row form-row form-group">
<div class = "col-sm-12 widen-slightly">
<input type = "text" class = "form-control-plaintext full-width" id = "phone" placeholder = "Phone number with area code">
</div>
</div>
<div class = "row form-row form-group">
<div class = "col-sm-12 widen-slightly">
<input type = "text" class = "form-control-plaintext full-width" id = "subject" placeholder = "Subject">
</div>
</div>
<div class = "row form-row form-group">
<div class = "col-sm-12 widen-slightly">
<textarea rows = "6" class = "form-control-plaintext full-width" id = "Description" placeholder = "Description"></textarea>
</div>
</div>
<div class = "row form-row form-group">
<label class = "col-sm-3 col-form-label" >Any Photos</label>
<div class = "col-sm-7">
<input type = "file" class = "form-control-file full-width" id = "">
</div>
<div class = "cl-sm-2">
<button type="submit" class="btn btn-default" id = "submit">Submit</button>
</div>
</div>
</form>

Update multiple select2 field with laravel, ajax and angularJs

I have a multiple select2 Select field.
What I want is to add a new value to my select field. (after adding an entry to the database and bind this entry to the select field)
This is my code so far:
Blade template:
<div class="form-group {{ ($errors->first('projectTypes')) ? 'has-error' : '' }}">
<label for="projectTypes" class="col-md-2 control-label">{{ trans('project/project.fields.projectTypes') }}</label>
<div class="col-md-9">
{!! Form::select('projectTypes[]',
$projectTypes,
($project->projectTypes()->count() > 0) ? $project->projectTypes->lists('id')->toArray() : (isset($projectType)) ? $projectType->id : '',
['id' => 'projectTypes', 'class' => 'form-control', 'ng-model' => 'projectTypes', 'multiple' => 'multiple'])
!!}
<span id="helpBlock" class="help-block">{{ $errors->first('projectTypes') }}</span>
</div>
<div class="col-md-1">
<i class="fa fa-plus-square-o fa-2" data-toggle="modal" data-target="#addProjectType"></i>
</div>
The <i> tag toggles the modal. In the modal window I have an input field and a button (it works!):
<input ng-model="name" id="addProjectType" class="form-control" type="text" name="name" placeholder="Projekttyp">
<button type="button" class="btn btn-primary btn-embossed" ng-click="addProjectType(name)" data-dismiss="modal">Save changes</button>
So if I click on the button this will trigger a function in my angularJS code (this works!).
This is my angularJS Code:
$scope.projectTypes = [];
$scope.addProjectType = function(name) {
$http.post('/ajax/projecttype/addprojecttype', {
name: name
}).success(function(data, status, headers, config) {
$scope.projectTypes.push(data);
});
}
This do an ajax call to my laravel php function (this works!):
public function addProjectType(Request $request, Sentinel $sentinel) {
$name = $request->get('name');
$projectType = new ProjectType;
$projectType->name = $name;
$projectType->slug = $projectType->strSlug($name);
$this->created_by = $sentinel::getUser()->id;
$this->updated_by = $sentinel::getUser()->id;
$projectType->saveModel($request);
return Response::json($projectType, self::$OK);
}
But although I have declared my select field (ng-model="projectTypes")
and I declared the $scope.projectTypes and push the new Object to the $scope.projectTypes after the ajax call the select field won't update.
What am I doing wrong here?

Categories