Laravel 'Form::model' does not populate my edit form - php

I am in the progress of making a form to edit an existing entry in the database. I am using the Form::model approach to do this, however it doesn't seem to work. The fields just stay empty.
ServerController.php
/**
* Editing servers
*/
public function edit($name)
{
$server = Server::find($name);
$keywords = ($server->getKeywords()) ? $server->getKeywords() : array();
$countries = $this->getCountries();
return View::make('server/edit', array('server' => $server, 'countries' => $countries));
}
public function update($name)
{
$server = Server::find($name);
// Did it succeed?
if($server->save()) {
Session::flash('success', 'You server was edited!');
return Redirect::route('server.view', array($name));
}
// Did not validate
if(Input::get('keywords')) {
$keywords = Input::get('keywords');
Session::flash('keywords', $keywords);
}
Session::flash('danger', "<b>Oops! There were some problems processing your update</b><br/>" . implode("<br/>", $server->errors()->all()));
return Redirect::route('server.edit', array($name))->withInput()->withErrors($server->errors());
}
The Form
{{ Form::model($server, array('route' => array('server.update', $server->name), 'class' => 'form-horizontal', 'role' => 'form', 'files' => true)) }}
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
{{ Form::label('email', 'Email', array('class' => 'control-label col-md-4')) }}
<div class="col-md-4">
{{ Form::text('email', '', array('class' => 'form-control')) }}
{{ $errors->first('email', '<br/><div class="alert alert-danger">:message</div>') }}
</div>
</div>
(some more fields)
{{ Form::close() }}

The problem here is that you're passing in an empty string as the default field value. As the documentation states here, any explicitly passed values will overrule the model attribute data. Try using null instead of '':
{{ Form::text('email', null, array('class' => 'form-control')) }}

Related

Passing two model values to different form.blade under one view in laravel 5.1 for edit

In my edit.blade page I have include two form blades as given below. To update I have to pass two different model data for those blades but its not working in my way. Please help me.
Here is my edit blade:
{!! Form::model($requisitions, array('route' => ['requisition.update', Crypt::encrypt($requisitions->id)], 'id' => 'requisition_update', 'class' => 'form-horizontal row-border')) !!}
#include('department_user.requisitions._form')
<div style="height:30px;"></div>
<h4> Requisition Material(s) </h4>
#include('department_user.requisitions._item_form')
<div class="col-md-12">
{!! Form::label('', '', array('class' => 'col-md-2 control-label')) !!}
{!! Form:: submit('Update', ['class' => 'btn btn-success']) !!}
</div>
{!!form::close()!!}
and my function is
public function edit( $id ) {
$id = Crypt::decrypt($id);
$requisitions = Requisition::findOrFail($id);
$requisitionitems = RequisitionItem::findOrFail($id);
$chargeable_accounts = [''=> 'Select Chargeable Account'] + ChargeableAccount::whereStatus(1)->orderBy('name', 'DESC')->lists('name', 'id')->toArray();
$item_measurements = [''=> 'Select Item'] + ItemMeasurement::whereStatus(1)->orderBy('item_name', 'DESC')->lists('item_name', 'id')->toArray();
$units = ['' => 'Select Unit'] + MeasurementUnit::whereStatus(1)->orderBy('name', 'DESC')->lists('name', 'id')->toArray();
return view('department_user.requisitions.edit', compact('units', 'item_measurements', 'chargeable_accounts', 'requisitions','requisitionitems'));
}
To pass data to the include just use a second parameter
#include('department_user.requisitions._item_form', $modelA)
#include('department_user.requisitions._item_form', $modelB)
This should do the trick. Also:
{!!form::close()!!}
to
{!!Form::close()!!}

Laravel 5.2 validation erros are empty at random moments

I have something very weird going on with my Laravel application's validation. I have an application where a user can only access it with his/hers unique hash/code in the url. When the url with hash matches a user I prefill the form with the user's profile information. The user then has to confirm/complete/modify it the information in using the form. This works fine, but when submitting the form sometimes the validation not behaving normally.
For example, I leave some fields empty that are required and I submit the form, I get redirected back, my errors are shown in the form fields with a nice red border. All good so far. However, for some unknown reason sometimes when submitting the form with an empty value in a field which is required by the validation, it redirects back and shows the profile form pre-filled again, but the errors variable is empty, but the validation still failed!
Their is no line to draw in when this happens, sometimes it happens on the first submit sometimes I have to submit the form 30 times before it happens. For now we tackled it with an extra layer of frontend validation because the app had to go live, but I can't stop thinking about why and how this is happening.
I'm using a Request class for validation, but I also tried creating a manual validator in my controller, but that has exactly the same behaviour. I first thought that it has something to do with pre-filling the form, so I tried that when there are errors and I don't prefill anything (except input old of course), but the problem still exists.
The weirdest part of it all is that the errors are empty, but some required fields were not filled (and their names are correct) because the problem does not always happens. I have been unable to reproduce the problem on my local and staging env, but it keeps happening on my live server.
It would be great if someone had any suggestions on what I'm doing wrong or what I happening. I did this 1000 of times the only difference with other times is that I prefill the form, but I also have it when I turn that feature off.
Edit: as requested my code below.
Note: I replaced some keywords like routes, redirects and relation names.
Request class
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class RegistrationRequest extends Request
{
/**
* 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 [
'hash' => 'required|exists:users,hash',
'language' => 'required|in:NLD,FRA',
'title' => 'required',
'firstName' => 'required',
'lastName' => 'required',
'street' => 'required',
'postalCode' => 'required',
'city' => 'required',
'email' => 'required|email',
'birthday' => 'required|date_format:d/m/Y',
'tac' => 'required'
];
}
}
Controller method index.
public function index($hash)
{
$user = $this->user->byHash($hash);
if(is_null($user)) {
return redirect()->to('/');
}
if(! is_null($user->myRelationName)) {
return redirect()->route('thanks');
}
return view('my-view', ['user' => $user]);
}
Controller method store
public function store(RegistrationRequest $request)
{
$user = $this->user->byHash($request->hash);
$user->language = $request->language;
$user->title = $request->title;
$user->firstName = $request->firstName;
$user->lastName = $request->lastName;
$user->street = $request->street;
$user->postalCode = $request->postalCode;
$user->city = $request->city;
$user->email = $request->email;
$user->birthday = $request->birthday;
$user->tac = true;
$user->ip = $this->getRemoteIPAddress();
$user->save();
return redirect()->route('my-route', ['hash' => $request->hash]);
}
Vieuw.blade.php
#extends('layouts.master')
#section('content')
<div class="bottom">
<div class="form-container">
<h2>{{trans('merci.register_maintitle')}}</h2>
<p>{!!trans('merci.register_p1')!!}</p>
<p>{!!trans('merci.register_p2')!!}</p>
<h3>{!!trans('merci.register_h3')!!}</h3>
{{ Form::open(['route' => 'register.store', 'class' => 'form', 'id' => "register-form"]) }}
{{Form::hidden('hash', $user->hash, array("id" => "hash"))}}
<div class="form-field-wrap form-group language {{$errors->has('language') ? 'has-error' : null}}">
{{ Form::label('language', trans('merci.register_language'), array('class' => 'form-field-text-label radio-label'))}}
{{ Form::radio('language', trans('merci.register_language1_value'), ($user->language == trans('merci.register_language1_value')) ? true : false, array('id' => 'nl-rad')) }}
<span>{{trans('merci.register_language1_label')}}</span>
{{ Form::radio('language', trans('merci.register_language2_value') , ($user->language == trans('merci.register_language2_value')) ? true : false, array('class' => 'radio', "id"=> 'fr-rad')) }}
<span>{{trans('merci.register_language2_label')}}</span>
</div>
<div class="form-field-wrap form-group title {{$errors->has('title') ? 'has-error' : null}}">
{{ Form::label('title', trans('merci.register_title'), array('class' => 'form-field-text-label radio-label'))}}
{{ Form::radio('title', trans('merci.register_title1_value'), ($user->title == trans('merci.register_title1_value')) ? true : false) }}
<span>{{trans('merci.register_title1_label')}}</span>
{{ Form::radio('title', trans('merci.register_title2_value'), ($user->title == trans('merci.register_title2_value')) ? true : false, array('class' => 'radio')) }}
<span>{{trans('merci.register_title2_label')}}</span>
</div>
<div class="form-field-wrap form-group lastName {{$errors->has('lastName') ? 'has-error' : null}}">
{{ Form::label('lastName', trans('merci.register_lastName'), array('id' => 'lastName', 'class' => 'form-field-text-label'))}}
{{ Form::text('lastName', $user->lastName, array('class' => 'form-field-text-input')) }}
</div>
<div class="form-field-wrap form-group firstName {{$errors->has('firstName') ? 'has-error' : null}}">
{{ Form::label('firstName', trans('merci.register_firstName') , array('class' => 'form-field-text-label'))}}
{{ Form::text('firstName', $user->firstName, array('class' => 'form-field-text-input')) }}
</div>
<div class="extramargin form-field-wrap form-group street {{$errors->has('street') ? 'has-error' : null}}">
{{ Form::label('street', trans('merci.register_street'), array('class' => 'form-field-text-label'))}}
{{ Form::text('street', $user->street, array('class' => 'form-field-text-input big')) }}
</div>
<div class="smallerpostal form-field-wrap form-group postalCode {{$errors->has('postalCode') ? 'has-error' : null}}">
{{ Form::label('postalCode', trans('merci.register_postalCode'), array('class' => 'form-field-text-label smaller-label'))}}
{{ Form::text('postalCode', $user->postalCode, array('class' => 'form-field-text-input smaller')) }}
</div>
<div class="smallercity form-field-wrap form-group city {{$errors->has('city') ? 'has-error' : null}}">
{{ Form::label('city', trans('merci.register_city'), array('class' => 'form-field-text-label smal-label'))}}
{{ Form::text('city', $user->city, array('class' => 'form-field-text-input smal')) }}
</div>
<div class="extramargin form-field-wrap form-group email {{$errors->has('email') ? 'has-error' : null}}">
{{ Form::label('email', trans('merci.register_email'), array('class' => 'form-field-text-label'))}}
{{ Form::email('email', $user->email, array('class' => 'form-field-text-input ')) }}
</div>
<div class="form-field-wrap form-group birthday {{$errors->has('birthday') ? 'has-error' : null }} ">
{{ Form::label('birthday', trans('merci.register_birthday'), array('class' => 'form-field-text-label', "id" => "birthdate"))}}
{{ Form::text('birthday', $user->birthday, array('class' => 'form-field-text-input', "id"=>"datepicker")) }}
</div>
<div class="check form-field-wrap form-group tac {{$errors->has('tac') ? 'has-error' : null }}">
{{ Form::checkbox('tac', trans('merci.register_tac_value'), false, array('class' => 'form-field-checkbox', "id" => "tac"))}}
{{ Form::label('tac', trans('merci.register_tac_label'), array('class' => 'form-field-error-label')) }}
<span>{!!trans('merci.register_tac_label_link')!!}</span>
</div>
#if (count($errors) > 0)
<div id="error server" style='display:none;'>
#else
<div id="error" style='display:none;'>
#endif
<p class="error">{{trans('merci.register_error')}}</p>
</div>
{!! Form::submit(trans('merci.register_submit'), array('class' => 'btn-main btn')) !!}
{{ Form::close() }}
<small>{{trans('merci.register_mandatory')}}</small>
</div>
</div>
<script src="{{ asset('js/validate.js') }}"></script>
#stop
I don't know if your routes are inside the web middleware, but if you are losing the $errors bag variable, that could be the cause.
Any routes not placed within the web middleware group will not have
access to sessions and CSRF protection (See the default routes file).
When $errors variable is bound to the view by the web middleware group this variable will always be available in your views. (See Displaying The Validation Errors).
// Make sure any routes that need access to session features are placed within
Route::group(['middleware' => 'web'], function () {
Route::get('/', 'MyController#index');
});
Also, I would use the old helper in the blade template to retrieve flashed input from the previous request.
{{ old('username') }}

Laravel 4 creating form open with database

I have problem with my creating offers form.
Page displays nicely, but when you add data and after sending form, page gives error.
Laravel 4
enter link description here
My routes:
Route::get('/user/{username}', array(
'as' => 'profile-user',
'uses' => 'ProfileController#user'
));
Route::get('/profile/offers', array(
'as' => 'profile-offers',
'uses' => 'OffersController#offers'
));
Route::post('/profile/offers', array(
'as' => 'profile-offers',
'uses' => 'OffersController#postDestroy' ));
Route::post('/profile/offers/create', array(
'as' => 'profile-create',
'uses' => 'OffersController#postCreate'
));
My controller
controllers/OffersController.php
<?php
class OffersController extends BaseController {
public function __construct() {
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('user');
}
public function Offers() {
$offers = array();
foreach(Category::all() as $category) {
$categories[$category->id] = $category->name;
}
//return View::make('offers.index')
return View::make('profile.offers')
->with('offers', Offer::all())
->with('categories', $categories);
}
public function postCreate() {
$validator = Validator::make(Input::all(), Offer::$rules);
if($validator->passes()){
$offer = new Offer;
$offer->category_id = Input::get('category_id');
$offer->title = Input::get('title');
$offer->description = Input::get('description');
$offer->price = Input::get('price');
$image = Input::file('image');
$filename = date('Y-m-d-H:i:s').'.'.$image->getClientOriginalName();
$path = public_path('img/offers/' . $filename);
Image::make($image->hetRealPath())->resize(468, 249)->save('public/img/offers/'.$filename);
$offer->image = 'img/offers/'.$filename;
$offer->save();
//return Redirect::route('profile-user', Auth::user()->username);
return Redirect::to('profile.offers.create') //
->with('global', 'Dodano ogloszenie');
}
//return Redirect::route('profile-user', Auth::user()->username);
return Redirect::to('profile.offers')
->with('global', 'Cos poszlo nie tak')
->withErrors($validator)
->withInput();
}
public function postDestroy(){
$offer = Offer::find(Input::get('id'));
if ($offer){
File::delete('public/'.$offer->image);
$offer->delete();
//return Redirect::route('profile-user', Auth::user()->username);
return Redirect::to('profile.offers.destroy')
->with('global', 'Skasowano ogłoszenie');
}
}
public function postToggleAvailability() {
$offer = Offer::find(Input::get('id'));
if ($offer){
$offer->availability = Input::get('availability');
$offer->save();
//return Redirect::route('profile-user', Auth::user()->username);
return Redirect::to('profile.offers')->with('global', 'Zaktualizowano')
->with('global', 'Zaktualizowano');
}
//return Redirect::route('profile-user', Auth::user()->username);
return Redirect::to('profile.offers')->with('global', 'zle ogloszenie')
->with('global', 'Zaktualizowano');
}
}
my views
views/profile/offers
<h1>Offerts</h1>
<ul>
#foreach($offers as $offer)
<li>
{{ HTML::image($offer->image, $offer->title, array('width'=>'50')) }}
{{ $offer->title }} -
{{ Form::open(array('url'=>'profile/offers/destroy', 'class'=>'form-inline')) }}
{{ Form::hidden('id', $offer->id) }}
{{ Form::submit('delete') }}
{{ Form::close() }} -
{{ Form::open(array('url'=>'profile/offers/toggle-availability', 'class'=>'form-inline')) }}
{{ Form::hidden('id', $offer->id) }}
{{ Form::select('availability', array('1'=>'In Stock', 'O'=>'Out of Stock'), $offer->availability)}}
{{ Form::submit('Update') }}
{{ Form::close() }}
</li>
#endforeach
</ul>
<h2>Create new offers</h2><hr>
#if($errors->has())
<div id="form-errors">
<p>the following errors have occurred:</p>
<ul>
#foreach($errors->all() as $error)
<li>{{ error }}</li>
#endforeach
</ul>
</div>
#endif
{{ Form::open(array('url'=>'profile/offers', 'method' => 'POST', 'files'=>true)) }}
<p>
{{ Form::label('category_id', 'Category') }}
{{ Form::select('category_id', $categories) }}
</p>
<p>
{{ Form::label('title') }}
{{ Form:: text('title', null, array('class' => 'form-control', 'required' => '')) }}
</p>
<p>
{{ Form::label('description') }}
{{ Form:: text('description', null, array('class' => 'form-control', 'required' => '')) }}
</p>
<p>
{{ Form::label('price') }}
{{ Form::text('price', null, array('class'=>'form-price')) }}
</p>
<p>
{{ Form::label('image', 'Choose an image') }}
{{ Form::file('image') }}
</p>
{{ Form::submit('Create offers', array('class'=>'secondary-cart-btn')) }}
{{ Form::close() }}
My models/Offer.php
<?php
class Offer extends Eloquent {
protected $fillable = array('category_id,', 'title', 'description', 'price', 'availability', 'image');
public static $rules = array(
'category_id'=>'required|integer',
'title'=>'required|min:2',
'description'=>'required|min:20',
'price'=>'required|numeric',
'availability'=>'integer',
'image'=>'required|image|mimes:jpge,jpg,bmp,png,gif'
);
public function category() {
return $this->belongsTo('Category');
}
}
You don't have the route for the POST request and have not correctly set-up the routes for the rest of your controller actions, hence the 404 exception. Form submissions have method of POST unless explicitly specified to GET. You also have to properly set the controller action you want. Laravel will not know profile/offers/destroy should route to postDestroy() unless you tell it to.
Route::post('/profile/offers/destroy', array(
'as' => 'profile-destroy',
'uses' => 'OffersController#postDestroy'
));
You have to do this each for your controller action.

Laravel, Swiftmailer error: Class does not exist

I have a form
{{ Form::open(array('route' => 'submit.contactAct', 'class' => 'form-horizontal')) }}
{{ Form::label('fremail', trans('people.email')) }} <span class="req">*</span>
{{ Form::text('fremail', Input::old('fremail'), array('class' => 'form-control')) }}
{{ $errors->first('fremail', '<span class="help-block alert alert-danger">:message</span>') }}
{{ Form::label('comment', trans('people.contact messages')) }} <span class="req">*</span>
{{ Form::textarea('comment', Input::old('comment'), array('class' => 'form-control', 'rows' => 5)) }}
{{ $errors->first('comment', '<span class="help-block alert alert-danger">:message</span>') }}
{{ Form::hidden('email', $actor['email']) }}
{{ Form::submit('Submit', array('class' => 'btn btn-success')) }}
{{ Form::close() }}
It has three fields: a from email field ('fremail'), a 'comment' field and a 'email' field which grabs the email from the 'actor' database table.
My submit function looks like this. It validates the data and sends it to a send function. It also creates a $star variable and stores the 'email' field. For this example the email stored in $star=actorname#gmail.com
public function submitContactAct()
{
//prepare input
$input = Input::except('_token');
$star = Input::get('email');
if ( ! $this->validator->with($input)->passes())
{
return Redirect::back()->withErrors($this->validator->errors())->withInput($input);
}
$this->mailer->sendContactUsAct($input, $star);
return Redirect::back()->withSuccess( trans('main.contact success') );
}
This is my send email function, I have set the setReplyTo to the $star variable, but I keep receiving
Class actorname#gmail.com does not exist
public function sendContactUsAct(array $input, $star)
{
//get contact us email for db
$options = App::make('Options');
$email = $options->getContactEmail();
if ($email)
{
Mail::send('Emails.ContactAct', $input, $star, function($message) use($email)
{
$message->setReplyTo($star);
$message->to($email)->subject( trans('main.contact email subject') );
});
}
}
I don't know why it is thinking a the string in $star is a class.
Try this
Mail::send('Emails.ContactAct', $input, function($message) use ($email, $star)
{
$message->setReplyTo($star);
message->to($email)->subject( trans('main.contact email subject') );
});
Variable $star has to be passed using use because it's not in scope of your closure.

Laravel4: upload a photo

I'm stuck..
I want to add to give the possibity to add a new photo through a form.
I have the Photo resource properly set up.
The table photo with: id, title, caption, path:string.
This is the form that i made until now in the view photo.create:
{{ Form::open(array('route' => 'photos.store'),'image/save', array('files'=> true)) }}
{{ Form::label('title', 'Title: ') }}
{{ Form::text('title') }}
{{ Form::label('caption', 'Caption: ') }}
{{ Form::textarea('caption') }} <br>
{{ Form::submit('Add Photo', array('class' => 'btn btn-primary' )) }}
{{ Form::close() }}
How can i add a button thanks to which select a new file?
Thank you!!
EDIT:
This is the simple store method i made until now:
public function store()
{
$input = Input::all();
$rules = array('title' => 'required', 'path' => 'required');
$validation = Validator::make($input, $rules);
if ($validation->passes())
{
$photo = new Photo();
$photo->title = $input['title'];
$photo->caption = $input['caption'];
$photo->path = $input['path'];
$photo->save();
return Redirect::route('photos.index');
}
return Redirect::back()->withInput()->withErrors($validation)->with('message','There were validation message');
}
How can i put correctly there that implementation to retrieve the file and store in the folder located in public/img ?
And then how can i save that path and put into $photo->path ?
Thank you very much!!
Use Form::file('image')
Then, you can retrieve your uploaded file with Input::file('image') and move it to a destination with Input::file('file')->move(YOUR_DESTINATION_PATH);
References : http://laravel.com/docs/requests#files and http://laravel.com/docs/html#file-input
edit :
To store your uploaded file to public/img : Input::file('file')->move(base_path() . '/public/img');
Storing path in database :
$photo->path = base_path() . '/public/img' . Input::file('file')->getClientOriginalName(); // if you want your real path on harddrive
or
$photo->path = URL::to('img/' . Input::file('file')->getClientOriginalName()); // if you want an exploitable path for http render
second edit
See my correction on your form http://paste.laravel.com/KX9
#extends('master')
#section('blog')
<div class="span12 well">
{{ link_to_route('photos.index', 'Back to index') }}
</div>
<div class="span12 well">
{{ Form::open(array('route' => 'photos.store', 'files'=> true)) }}
{{ Form::label('title', 'Title: ') }}
{{ Form::text('title') }}
{{ Form::label('caption', 'Caption: ') }}
{{ Form::textarea('caption') }}
{{ Form::label('image', 'Image: ') }}
{{ Form::file('image') }}
<br>
{{ Form::submit('Add Photo', array('class' => 'btn btn-primary' )) }}
{{ Form::close() }}
<br><br>
#if($errors->any())
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
#endif
</div>
#stop
you can use Form::file('image');
see http://laravel.com/docs/html#file-input
{{ Form::open(array('action' => 'HomeController#upload', 'files'=>true)) }}
{{ Form::label('image', 'Upload Image')}}
{{ Form::file('image') }}
{{ Form::submit('Submit') }}
{{ Form::close() }}
Step2:
public function upload(){
$image = Input::file('image');
$savepath = 'public/uploads/';
$filename = $image->getClientOriginalName();
Input::file('image')->move($savepath, $filename);
}
Final Step:
Route::get('/upload' function()
{
return View::make('upload');
});
Route::post('/upload', 'HomeController#upload');

Categories