i'm a newbie to laravel framework and i just find it's so hard to understanding laravel form usability.... so here is some issue that i face into
First my dropdown should be having my categories name and at the very end of dropdown it will be my specific dropdown add new categories that when i selected will trigger my javascript... and im here is my form code
{{ Form::select('kategori',KategoriArtikel::lists('name','id'),Input::old('kategori'),array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}
that will show right value from my database also with right selected value but it's missing my specific dropdown, so i tried to add like this
<?php
$tambah = array('tambah' => 'Tambah Kategori Baru');
$list = array_merge(KategoriArtikel::lists('name','id'),$tambah);
?>
{{ Form::select('kategori',array(KategoriArtikel::lists('name','id'),$tambah),Input::old('kategori'),array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}
but it will generate 2 with different layout (which ugly) and not showing right selected value, so i tried other way
<?php
$tambah = array('tambah' => 'Tambah Kategori Baru');
$list = array_merge(KategoriArtikel::lists('name','id'),$tambah);
?>
{{ Form::select('kategori',$list,Input::old('kategori'),array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}
and it not generate and my dropdown layout is what it supposed to be but now the is not from my table id anymore but just sequential number 0,1,2,3,etc
any solution to that?
Second problem is when i submit my form, it's not working, my field in table is int and when i submit it just not saving/updating so i tried to dd(Input::all()) and my dropdown is returning string of selected option value and it's not saved into my table... so why is that? it also not working for my boolean field that contain tinyint(1)... so basicly all value returning string.
its returning this
array(8) { ["_method"]=> string(3) "PUT" ["_token"]=> string(40) "IspUKdCETMe4Nn3pDI43GI7aJKQfXpupJvQAy1k6" ["simpan"]=> string(6) "simpan" ["judul"]=> string(18) "test "kegiatan" 21" ["kategori"]=> string(1) "9" ["kategori_baru"]=> string(0) "" ["status"]=> string(1) "0" ["content"]=> string(1012) "
I used--and I don't put my arm round your waist,' the Duchess said to herself. 'Of the mushroom,' said the Dormouse, and repeated her question. 'Why did they live at the sides of it, and then turned to the tarts on the twelfth?' Alice went on, 'that they'd let Dinah stop in the shade: however, the moment he was obliged to have wondered at this, but at the Caterpillar's making such a capital one for catching mice--oh, I beg your pardon!' cried Alice hastily, afraid that she had read about them in books, and she at once without waiting for turns, quarrelling all the children she knew, who might do something better with the time,' she said to herself; 'I should like to drop the jar for fear of killing somebody, so managed to swallow a morsel of the house, quite forgetting her promise. 'Treacle,' said the Gryphon: and it sat for a few minutes to see if she had grown up,' she said this, she looked down at her as she wandered about for it, you know--' (pointing with his head!' she said,.
" }
and as you can see ['kategori'] is supposed to be making my field kategori in my table to be 9 but it's not changing anything in my database
well i laravel simplicity but it's very confusing when working with database (can't find any documentation example related to databas retrieving data and so on)
edit:
this is my controller
public function update($id)
{
$artikel = Artikel::findOrFail($id);
if(Input::get('simpan')){
//dd(Input::all());
$validator = Validator::make($data = Input::all(), Artikel::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
$judul = Input::get('judul');
$artikel->update($data);
return Redirect::route('admin.artikels.index')->with('message', 'Artikel ' .$judul. ' Telah berhasil di ubah.');
}elseif(Input::get('batal')){
return $this->index();
}
}
and here is my view
#extends('admin._layouts.admin')
#section('content')
{{ Form::model($artikel, array('route' => array('admin.artikels.update',$artikel->id), 'method' => 'put')) }}
<div class="panel panel-default">
<!--button-->
<div class="panel-heading tooltip-demo">
{{ Form::submit('Simpan',array('class' => 'btn btn-primary', 'data-toggle' => 'tooltip',
'data-placement' => 'top','title' => 'Menyimpan artikel' )) }}
{{ Form::submit('Batal',array('class' => 'btn btn-default', 'data-toggle' => 'tooltip',
'data-placement' => 'top','title' => 'Batal menambah artikel dan kembali ke halaman kelola artikel' )) }}
</div>
<!--/button-->
<div class="panel-body">
<!--judul-->
<div class="col-lg-10">
<div class="form-group">
{{ Form::label('Judul Artikel') }}
{{ Form::text('judul',null,array('class' => 'form-control', 'placeholder' => 'Silahkan masukkan judul artikel'))}}
{{ $errors->first('judul', '<p class="error">:message</p>') }}
</div>
</div>
<!--/judul-->
<!--kategori-->
<div class="col-lg-4">
<div class="form-group">
{{ Form::label('Kategori') }}
<?php
$tambah = array('tambah' => 'Tambah Kategori Baru');
$list = array_merge(KategoriArtikel::lists('name','id'),$tambah);
?>
{{ Form::select('kategori',$list,'Pilih Kategori Artikel',array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}
</div>
</div>
<!--/kategori-->
<!--kategori baru-->
<div class="col-lg-4" id="pilihan" style="display:none;">
<div class="form-group">
{{ Form::label('Kategori Baru') }}
{{ Form::text('kategori_baru',null,array('class' => 'form-control', 'placeholder' => 'Silahkan masukkan kategori baru',
'maxlength' => '30'))}}
</div>
</div>
<!--/kategori baru-->
<!--status-->
<div class="col-lg-4">
<div class="form-group">
{{ Form::label('Status') }}
{{ Form::select('status',array('0' => 'Tidak diterbikan', '1' => 'Terbitkan'),null, array('class' => 'form-control')) }}
</div>
</div>
<!--/status-->
<!--artikel pilihan-->
<div class="col-lg-5">
<div class="form-group">
{{ Form::label('Artikel Pilihan') }}
<div class="input-group">
<span class="input-group-addon">
{{ Form::checkbox('pilihan','1',true,array('id' => 'artikelpilihan')) }}
</span>
{{ Form::text('null','Tidak',array('class' => 'form-control', 'id' => 'artikeltext' ,'disabled' => 'true'))}}
</div>
</div>
</div>
<!--/artikel pilihan-->
<!--content-->
<div class="col-lg-12">
{{ Form::label('Isi Artikel') }}
{{ Form::textarea('content',null,array('style' => 'height:300px')) }}
{{ $errors->first('content', '<p class="error">:message</p>') }}
</div>
<!--/content-->
</div>
</div>
{{ Form::close() }}
{{ HTML::script('js/tinymce/tinymce.min.js') }}
<script type="text/javascript">
tinymce.init({
selector: "textarea",
theme: "modern",
skin: 'light',
plugins: [
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table contextmenu directionality",
"emoticons template paste textcolor colorpicker textpattern"
],
toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
toolbar2: "print preview media | forecolor backcolor emoticons | fontselect fontsizeselect",
image_advtab: true,
templates: [
{title: 'Test template 1', content: 'Test 1'},
{title: 'Test template 2', content: 'Test 2'}
],
file_browser_callback: RoxyFileBrowser
});
function RoxyFileBrowser(field_name, url, type, win) {
var roxyFileman = '../../../../public/js/tinymce/plugins/fileman/index.html?integration=tinymce4';
if (roxyFileman.indexOf("?") < 0) {
roxyFileman += "?type=" + type;
}
else {
roxyFileman += "&type=" + type;
}
roxyFileman += '&input=' + field_name + '&value=' + document.getElementById(field_name).value;
tinyMCE.activeEditor.windowManager.open({
file: roxyFileman,
title: 'File Manager',
width: 800,
height: 480,
resizable: "yes",
plugins: "media",
inline: "yes",
close_previous: "no"
}, { window: win, input: field_name });
return false;
}
</script>
#stop
If I have understood your problem correctly, you want to populate a dropdown based on values from database and also want to display "Select A Category" in the category dropdown. And currently your dropdown values are not being saved.
To populate the dropdown put the following code your controller's method through which you are loading the view file.
$data['kategori'] = KategoriArtikel::lists('name','id');
$data['kategori'][''] = 'Select a kategori';
return View::make('YOUR_VIEW_FILE', $data);
In your view file, simple use the following, (same rules apply for other select dropdowns):
{{ Form::select('kategori', $kategori , Input::old('kategori'), array('id' => 'category', 'class' => 'form-control', )) }}
The above code basically generates something like this:
<select id="category" class="form-control">
<option value="">Select a Kategori</option>
<option value="1">First Kategori</option>
<option value="2">Second Kategori</option>
</select>
The third parameter in Form::select() expects a default option value, if you provide a value it will compare with option values and display the matched one as selected.
And Your form's method shouldn't be 'method' => 'POST' not 'method' => 'put'
I am using the following code in cases such this you described. In my controller i have
public function create()
{
$category1= Category1::lists('category1','id');
$category2= Category2::lists('category2','id');
//you can have many select lists in an form
return
View::make('someobject.create',compact('category1','category2'));
}
and in my someobject.create view
{{Form::open(array('route'=>'someobject.store'))}}
<div>
{{Form::label('category1', 'category1')}}
{{Form::select('category1',array('' => 'Please select') + $category1) }}
<span class="errors">{{$errors->first('category1')}}</span>
{{Form::label('category2', 'category2')}}
{{Form::select('category2',array('' => 'Please select') + $category2) }}
<span class="errors">{{$errors->first('category2')}}</span>
</div>
<div>
{{Form::submit('Save',array('class' => 'btn'))}}
</div>
Related
Here is what i'm trying to do :
I have a classic Folder entity which contains Sku entities in a OneToMany relation as an ArrayCollection. So far so good.
I want the FolderType to dynamically create as many Skus as I want in it. For that, I followed the Symfony fast track method to generate prototypes in javascript. Works great.
Now, in this folder form, "skus" are an array collection of entities. In the SkuType, I have files to uploads. Here are the forms (Folder and Sku) :
$builder
->add('norlogReference', TextType::class, [
'label' => 'Référence du dossier'
])
->add('skus', CollectionType::class, [
'entry_type' => SkuType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'prototype' => 'skus'
]);
As for the SkuType, here are my upload fields :
->add('picture_1', FileType::class, [
'label' => 'Image 1 du produit',
'mapped' => false,
'required' => false,
'attr' => ['accept' => 'image/*']
])
->add('picture_2', FileType::class, [
'label' => 'Image 2 du produit',
'mapped' => false,
'required' => false,
'attr' => ['accept' => 'image/*']
])
Here is the controller recieving the form :
/**
* #Route("/new", name="folder_new")
*/
public function new(Request $request): Response
{
$entityManager = $this->getDoctrine()->getManager();
$norlogFolder = new NorlogFolder();
$form = $this->createForm(NorlogFolderType::class, $norlogFolder);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
foreach ($norlogFolder->getSkus() as $sku) {
I want to get both file objects here, pass them in handleUploadedFile(), and use $sku->setPicture1() and setPicture2 with the $newfileName returned by the private method.
$sku->setFolder($norlogFolder);
$sku->setSKU($norlogFolder->getNorlogReference() . '-' . $sku->getSKU());
}
$entityManager->persist($norlogFolder);
$entityManager->flush();
return $this->redirectToRoute('folder_edit', ['id' => $norlogFolder->getId()]);
}
return $this->render('folder/new.html.twig', [
'form' => $form->createView(),
]);
}
and the little private method I want to use in order to handle the file :
private function handleUploadedFile(UploadedFile $uploadedFile): string
{
$destination = $this->getParameter('kernel.project_dir').'/public/uploads/sku_medias';
$originalFilename = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
$newFilename = $originalFilename . '-' . uniqid() . '.' . $uploadedFile->guessExtension();
$uploadedFile->move(
$destination,
$newFilename
);
return $newFilename;
}
And the folder form view :
{{ form_start(form, {
attr: {
class: 'sku-form'
}
}) }}
<div class="form-group">
{{ form_row(form.norlogReference, {
attr: {
placeholder: 'ex: XOTP-25',
class: 'sku-form-input'
}
}) }}
</div>
<div class="form-group sku-row skus" data-prototype="{{ form_widget(form.skus.vars.prototype)|e('html_attr') }}">
{% if form.skus|length > 0 %}
{% for sku in form.skus %}
<div class="row sku-bloc bg-light">
<div class="field-title">
<p class="display-3 text-center">Produit #{{ loop.index }}</p>
<a href="{{ path('sku_delete', {id: sku.vars.data.id}) }}"
class="btn bg-danger btn-sku-remove"><i class="fas fa-trash-alt"></i></a>
</div>
<span class="btn btn-secondary form-extend-btn">Voir</span>
<div class="col-12 sku-fields-bloc">
<div class="form-control">
{{ form_row(sku.SKU, {
attr: {
placeholder: 'ex: XVF-25663',
class: 'sku-form-input'
}
}) }}
</div>
<div class="container">
<div class="row">
{{ form_label(sku.marque) }}
{{ form_widget(sku.marque, {
attr: {
class: 'sku-form-input'
}
}) }}
{{ form_label(sku.taille) }}
{{ form_widget(sku.taille, {
attr: {
class: 'sku-form-input'
}
}) }}
{{ form_label(sku.designation) }}
{{ form_widget(sku.designation, {
attr: {
class: 'sku-form-input'
}
}) }}
{{ form_label(sku.couleur) }}
{{ form_widget(sku.couleur, {
attr: {
class: 'sku-form-input'
}
}) }}
{{ form_label(sku.etat) }}
{{ form_widget(sku.etat, {
attr: {
class: 'sku-form-input'
}
}) }}
{{ form_label(sku.composition) }}
{{ form_widget(sku.composition, {
attr: {
class: 'sku-form-input'
}
}) }}
</div>
</div>
<div class="form-control mt-3">
{{ form_row(sku.picture_1, {
attr: {
placeholder: 'Image 1',
class: 'sku-form-input'
}
}) }}
</div>
<div class="form-control mt-3">
{{ form_row(sku.picture_2, {
attr: {
placeholder: 'Image 2',
class: 'sku-form-input'
}
}) }}
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="row">
<div class="col-12 mt-4">
<p class="p-3 bg-info">Pas encore de {{ form_label(form.skus) }} ajoutés</p>
{{ form_widget(form.skus) }}
</div>
</div>
{% endif %}
</div>
<div class="row">
<div class="col-4">
<button type="button" class="btn btn-primary btn-nav w-100 mt-2 mb-2 add_item_link"
data-collection-holder-class="skus">
Ajouter Sku
</button>
</div>
<div class="col-4">
<button type="submit"
class="btn btn-success btn-nav w-100 mt-2 mb-2">{{ button_label|default('Enregistrer') }}</button>
</div>
<div class="col-4">
<a href="{{ path('folder_list') }}"
class="btn btn-primary btn-nav w-100 mt-2 mb-2">Retour liste</a>
</div>
</div>
{{ form_end(form) }}
So the question is : how to get these picture_1 and 2 objects (and not path which I already have by remapping them to true), by Sku, in the controller side, in order to handle the files as usual ?
I tried :
$request->files->get() (result = null, and I have the enctype right in the form)
$sku->getPicture_1() (result = temporary linux path, but is there a simple way to retrieve the file from that, and on every OS ?)
Trying to access the $form from inside the sku loop (result = nada)
$request->get('picture_1') and that + ->getData()
Various weird tries I forgot which gave me nothing
I might miss something obvious here, but I can't think properly on this project anymore.
Please don't mind the necessary refactoring for now =) Ty !
With 'mapped' => false, you need to handle the collection of uploads like this:
if ($form->isSubmitted() && $form->isValid()) {
foreach ($form->get('skus') as $formChild)
{
// Get the unmapped picture fields
$uploadedPicture1 = $formChild->get('picture_1')->getData();
$uploadedPicture2 = $formChild->get('picture_2')->getData();
// Get the sku
$sku = $formChild->getData();
// Upload the pictures
$picture1Filename = $this->handleUploadedFile($uploadedPicture1);
$picture2Filename = $this->handleUploadedFile($uploadedPicture2);
// Set the new filenames onto the sku
$sku->setPicture1($picture1Filename);
$sku->setPicture2($picture2Filename);
// Your original code
$sku->setFolder($norlogFolder);
$sku->setSKU($norlogFolder->getNorlogReference() . '-' . $sku->getSKU());
}
}
$entityManager->persist($norlogFolder);
$entityManager->flush();
return $this->redirectToRoute('folder_edit', ['id' => $norlogFolder->getId()]);
}
Edit: do check if a picture was actually uploaded, as in the other answer. :-)
Your picuter_1 and picture_2 are mapped: false.
That means, you have to use ->getData() (or maybe ->getNormData()) on each SkuType or your NorlogFolderType
instead of looping through SKUs entities collection, loop through sku formtypes and get the data directly from 'picture_1' and 'picture_2' field
if ($form->isSubmitted() && $form->isValid())
{
if ($form->has('skus'))
{
foreach ($form->get('skus') as $skuForm)
{
// always check if field named 'picture_1' is there
if ($skuForm->has('picture_1'))
{
/** #var \Symfony\Component\HttpFoundation\File\UploadedFile $firstPic */
$firstPic = $skuForm->get('picture_1')->getData();
//todo: maybe check if null
$picOne = $this->handleUploadedFile($firstPic);
}
// do the same with picture_2 (and others if any)
}
}
}
I want to echo the selected value when I edit a specific resource in my table. When I edit the specific resource it should display the current data in my dropdown but in the real scenario it displays the first one on the list which is wrong. So how can I echo the selected value in the options of the dropdown using blade in laravel?
Here is some sample of my code in the view below
<!-- Shows Field -->
<div class="form-group col-sm-6">
{!! Form::label('show_id', 'Shows:') !!}
{!! Form::select('show_id', $shows, $shows, ['class' => 'form-control input-md','required'])!!}
</div>
{{-- {{ $channelshows->channel->name }} --}}
<!-- Client Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('channel_id', 'Channels:') !!}
{!! Form::select('channel_id', $channel, $channel, ['class' => 'form-control input-md','required'])!!}
</div>
<!-- Submit Field -->
<div class="form-group col-sm-12">
{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
Cancel
</div>
and here is the code in my controller below.
public function edit($id)
{
$channelshows = $this->channelshowsRepository->findWithoutFail($id);
$shows = Show::pluck('name', 'id');
$channel = Channel::pluck('name', 'id');
if (empty($channelshows)) {
Flash::error('Assigned show not found');
return redirect(route('admin.channelshows.index'));
}
return view('admin-dashboard.channelshows.edit', compact('shows', $shows), compact('channel', $channel))->with('channelshows', $channelshows);
}
Everything here works fine even if I updated the specific resource. I just want to auto populate or select the current value of the resource that I will update because when I edit the specific resource it shows the first one on the list.
Am I going to use an #if statement in blade? But how can I do it using the blade template in my select form. Can somebody help me?
Appreciate if someone can help.
Thanks in advance.
Here is an example:
Open form:
{{ Form::model($service, array('route' => array('services.update', $service->id))) }}
Select form field:
<div class="form-group">
{{ Form::label('Related Agreement') }}
{{ Form::select('agreement', $agreementsList, null, array('class'=>'form-control', 'placeholder'=>'Please select ...')) }}
</div>
In Controller:
$agreementsList = Agreement::all()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('name', 'id');
(Include this when passing data to your view)
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') }}
I'm having problems populating values of my inputs when I have eloquent queries using with(
Controller:
private $viewPath = "pages.person.";
public function edit($id)
{
$person = Person::where('id', '=', $id)->with('Email', 'Phone', 'User', 'Client', 'JuridicPerson.TypeActivities')->firstOrFail();
$this->setData('person', $person); // Set information to be used in the creation of `views` and `nest.views`.
$this->setData('users', User::lists('name', 'id'), ['0' => 'Select…']); // Set information to be used in the creation of `views` and `nest.views`.
return $this->view($this->viewPath.'edit'); // Register a new view.
}
My views are made in a way that I share the form between my edit and my create. So I have create.blade.php, edit.blade.php and both made a call to form.blade.php this I can not change.
My edit.blade
{{ Form::model($person, array('method' => 'PATCH', 'class' => 'defaultForm', 'route' => array('person.update', $person->id))) }}
#include('pages.person.form')
{{ Form::close() }}
My form.blade
<!-- This input brings the correct value -->
<div class="row">
<div class="col-md-12">
{{ Form::input('name', 'name', null, ['class' => 'form-control', 'placeholder' => 'Nome', 'maxlength' => 35, 'required', 'autofocus']) }}
</div>
</div>
<!-- This input value is empty -->
<div class="row">
<div class="col-md-12">
{{ Form::textarea('Client[observation]', null, ['class' => 'form-control', 'placeholder' => 'Observations']) }}
</div>
</div>
But if I add this piece of code anywhere in my html, I get the correct value in client...
{{ $person->client }}
Not sure what should I do to fix my code, the data is correct, when I print the data (above code) the inputs output the correct value (but I can't have the the return printed on the screen for the user).
What I need is to print the correct value into the correct input.
Use client rather than Client when loading that relationship.
When you did {{ $person->client }} it had the side effect of loading that client relationship so it could be used.
When loading relationships, you should use the name of the function, exactly, that's responsible for setting up those relationships.
I'm building a form using Laravel 4 and Twitter Bootstrap 3 and I want to error messages to appear next to the field. This is the solution that I came up with but it ends up being 15 lines of code per field.
#section('content')
<div class="container">
<h1>Edit User</h1>
{{ Form::model($user, array('route' => array('users.update', $user->id), 'method' => 'PUT', 'class' => 'form-horizontal')) }}
{{-- First Name field --}}
{{-- Start a form group. If there any errors, then highlight the field red. --}}
<div class="form-group {{ $errors->has('first_name') ? 'has-error' : '' }}">
{{-- Display the label and the field. --}}
{{ Form::label('first_name', 'First Name', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::text('first_name', NULL, array('class' => 'form-control', 'placeholder' => 'First Name')) }}
</div>
{{-- If there is an error, display any messages to the right of the field with a warning icon. --}}
#if($errors->has('first_name'))
<div class="col-sm-5">
#foreach ($errors->get('first_name') as $message)
<span class="help-block">
<span class="glyphicon glyphicon-warning-sign"></span>
{{ $message }}
</span>
#endforeach
</div>
#endif
</div>
{{-- Form buttons --}}
<div class="form-group">
{{-- Line up the buttons with the right edge of the fields. --}}
<div class="col-sm-offset-2 col-sm-5">
<div class="pull-right">
{{-- Cancel button takes user back to profile page. --}}
{{ HTML::linkRoute('users.show', 'Cancel', array($user->id), array('class' => 'btn btn-default')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
</div>
</div>
</div>
{{ Form::close() }}
</div>
#stop
This is how it appears:
I'm just starting out with both Laravel and Bootstap. I used Jeffery Way's tutorial on NetTuts to make the form and Coder's Guide's tutorial to apply the formatting.
Should I be using client-side validation or would this be considered an acceptable implementation of Laravel 4 and Bootstrap?
Thanks!
This may not be the coolest way to do this but I think it's pretty slick.
Laravel has a feature called Form::macro that allows you to sort of make reusable code snippets. You can define a macro all kinds of places but I just slapped mine in my routes.php file to get this going real quick.
Form::macro('errorMsg', function($field, $errors){
if($errors->has($field)){
$msg = $errors->first($field);
return "<span class=\"error\">$msg</span>";
}
return '';
});
Then to use in a form, pass the macro your error messages:
{{ Form::label('first_name', 'First Name:') }}
{{ Form::text('first_name') }}
{{ Form::errorMsg('first_name', $errors) }}
{{-- where $errors is your Illuminate\Support\MessageBag object --}}
To get even more tech, you can use Form::objects in a Form::macro like so:
Form::macro('textError', function($field, $label, $errors){
$label_html = Form::label($field, $label);
$text_html = Form::text($field);
$msg_html = '';
if($errors->has($field)){
$msg_html.= '<span class="error">';
$msg_html.= $errors->first($field);
$msg_html.= '</span>';
}
return $label_html.$text_html.$msg_html;
});
Then you're at 1 line per input:
{{ Form::textError('first_name', 'First Name:', $errors) }}
You'd need to make other macros for password, textarea, etc. (which is why I just use the first example; it's only a couple more lines of code per input and serves all input types.)
If you wanted to style your input on error, eg. a red border, you'd probably want the second example then wrap it in your div.form-group or whatevers. Anyway, options out the wazoo.
UPDATE: An even slicker way to get errors in macros is to access them via Session::get('errors'); like so:
Form::macro('errorMsg', function($field){//yay! we don't have to pass $errors anymore
$errors = Session::get('errors');
if($errors && $errors->has($field)){//make sure $errors is not null
$msg = $errors->first($field);
return "<span class=\"error\">$msg</span>";
}
return '';
});