Ruby On Rails "undefined method `description' for #" when save - forms

I'm relatively new to rails and I've been struggling with this for a couple of days. I'd be much appreciated if you can see where I've gone wrong.
I got this error message
undefined method `description' for #<Invoicegeneric:0x000001054900b0>
if #invoicegeneric.save ==> error at this
response = "Success"
else
response = "Error"
and this is my controller code
def addgenericitems
#invoicegeneric = Invoicegeneric.new
#invoicegeneric.invoice_id = params[:invoice_id]
#invoicegeneric.po_id = params[:po_id]
if #invoicegeneric.save
response = "Success"
else
response = "Error"
end
render :json => {:html => render_to_string(:partial => "invoices/invoicegenerics", :layout => false) }.to_json, :status => :ok
end
and this is my html
<form id="modal-form" class="pure-form pure-form-stacked"
name="invoicegenericform" action="<%= addgenericitems_invoice_path(#invoice) %>"
method="post">
<fieldset>
<label for="po_id">PO</label>
<select name="po_id" class="chzn-select">
<% Purchaseorder.active.order(:sku).each do |p| %>
<option value="<%= p.sku %>"><%= "#{p.sku}" %></option>
<% end %>
</select>
</fieldset>
<fieldset>
<label for="sku_sj">SJ</label>
<input name="sku_sj" type="text">
</fieldset>
<div class="modal-footer">
<button class="pure-button" data-dismiss="modal" aria-hidden="true">Close</button>
<input type="submit" class="pure-button pure-button-primary" value="Tambah"/>
</div>
</form>
In my table there is no column name description

Related

storing form and rout

I have problem on storing form . All my efforts will be damaged if I could not solve it.
The GET method is not supported for this route. Supported methods: POST.
what happen now :
1.When I press on register which is linked to this rout :
Route::POST('/jobs/apply/{id}/', [JobseekerController::class,'applyforjob'])->name('aplpy1');
there will be two scenarios:
if the user has cv it will register the user directly.(works)
if the user has not cv it will direct the user to create cv view .(works)
This is a part of create cv view :
<form method="POST" action="{{route('storing')}}" enctype=multipart/form-data>
#csrf
<input type="hidden" name=job_id value= {{$s}}>
#if (count($errors) > 0)
<div class="alert alert-danger alert-dismissible fade show">
<strong>Opps!</strong> Something went wrong, please check below errors.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
<div class="card-body">
<div class="container">
<!------ Include the above in your HEAD tag ---------->
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="accordion" class="checkout">
<div class="panel checkout-step">
<div> <span class="checkout-step-number">1</span>
<h4 class="checkout-step-title"> <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" > Personal Information</a></h4>
</div>
<div id="collapseOne" class="collapse in">
<div class="checkout-step-body">
<div class="row mt-3 pr-3">
<div class="col-6 ">
<strong>Full Name:</strong>
{!! Form::text('FName', null, array('placeholder' => 'Full Name','class' =>
'form-control pb-4')) !!}
</div>
<div class="col-6">
<div class="row mt-3 mr-2">
<strong>Nationality:</strong>
<select name="Nationality" class="custom-select">
#foreach(\App\Models\Nationality::all() as $nation)
<option value="{{$nation->name}}">{{$nation->name}}</option>
#endforeach
</select>
</div>
<div class="form-group ">
<button type="submit" name="submit" class="btn btn-primary ">{{ __('APPLAY') }}</button
</div>
<input type="hidden" name=job_id value= {{$s}}>
</form>
2.Now Here is the problem:
If I fill all the fields on the form correctly and click apply it works , but if there is missing field or anything not filled as it should be and then click apply , although there is validation on controller it does not work it gives this error:
The GET method is not supported for this route. Supported methods: POST.
Although I am using Post this my rout that I use to store the form
Route::POST('/jobsapply', [JobseekerController::class,'store'])->name('storing');
This my controller for storing:
public function store(Request $request )
{
$this->validate($request, [
'FName' => 'required|alpha|regex:/^([^"!\*\\]*)$/',
'Nationality' => 'required',
]);
$input = $request->all();
$input = $request->except(['_token']);
$cv = new cv();
if ($this->cvsave($cv, $request )) {
$data = Job::all();
$cv = auth()->user()->cv;
return view ('show',compact('cv' ,'data'))->with('success', 'CV created successfully.');
}
$data = Job::all();
return view('show')->with('Failed!', 'error');
}
public function cvsave(cv $cv, Request $request)
{
$cv->FName = $request->FName;
$cv->Nationality = $request->Nationality;
if ($cv->save()) {
$application = new JobApplication;
$id=$request->job_id;
$jobs = Job::find($id)->get();
$application->job_id =$request->job_id;
$user = User::find(auth()->user()->id);
$application->user_id = auth()->user()->id;
$cv = auth()->user()->cv;
$i= $cv->id;
$application->cv_id = $i;
$application->save();
\Session::flash('success', 'Thank you for applying! Wait for the company to respond.!');
return true;
}
return false;
}
I could not know the reason, I have read lots of stuff but still the same error

how to define an entity inside the function symfony 5

for exemple this is my function :
/**
* #Route("/companyProfile/{id_Adresse}/{id_Employes}/{id_Contact}", name="company_profile")
* #ParamConverter("Adresse", options={"mapping": {"id_Adresse" : "id"}})
* #ParamConverter("Employes", options={"mapping": {"id_Employes" : "id"}})
* #ParamConverter("Contact", options={"mapping": {"id_Contact" : "id"}})
*/
public function index(Adresse $adresse , Employes $employes , Contact $contact,ContactRepository $contactrepository, EmployesRepository $employesrepository , AdresseRepository $adresserepository ): Response
{
$contactform=$this->createForm(ContactType::class, $Contact);
$employesform=$this->createForm(EmployesType::class, $Employes);
$adresseform=$this->createForm(AdresseType::class, $Adresse);
return $this->render('companyProfile.html.twig', [
'Contact' => $contactrepository->findAll(),
'Employes' => $employesrepository->findAll(),
'Adresse' => $adresserepository->findAll(),
'contactform'=>$contactform->createView(),
'employesform'=>$employesform->createView(),
'adresseform'=>$adresseform->createView()
]);
}
as you can see i declare all my entity in the parameter but i need to add all there ids in the route and that's not what i need , i just want my route to be like this :
/*
*#Route ("/companyProfile", name="company_profile")
*/
thanks in advance for all your answer
The param converter goal is the retrieve an entity from a route parameter. My guess is that you want to get all this entities but not with their ids in the route.
To do so, you will need to get the repository for each of your entity and then get them here. There is a question still : how do you know which entity do you want?
Here is an exemple of your action
/**
* #Route("/companyProfile", name="company_profile")
*/
public function index(ContactRepository $contactRepository, EmployesRepository $employesRepository , AdresseRepository $adresseRepository): Response
{
$contactform = $this->createForm(ContactType::class, $contactRepository->find($contactId);
$employesform = $this->createForm(EmployesType::class, $employesRepository->find($employesId);
$adresseform = $this->createForm(AdresseType::class, $adresseRepository->find($adresseId);
return $this->render('companyProfile.html.twig', [
'Contact' => $contactrepository->findAll(),
'Employes' => $employesrepository->findAll(),
'Adresse' => $adresserepository->findAll(),
'contactform'=>$contactform->createView(),
'employesform'=>$employesform->createView(),
'adresseform'=>$adresseform->createView()
]);
}
You still need a way to get all this new ids variables, but I can't help you more with the given informations.
i tried a different way to display them but when i want to edit for exemple contact , it dosen't work and they show me this error:
An exception has been thrown during the rendering of a template ("Notice: Undefined index: Contact").
here's a screenshot:
enter image description here
and here's my code :
/**
* #Route("/companyProfile/", name="company_profile")
*/
public function index(): Response
{
$Contact = $this->getDoctrine()
->getRepository(Contact::class)
->findAll();
$Employes = $this->getDoctrine()
->getRepository(Employes::class)
->findAll();
$Adresse = $this->getDoctrine()
->getRepository(Adresse::class)
->findAll();
return $this->render('companyProfile.html.twig', [
'Contact' => $Contact,
'Employes' => $Employes,
'Adresse' => $Adresse,
]);
}
this is the edit function:
/**
* #Route("/UpdateContact/{id}",name="editcontact")
*/
public function EditContact(Contact $contact , Request $request ,ManagerRegistry $manager)
{
$contactform=$this->createForm(ContactType::class, $contact);
$contactform->handleRequest($request);
if($contactform->isSubmitted() && $contactform->isValid())
{
$manager = $this->getDoctrine()->getManager();
$manager->persist($contact);
$manager->flush();
return $this->redirectToRoute('company_profile');
}
return $this->render('companyProfile.html.twig', [
'contactform'=>$contactform->createView()
]);
}
and last my twig :
<div class="boxed-list margin-bottom-60">
<div class="boxed-list-headline">
<h3><i class="icon-material-outline-business-center"></i> les contactes d'entreprise</h3>
</div>
</br>
{% for Contact in Contact %}
<div class="listings-container compact-list-layout">
<ul class="list-group">
<li class="list-group-item">
<h3>Contact</h3>
</br></br>
<div class="container pt-3">
<h5>Responsable:</h5>
<p>{{Contact.responsable}}</p>
<h5>N° de tele:</h5>
<p>{{Contact.telephone}}</p>
<h5>Addresse email:</h5>
<p>{{Contact.email}}</p>
<h5>Note:</h5>
<p>{{Contact.note}}</p>
<div class="centered-button margin-top-35">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Modifier
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<!-- Form -->
<form method="post" id="add-note">
<div class="form-group">
<label for="nom">Responsable:</label>
<input type="text" class="form-control" placeholder="{{Contact.responsable}}" id="nom">
</div>
<div class="form-group">
<label for="tele">N° de tele:</label>
<input type="text" class="form-control" placeholder="{{Contact.telephone}}" id="telephone">
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" placeholder="{{Contact.email}}" id="email">
</div>
<label for="note">Note:</label>
<textarea name="textarea" cols="10" placeholder="{{Contact.note}}" class="with-border"></textarea>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button><i class="icon-material-outline-arrow-right-alt"></i>
</div>
</div>
</div>
</div>

My form is not populating when there is some validation error in the input data. Laravel Collective

Hope yo are all doing great.
I am using Laravel 5.3 and a package LaravelCollective for form-model binding.
I have subjects array that I want to validate and then store in database if there is no error in the input data.
The following snippets show the partial view of form, other views, rules for validations and controller code.
UserProfile.blade.php
<!-- Panel that Adds the Subject - START -->
<div class="col-md-12">
<div class="panel panel-default" id="add_Subject_panel">
<div class="panel-heading">Add Subject(s):</div>
<div class="panel-body">
{!! Form::open( array('method'=>'post', 'url'=>route('user.store.subject', 1)) ) !!}
#include('user.partials.subjects', ['buttonText'=>'Add Subject(s)'])
{!! Form::close() !!}
</div>
</div>
</div>
<!-- Panel that Adds the Subject - END -->
subjects.blade.php
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="subject-list">
<div class="input-group subject-input">
<input type="text" name="name[]" class="form-control" value="" placeholder="Subject" />
<span class="input-group-btn">
<span class="btn btn-default">Primary subject</span>
</span>
</div>
</div>
<div class="text-right">
<br />
<button type="button" class="btn btn-success btn-sm btn-add-subject"><span class="glyphicon glyphicon-plus"></span> Add Subject</button>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4 text-right">
<button type="submit" class="btn btn-primary">
{{ $buttonText }} <i class="fa fa-btn fa-subject"></i>
</button>
</div>
</div>
#push('scripts')
{{-- <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> --}}
<script src="{{ asset('scripts/jquery-2.2.4.min.js') }}" type="text/javascript" charset="utf-8" async defer></script>
<script>
$(function()
{
$(document.body).on('click', '.btn-remove-subject', function(){
$(this).closest('.subject-input').remove();
});
$('.btn-add-subject').click(function()
{
var index = $('.subject-input').length + 1;
$('.subject-list').append(''+
'<div class="input-group subject-input" style="margin-top:20px; margin-bottom:20px;">'+
'<input type="text" name="name['+index+']" class="form-control" value="" placeholder="Subject" />'+
'<span class="input-group-btn">'+
'<button class="btn btn-danger btn-remove-subject" type="button"><span class="glyphicon glyphicon-remove"></span></button>'+
'</span>'+
'</div>'
);
});
});
</script>
#endpush
I want to validate all the subjects passed as an array to the controller using a custom created form request. the following is the code for that form request
SubjectRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SubjectRequest 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()
{
// dd("Rules Area");
foreach($this->request->get('name') as $key => $val)
{
$rules['name.'.$key] = 'required|min:5|max:50';
}
// dd($rules);
return $rules;
}
public function messages()
{
// dd('Message Area. . .');
$messages = [];
foreach($this->request->get('name') as $key => $val)
{
$messages['name.'.$key.'.required'] = ' Subject Name '.$key.'" is required.';
$messages['name.'.$key.'.min'] = ' Subject Name '.$key.'" must be atleast :min characters long.';
$messages['name.'.$key.'.max'] = ' Subject Name '.$key.'" must be less than :max characters.';
}
// dd($messages);
return $messages;
}
}
the following is the code for controller method I am using to store inputted array data to database.
public function storeSubjects(SubjectRequest $request)
{
$data = $request->all();
// save logic
dd($data);
}
Problem:
My form is not populating when there is some validation error in the input data.
After getting validation errors, my input fields are blank.
Problem
In subject.blade.php, your code looks like
<input type="text" name="name[]" class="form-control" value="" placeholder="Subject" />
Your fields are not populating because you have left value attribute blank.
Solution:
Pass the old value to solve your problem.
<input type="text" name="name[]" class="form-control" value="{{old('name[]')}}" placeholder="Subject" />
Use Form Model Binding instead
https://laravelcollective.com/docs/5.3/html#form-model-binding
{{ Form::model($user, [....]) }}
{{ Form::text('firstname', null, [...]) }}
{{ Form::close() }}

Form authentication for . NET sites using Perl

We are new in Perl scripting and we wanted to pass through a .NET site authentication.
We have an existing code for authentication specific for Sharepoint sites, code snippet below:
my $ua = new LWP::UserAgent('keep_alive' => '1');
print "$url \n";
$ua->credentials("$uname", "$pwd");
my $response =$ua->get($url);
my $cde = $response->code();
We wanted to customize the code so that it will work specific for .NET sites authentication. We used WWW::Mechanize, see code snippet below:
my $mech = WWW::Mechanize->new();
$mech->cookie_jar(HTTP::Cookies->new());
$mech->get($url);
$mech->form_name('Login');
$mech->field("UserName", $username);
$mech->field("Password", $password);
$mech->click();
But when the program is run, an error is shown: "There is no form named 'Login' in sample.pl". Any thoughts on how to authenticate forms specific for .NET sites?
Adding: HTML form code snippet...
<div id="loginArea">
<div id="loginMessage" class="groupMargin">Sign in with your account</div>
<form method="post" id="Login" autocomplete="off" novalidate="novalidate" onkeypress="if (event && event.keyCode
== 13) Login.submitLoginRequest();" action="">
<div id="formsAuthenticationArea">
<div id="userNameArea">
<input id="userNameInput" name="UserName" type="email" value="" tabindex="1" class="text fullWidth" spellcheck="false" placeholder="Username" autocomplete="off">
</div>
<div id="passwordArea">
<input id="passwordInput" name="Password" type="password" tabindex="2" class="text fullWidth" placeholder="Password" autocomplete="off">
</div>
<div id="kmsiArea" style="display:none">
<input type="checkbox" name="Kmsi" id="kmsiInput" value="true" tabindex="3">
<label for="kmsiInput">Keep me signed in</label>
</div>
<div id="submissionArea" class="submitMargin">
<span id="submitButton" class="submit" tabindex="4" onkeypress="if (event && event.keyCode == 32) Login.submitLoginRequest();" onclick="return Login.submitLoginRequest();">Sign in</span>
</div>
</div>
</form>
</div>
Usually this code works for .NET sites:
$mech->submit_form(
with_fields => {
login => "somelogin",
pass => "somepass",
},
button => "submit_button_name",
);
But you have weird error message: you're selecting "Login" form but $mech searching for "loginForm"... Can you show actual form's HTML?
Also there is no need to do $mech->cookie_jar(...) because $mech do this by default.
UPDATE
Try this code (Login is id of your form but not the name):
$mech->submit_form(
with_fields => {
UserName => "somelogin",
Password => "somepass",
},
);

Yii - Error (and possible solution) validating form with clientValidation active, and using a custom container

I was creating a CActiveForm with the ClientValidation enabled, but stepped in an error when I wrapped a RadioButtonList inside a UL container.
Whenever I submited the form I get a "field cannot be empty" message, even if the radios were checked.
My form:
$form=$this->beginWidget('CActiveForm', array(
'id'=>'enrollment-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'inputContainer'=>'ul',
'validateOnSubmit'=>true,
),
));
And one of the RadioButtonLists I use:
<div id="drinks">
<?php echo $form->label($model,'drink_id',array('class' => 'title')); ?>
<?php echo $form->radioButtonList($model,'drink_id', CHtml::listData($drinks, 'id', 'name'), array('container'=>'ul', 'template' => '<li class="radio_row">{input}{label}</li>','separator' => '')); ?>
<?php echo $form->error($model,'drink_id'); ?>
</div>
Was I making something wrong?
I studied the code of the jquery.yiiactiveform.js and found that my problem was that in the function that gets the value of the inputs, the value was not taken correctly, because the ID used to identify the inputs was not set in a span, or in the checkboxes/radios themselves (the id was set in the UL container I defined):
var getAFValue = function (o) {
var type,
c = [];
if (!o.length) {
return undefined;
}
if (o[0].tagName.toLowerCase() === 'span') {
o.find(':checked').each(function () {
c.push(this.value);
});
return c.join(',');
}
type = o.attr('type');
if (type === 'checkbox' || type === 'radio') {
return o.filter(':checked').val();
} else {
return o.val();
}
};
So I solved this adding || o[0].tagName.toLowerCase() === 'ul':
var getAFValue = function (o) {
var type,
c = [];
if (!o.length) {
return undefined;
}
if (o[0].tagName.toLowerCase() === 'span' || o[0].tagName.toLowerCase() === 'ul') {
o.find(':checked').each(function () {
c.push(this.value);
});
return c.join(',');
}
type = o.attr('type');
if (type === 'checkbox' || type === 'radio') {
return o.filter(':checked').val();
} else {
return o.val();
}
};
Maybe I was just making some mistake and this solution is just a crappy workaround... but maybe this is just a bug ¿?
The HTML generated:
<form id="enrollment-form" action="/enrollment" method="post">
<div style="display:none"><input type="hidden" value="b06e1d1d796f838f30ba130f8d990034aa9fdad6" name="YII_CSRF_TOKEN" /></div>
<div id="enrollment-form_es_" class="errorSummary" style="display:none"><p>Please fix the following input errors:</p>
<ul><li>dummy</li></ul>
</div>
<div id="drinks">
<label class="title" for="EnrollmentForm_drink_id">Drinks</label>
<input id="ytEnrollmentForm_drink_id" type="hidden" value="" name="EnrollmentForm[drink_id]" />
<ul id="EnrollmentForm_drink_id">
<li class="radio_row">
<input id="EnrollmentForm_drink_id_0" value="2" type="radio" name="EnrollmentForm[drink_id]" />
<label for="EnrollmentForm_drink_id_0">Tea</label>
</li>
<li class="radio_row">
<input id="EnrollmentForm_drink_id_1" value="1" type="radio" name="EnrollmentForm[drink_id]" />
<label for="EnrollmentForm_drink_id_1">Juice</label>
</li>
</ul>
<div class="errorMessage" id="EnrollmentForm_drink_id_em_" style="display:none"></div>
</div>
I noticed that if I didn't use any container when generating the RadioButtonList, Yii aplies a "class=success" to a span. And with my UL container, that class is not generated. When I've changed the Javascript, the class success is generated again.
** The HTML generated without the inputContainer option and without the last array in radioButtonList:
<div id="drinks">
<label class="title" for="EnrollmentForm_drink_id">Bebidas</label>
<input id="ytEnrollmentForm_drink_id" type="hidden" value="" name="EnrollmentForm[drink_id]">
<span id="EnrollmentForm_drink_id">
<input id="EnrollmentForm_drink_id_0" value="2" type="radio" name="EnrollmentForm[drink_id]"> <label for="EnrollmentForm_drink_id_0">Tea</label><br>
<input id="EnrollmentForm_drink_id_1" value="1" type="radio" name="EnrollmentForm[drink_id]"> <label for="EnrollmentForm_drink_id_1">Juice</label>
</span>
<div class="errorMessage" id="EnrollmentForm_drink_id_em_" style="display:none"></div>
</div>
As you can see, Yii generates a strange span that controls if the form is valid or not, by aplying to it the class "success". If I use the inputContainer UL then this class="success" is not generated (with my workaround it is generated and it works).