laravel livewire insert selected data from datatable to an application form - laravel-livewire

I have a datatable with a list of job/career vacancies where in the selected item_number and position_title should be automatically filled in the application form.
item_number and position_title becomes null in the apply.blade.php
Vacant Component
class Vacant extends Component
{
use WithPagination;
use WithSorting;
use WithConfirmation;
protected $listeners = ['careerUpdated'];
public int $perPage;
public array $orderable;
public string $search = '';
public array $selected = [];
public array $paginationOptions;
protected $queryString = [
'search' => [
'except' => '',
],
'sortBy' => [
'except' => 'id',
],
'sortDirection' => [
'except' => 'asc',
],
];
public function careerUpdated() {
// Just Blank
}
public function getSelectedCountProperty()
{
return count($this->selected);
}
public function updatingSearch()
{
$this->resetPage();
}
public function updatingPerPage()
{
$this->resetPage();
}
public function resetSelected()
{
$this->selected = [];
}
public function vacant($id){
$career = Career::find($id);
$this->career = $career;
$this->emit('newCareer', $career->id);
}
public function mount()
{
$this->sortBy = 'id';
$this->sortDirection = 'asc';
$this->perPage = 100;
$this->paginationOptions = config('project.pagination.options');
$this->orderable = (new Career())->orderable;
}
public function render()
{
$query = Career::advancedFilter([
's' => $this->search ?: null,
'order_column' => $this->sortBy,
'order_direction' => $this->sortDirection,
]);
$careers = $query->paginate($this->perPage);
return view('livewire.career.vacant', compact('careers', 'query'));
}
vacant.blade.php
<table class="table table-index w-full" style="background-color: white; font-size: 13px;">
<thead>
<tr >
<th>
{{ trans('cruds.career.fields.item_number') }}
#include('components.table.sort', ['field' => 'item_number'])
</th>
<th>
{{ trans('cruds.career.fields.postition_title') }}
#include('components.table.sort', ['field' => 'postition_title'])
</th>
</tr>
</thead>
<tbody>
#forelse($careers as $career)
<tr>
<td>
{{ $career->item_number }}
</td>
<td>
{{ $career->postition_title }}
</td>
<td>
<div class="flex justify-end">
<a class="btn btn-sm btn-success mr-2" href="{{ route('applicants.apply', ['career' => $career->id]) }}">
{{ trans('Apply') }}
</a>
{{ trans('Apply') }}
</a>
</div>
</td>
</tr>
#empty
<tr>
<td colspan="10">No entries found.</td>
</tr>
#endforelse
</tbody>
</table>
Apply Component
class Create extends Component
{
public Applicant $applicant;
public $item_number, $position_title;
public Career $career;
public array $listsForFields = [];
public function mount(Applicant $applicant)
{
$this->applicant = $applicant;
$this->initListsForFields();
$getCareerID = explode('/', url()->current());
$this->career_id = end($getCareerID);
}
public function render()
{
return view('livewire.applicant.apply', ['career' => Career::find($this->career_id)]);
}
public function submit()
{
$this->validate();
$this->applicant->save();
$this->syncMedia();
return redirect()->route('admin.applicants.index');
}
protected function rules(): array
{
return [
'applicant.item_number' => [
'string',
'required',
],
'applicant.position_title' => [
'string',
'required',
],
'applicant.first_name' => [
'string',
'required',
],
'applicant.middle_name' => [
'string',
'required',
],
'applicant.last_name' => [
'string',
'required',
],
'applicant.email' => [
'email:rfc',
'required',
'unique:applicants,email',
],
}
}
apply.blade.php
<form wire:submit.prevent="submit">
<div class="form-group {{ $errors->has('career.item_number') ? 'invalid' : '' }}">
<label class="form-label" for="item_number">{{ trans('cruds.career.fields.item_number') }}</label>
<input class="form-control" type="text" name="item_number" id="item_number" wire:model.defer="career.item_number">
<div class="validation-message">
{{ $errors->first('career.item_number') }}
</div>
<div class="help-block">
{{ trans('cruds.career.fields.item_number_helper') }}
</div>
</div>
<div class="form-group {{ $errors->has('career.postition_title') ? 'invalid' : '' }}">
<label class="form-label" for="postition_title">{{ trans('cruds.career.fields.postition_title') }}</label>
<input class="form-control" type="text" name="postition_title" id="postition_title" wire:model.defer="career.postition_title">
<div class="validation-message">
{{ $errors->first('career.postition_title') }}
</div>
<div class="help-block">
{{ trans('cruds.career.fields.postition_title_helper') }}
</div>
</div>
<div class="form-group {{ $errors->has('applicant.first_name') ? 'invalid' : '' }}">
<label class="form-label required" for="first_name">{{ trans('cruds.applicant.fields.first_name') }}</label>
<input class="form-control" type="text" name="first_name" id="first_name" required wire:model.defer="applicant.first_name">
<div class="validation-message">
{{ $errors->first('applicant.first_name') }}
</div>
<div class="help-block">
{{ trans('cruds.applicant.fields.first_name_helper') }}
</div>
</div>
<div class="form-group {{ $errors->has('applicant.middle_name') ? 'invalid' : '' }}">
<label class="form-label required" for="middle_name">{{ trans('cruds.applicant.fields.middle_name') }}</label>
<input class="form-control" type="text" name="middle_name" id="middle_name" required wire:model.defer="applicant.middle_name">
<div class="validation-message">
{{ $errors->first('applicant.middle_name') }}
</div>
<div class="help-block">
{{ trans('cruds.applicant.fields.middle_name_helper') }}
</div>
</div>
<div class="form-group {{ $errors->has('applicant.last_name') ? 'invalid' : '' }}">
<label class="form-label required" for="last_name">{{ trans('cruds.applicant.fields.last_name') }}</label>
<input class="form-control" type="text" name="last_name" id="last_name" required wire:model.defer="applicant.last_name">
<div class="validation-message">
{{ $errors->first('applicant.last_name') }}
</div>
<div class="help-block">
{{ trans('cruds.applicant.fields.last_name_helper') }}
</div>
</div>
<div class="form-group {{ $errors->has('applicant.email') ? 'invalid' : '' }}">
<label class="form-label required" for="email">{{ trans('cruds.applicant.fields.email') }}</label>
<input class="form-control" type="email" name="email" id="email" required wire:model.defer="applicant.email">
<div class="validation-message">
{{ $errors->first('applicant.email') }}
</div>
<div class="help-block">
{{ trans('cruds.applicant.fields.email_helper') }}
</div>
</div>
<div class="form-group">
<button class="btn btn-indigo mr-2" type="submit">
Submit
</button>
</div>
</form>

Related

Livewire old values for dynamic arrays as part of a parent form

I'm working with livewire and need to preserve old values of a dynamic array (add/delete fields), inserted as a subform, when validation fails from another part of the form.
I need to preserve data already entered in the inputs, by means of an inserted livewire block, when a field of the container form fails in the validation. It turns out that when you return, the data entered in the livewire form is lost. Thanks for your help!
The place where I insert livewire tag...
...
<div class="form-group row">
<label for="numbers_per_line"
class="col-md-4 col-form-label text-md-right">
{{ __('Cantidad de números por línea (9 o 10)') }}
</label>
<div class="col-md-6">
<input class="form-control"
type="number" min="9" max="10"
name="numbers_per_line"
value="{{ old('numbers_per_line') ??
$bingo->numbers_per_line }}"
required>
</div>
</div>
#livewire('bingo-draw', ['bingo' => $bingo])
<div class="form-group row">
<label for="card_price"
class="col-md-4 col-form-label text-md-right">
{{ __('Precio del cartón') }}
</label>
<div class="col-md-6">
<input class="form-control"
type="number" min="1.00"
step="0.01" name="card_price"
value="{{ old('card_price') ?? $bingo->card_price }}"
required>
</div>
</div>
...
The code of livewire inserted is the following:
<div>
<div class="form-group row">
<label for="number_of_draws"
class="col-md-4 col-form-label text-md-right">
{{ __('Cantidad de premios en el sorteo final') }}
</label>
<div class="col-md-6">
<input class="form-control" type="number" min="1"
name="number_of_draws"
wire:model="numberOfDraws"
value="{{ old('number_of_draws') ??
$numberOfDraws }}"
required readonly="" disabled="true">
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<table class="table table-auto w-full">
<thead>
<th class="col-md-1 text-left">Nro. Sorteo</th>
<th class="col-md-7 text-left">Descripción</th>
<th class="col-md-2 text-left">
Valor del premio en pesos</th>
<th class="col-md-2 text-left" width="100"></th>
</thead>
<tbody>
#php $i = 0; #endphp
#foreach($drawsArray as $drawElement)
<tr>
<td class="p-1" valign="top">
<input class="form-control" type="number"
min="1" name="draw_number[]"
value="{{ old('draw_number.'.$i)
??
$drawElement['draw_number']
}}"
required readonly />
</td>
<td class="p-1" valign="top">
<textarea class="md-textarea form-control"
name="draw_description[]"
rows="2" required
>{{ old('draw_description.'.$i) ??
$drawElement['draw_description'] }}
</textarea>
</td>
<td class="p-1" valign="top">
<input class="form-control" type="text"
name="draw_prize[]"
value="{{ old('draw_prize.'.$i) ??
$drawElement['draw_prize']
}}"
required />
</td>
<td class="p-1" valign="top">
<button wire:click="removeDraw({{
$drawElement['draw_number'] }})"
type="button"
class="btn btn-warning">
Eliminar
</button>
</td>
</tr>
#php $i++; #endphp
#endforeach
</tbody>
</table>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-1">
#error('newDescription')
<div class="alert alert-danger" role="alert">
{{ $message }}
</div>
#enderror
<textarea class="md-textarea form-control"
name="new_description"
rows="2" wire:model.lazy="newDescription"
placeholder="Ingrese nuevo premio...">
</textarea>
</div>
<div class="col-md-3">
#error('newPrize')
<div class="alert alert-danger" role="alert">
{{ $message }}
</div>
#enderror
<input class="form-control" type="text"
name="new_prize"
placeholder="Importe..."
wire:model.lazy="newPrize">
</div>
<div class="col-md-2">
<button wire:click="addDraw"
type="button" class="btn btn-success">
Agregar premio
</button>
</div>
</div>
</div>
</div>
And finally, the code of the mount function:
public function mount(Bingo $bingo){
$this->numberOfDraws = old('numberOfDraws') ??
$bingo>number_of_draws;
$this->draws = $bingo->draws;
$this->currentBingo = $bingo;
if(old('numberOfDraws')){
for($i = 0; $i <= $this->numberOfDraws; $i++){
$this->drawsArray[] = [
'draw_number' => old('draw_number.'.$i),
'draw_description' => old('draw_description.'.$i),
'draw_prize' => old('draw_prize.'.$i),
];
}
}else{
foreach($this->draws as $draw){
$this->drawsArray[] = [
'draw_number' => $draw->draw_number,
'draw_description' => $draw->description,
'draw_prize' => $draw->prize,
];
}
}
}
The function addDraw keeps the values of draw_number in order, but if the validation fails I lost the old values...
I apologize if I'm not clear enough... my english is not very well, and is the first time I post some question here.
Thanks!

Bootstrap select2 in livewire keeps disappearing when I submit the form

I have a problem with my code the select2 is displaying only once when I refresh the page but it disappears when I submit the form or if there was a validation error it will disappear too. I tried wire:ignore The select2 doesn't disappear but it stops working properly and the form considered it like if it doesn't exist.
I use laravel 8, livewire 2 and turbolinks. Any help would be appreciated I've been stuck for almost 2 weeks.
Here is my code :
Blade:
<form wire:submit.prevent="submit">
{{ csrf_field() }}
<div class="form-group row">
<label for="to" class="col-form-label col-md-1">à :</label>
<div class="col-md-11" >
<select class="form-control mul-select" wire:model.lazy="id_to" name="id_to[]" multiple="multiple">
<option value="test#gmail.com">test#gmail.com</option>
<option value="test5#gmail.com">test5#gmail.com</option>
</select>
<div class="text-danger">
#error('id_to')
<span>
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
</div>
<div class="form-group row">
<label for="cc" class="col-form-label col-md-1">Cc :</label>
<div class="col-md-11">
<input type="text" class="form-control" wire:model.lazy="cc" name="cc" placeholder="Cc">
<div class="text-danger">
#error('cc')
<span>
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
</div>
<div class="form-group row">
<label for="sujet" class="col-form-label col-md-1">Sujet :</label>
<div class="col-md-11">
<input type="text" class="form-control" wire:model.lazy="sujet" name="sujet" placeholder="Sujet">
<div class="text-danger">
#error('sujet')
<span>
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
</div>
<div class="form-group row">
<label for="message" class="col-form-label col-md-1">Message :</label>
<div class="col-md-11">
<textarea class="form-control" name="message" wire:model.lazy="message" rows="8"></textarea>
<div class="text-danger">
#error('message')
<span>
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
</div>
{{-- <div class="email-editor">
<textarea class="form-control" id="summary-ckeditor" name="summary-ckeditor" wire:model.lazy="message"></textarea>
<div class="text-danger">
#error('message')
<span>
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div> --}}
<div class="email-action mt-3">
<button class="btn btn-primary" type="submit">Envoyer</button>
<button class="btn btn-warning" wire:click="resetForm">Reset</button>
</div>
</form>
<script type="text/javascript">
document.addEventListener("livewire:load", function (event) {
$(document).ready(function() {
$('.mul-select').select2();
});
});
</script>
Component:
public $id_to, $id_from, $sujet, $cc, $message;
public $rules=[
'id_to' => 'required',
'id_from' => '',
'cc' => '',
'sujet' => 'required|max:30',
'message' => 'required|max:155',
];
public function render()
{
return view('livewire.admin.messages.messages');
}
public function submit()
{
$validateData=$this->validate();
$to_email=User::where('email', $validateData['id_to'])->first();
Mail::send(array(), array(), function ($message) {
$validateData=$this->validate();
$emails=$validateData['id_to'];
foreach($emails as $email)
{
$message->to($email)
->subject($validateData['sujet'])
->from(Auth::user()->email, 'ADMIN')
->setBody($validateData['message']);
}
});
$validateData['id_from']=Auth::user()->id;
$validateData['id_to']= implode(",", $to_email->id);
SendMessage::create($validateData);
session()->flash('success', 'data has been sent successfully');
$this->resetForm();
}
public function resetForm()
{
$this->id_to = '';
$this->cc = '';
$this->sujet = '';
$this->message = '';
}
Here is a simple way to achieve that
<div class="col-md-11">
<div wire:ignore> // this will make sure to ignore DOM changes
<select
class="form-control"
id="mul-select"
name="id_to[]"
multiple="multiple"
>
<option value="test#gmail.com">test#gmail.com</option>
<option value="test5#gmail.com">test5#gmail.com</option>
</select>
</div>
<div class="text-danger">
#error('id_to')
<span>
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
And then outside of your component root tag make sure you push this script to your layout
#push('scripts')
<script>
$(document).ready(function () {
$('#mul-select').select2();
$(document).on('change', '#mul-select', function (e) {
//when ever the value of changes this will update your PHP variable
#this.set('id_to', e.target.value);
});
});
</script>
#endpush
Finally, on your layout file append the pushed script like this just before closing your body tag
#stack('scripts')
</body
Normally for select2 in Livewire I use hydration for element's rerender.
<div class="form-group row" wire:ignore.self> // I'm not sure about this it's necessary
<label for="to" class="col-form-label col-md-1">à :</label>
<div class="col-md-11" >
<select class="form-control mul-select" wire:model.lazy="id_to" name="id_to[]" multiple="multiple">
<option value="test#gmail.com">test#gmail.com</option>
<option value="test5#gmail.com">test5#gmail.com</option>
</select>
<div class="text-danger">
#error('id_to') <span><strong>{{ $message }}</strong></span> #enderror
</div>
</div>
</div>
//......
<script>
$(document).ready(function() {
window.initSelectDrop=()=>{
$('.mul-select').select2({
placeholder: '{{ __('locale.Select') }}',
allowClear: true});
}
initSelectDrop();
$('.mul-select').on('change', function (e) {
livewire.emit('selectedCompanyItem', e.target.value)
});
window.livewire.on('select2',()=>{
initSelectDrop();
});
});
</script>
in component
public function hydrate()
{
$this->emit('select2');
}
protected $listeners = [
'selectedCompanyItem'
];
public function selectedCompanyItem($value)
{
dd($value);
}

How to create a query function that will set a dynamic variable foreach selected column

Sorry if the title is misleading , i have a page that has many select option element , that will make you choose the database name , table name , column name , and filter .. here's the html
div class="row mt">
<div class="col-lg-12">
<div class="form-panel">
<form class="form-horizontal style-form" action="#">
<div class="form-group">
<label class="control-label col-md-3">Database Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id = "tableselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
<option disabled selected value>-- Choose --</option>
<!-- <li></li> -->
{% for table in obj2 %}
<option value = "{{table}}" >{{ table }}</option>
{% endfor %}
<!-- <li>Dropdown link</li> -->
</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Table Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
</div>
<div class="form-group" id="column-name">
<button class="btn btn-theme" onclick="return appendBox()">Add</button>
<label class="control-label col-md-3">Column Name</label>
<div class="col-md-4" id ="test">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select class = "columnselect" id="headerselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
</div>
<div class="form-group" id="condition">
<button class="btn btn-theme" onclick=" return appendFilterBox()">Add</button>
<label class="control-label col-md-3">Filter</label>
<div class="col-md-4" id="filtbox">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select class = "columnselect" id="conditionselect" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;"></select>
<select id="operator" style="width:120px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
<option disabled selected value>-- Choose --</option>
<option> > </option>
<option> < </option>
<option> ≥ </option>
<option> ≤ </option>
<option> = </option>
</select>
<input id="parameter" type="text" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
</input>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-4" id="showquery">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<button id="result" class="btn btn-theme" type="submit" style="height:30px;width:100px;" onclick="return showQuery()">Show</button>
<button id="export" class="btn btn-theme" type="Export" style="height:30px;width:100px;" href="{% url 'polls:export' %}" onclick="return ExportFile()">Export</button>
</div>
</div>
</div>
</div>
<div id="query_result">
#Query result will be shown here
</div>
<script>
$(document).ready(function() {
$("#result").click(function () {
var urls = "{% url 'polls:load-query' %}";
var table = $('#dataselect').val();
data = {
'name' : [],
'table': table,
'condition': []
};
$('#column-name .columnselect').each((idx, el) => data.name.push($(el).val()));
$('#filtbox .input-group').each((idx, el) => {
let column = $(el).find('#conditionselect').val();
let operator = $(el).find('#operator').val();
let value = $(el).find('#parameter').val();
data.condition.push(`${column}${operator}${value}`);
});
data.name = data.name.join(',');
data.condition = data.condition.join(' AND ');
console.log(data);
$.ajax({
url: urls,
data: data,
success: function(data) {
$("#query_result").html(data);
},
error: function(data)
{
alert("error occured");
}
});
});
});
</script>
<script>
function appendBox()
{
$('#test').append('<select class ="columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;margin-top:5px"></select>')
return false
}
</script>
For every option that can be choose , user can add another select option element for column name .
data name will be used for select in query , for example user choose user data name , so when we send the request , it will be like select [data_name](which mean user) from table_name where filter
here's the views
def list_all_table(request):
data_name = request.GET.get('name',1)
table_name = request.GET.get('table',1)
column_name = request.GET.get('column',1)
operator = request.GET.get('operator',1)
condition = request.GET.get('condition',1)
dsn_tns = cx_Oracle.makedsn('', '', sid='dicb')
conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns)
c = conn.cursor()
c.execute("select "+data_name+" from "+table_name+" where "+column_name+operator+"'"+condition+"'")
c.rowfactory = makeDictFactory(c)
databasetable = []
for rowDict in c:
databasetable.append(rowDict['data_name'])
context = {
'obj2' : databasetable
}
return render(request,'define_segment.html',context)
for a single value , it is easy because my views no need to that dynamically and only need 1 variable to send the request . But what if user add more column name , how bout 2 ? how bout 3 ? we dont know really what user want to add how much .
I just want it to dynamically , if user add 3(for example , and value can change) column name, it will select 3 column and they can send 3 selected value to the return render(request,'define_segment.html',context). It's just i dont have in mind what i must suppose to do .
So long as your column names list maintains its order you should be able to dynamically generate a table from the results
column_names = ['foo', 'bar', ...]
databasetable = []
for row in c:
databasetable.append([row[column_name] for column_name in column_names])
Then return databasetable and column_names in the render context
return render(request,'template.html', {'data': databasetable, 'column_names': column_names})
Then in the template
<table>
<thead>
<tr>
{% for column_name in column_names %}
<th>{{ column_name }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in data %}
<tr>
{% for value in row %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>

how to properly configure error handling in template

I have a basic form that I'm rendering in template using standard "{{ form.name_of_field.errors }} tags. When I try to submit an empty form, I expect to see the form re-rendered with "•field is required" next to the empty form fields. What I get instead is a Value Error. "The view wedbpjr.wedb.views.display_prdInboxEntry didn't return an HttpResponse object." Where am I going wrong?
<form action="." method="POST">{% csrf_token %}
{{ form.non_field_errors }}
<table id="inbox_table">
<tr>
<td colspan="6">
<div class="fieldWrapper">
{{ form.assigned_by.errors }}
<label for="id_assigned_by">Assigned by:</label>
{{ form.assigned_by }}
</div>
</td>
</tr>
<tr>
<td>
<div class="fieldWrapper">
{{ form.job_number.errors }}
<label for="id_job_number">job no:</label><br />
{{ form.job_number }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.cell_number.errors }}
<label for="id_cell_number">cell:</label><br />
{{ form.cell_number }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.job_name.errors }}
<label for="id_job_name">job name:</label><br />
{{ form.job_name }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.request.errors }}
<label for="id_request">request:</label><br />
{{ form.request }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.note.errors }}
<label for="id_note">note:</label><br />
{{ form.note }}
</div>
</td>
<td>
<div class="container">
<!-- <div class='well'> -->
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
{{ form.date_due.errors }}
<label for="id_date_due">date_due:</label>
{{ form.date_due}}
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<!-- </div> -->
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker();
});
</script>
</div>
</td>
</tr>
<tr>
<td>
<div class="fieldWrapper">
{{ form.box.errors }}
<label for="id_box">inbox:</label><br />
{{ form.box }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.assigned_to.errors }}
<label for="assigned_to">assigned_to:</label><br />
{{ form.assigned_to }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.basecamp_link.errors }}
<label for="id_basecamp_link">basecamp:</label><br />
{{ form.basecamp_link }}
</div>
</td>
<td>
<div class="accepted_by">
{{ form.accepted_by.errors }}
<label for="id_accepted_by">accepted_by:</label><br />
{{ form.accepted_by }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.status.errors }}
<label for="id_status">status:</label><br />
{{ form.status }}
</div>
</td>
<td>
<div class="container">
<!-- <div class='well'> -->
<div class="form-group">
<div class='input-group date' id='datetimepicker2'>
{{ form.completed_on.errors }}
<label for="id_completed_on">completed:</label>
{{ form.completed_on}}
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<!-- </div> -->
<script type="text/javascript">
$(function () {
$('#datetimepicker2').datetimepicker();
});
</script>
</div>
</td>
</tr>
<tr>
<td>
<p><input id="inbox_submit_btn" type="submit" value="add" /></p>
</td>
<td>
<p><input id="inbox_delete_btn" name="delete" type="submit" value="delete" /></p>
</td>
</tr>
</table>
</form>
Running Django 1.5.1 - Python 2.7
views.py
def display_prdInboxEntry(request, id):
if request.method == 'POST':
form = PrdInboxForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/production-display/'+ id +'/')
else:
form = PrdInboxForm()
user = request.user
u = UserProfile.objects.get(pk=id)
creativerecords = InboxEntry.objects.filter(box="Creative")
studiorecords = InboxEntry.objects.filter(box="Studio")
records = InboxEntry.objects.filter(assigned_to=u)
return render_to_response('home_inbox.html', {'form': form, 'records': records, 'studiorecords': studiorecords, 'creativerecords': creativerecords, 'user': user}, context_instance=RequestContext(request))
The errors is coming from your view, Make sure you have a condition for your form.is_valid equaling False. This usually involves reshowing the form with the incorrect data
from django.shortcuts import render
from django.http import HttpResponseRedirect
def contact(request):
if request.method == 'POST': # If the form has been submitted...
# ContactForm was defined in the the previous section
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {
'form': form,
})
The django documentation, clearly explains this

How to create a popup with a form inside a table element in Django

I want to have a "sendemail" button for each element in the table, once the user clicks on this there should be a pop up with a form inside and a button. I tried using jquery for the popup but it is not working, can someone please tell me what I am doing wrong or suggest me any other way of creating this pop up. Currently I am using twitter bootstrap modal but want to replace that with a popup/popover
homepage.html
<table id="search-results" class="table table-hover">
</table>
ajax.js
$(function(){
$('#searchtest').click(function() {
$.ajax({
type: "POST",
url: "/searchtrips/",
data: {
'city' : $('#city').val(),
'location' : $('#location').val(),
'duration' : $('#duration').val(),
'search_text' : $('#searchtest').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#search-results').html(data);
}
search-results.html
{% for data in datas %}
<tr>
<td>{{ data.score}}</td>
<td>{{ data.distance}}</td>
<td>{{ data.time}}</td>
{%for element in data.place.elements%}
<td>
{{element.placeName}}
</td>
{% endfor %}
<td>
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Share with your friends</h3>
</div>
<form action="{% url "send_mail"%}" class="form-horizontal" method="post">
<div class="control-group">
<label class="control-label" for="subject">Subject</label>
<div class="controls">
<input type="text" name="subject" value="Your friend has shared a traverse trip" id="subject" placeholder="subject">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" name="email" id="email" placeholder="Email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="message">Message</label>
<div class="controls">
<input type="text" name="message" id ="message" placeholder="message" value ="Here we will have the link ">
</div>
</div>
<div class="modal-footer">
{% csrf_token %}
<input type="submit" value="email" class="btn btn-primary">
</div>
</form></div>
<i class="icon-envelope"></i>SendEmail
<a href="{% url "add_trip" city=data.score score=data.score distance=data.distance|floatformat:"0" time=data.time %}"
class ="btn btn-mini btn btn-warning">Add/delete</a>
</td>
</tr>
{% endfor %}*