How can i store my data inside db using {!! form !!} builder?
controller:
public function create()
{
$categories = \DB::table('categories')->lists('title', 'id');
return view('dash.reports.create')->with('categories', $categories);
}
/**
* Store a newly created resource in storage.
*
* #return void
*/
public function store(Request $request)
{
$this->validate($request, ['title' => 'required', ]);
Report::create($request->all());
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}
my view:
{!! Form::label('category_id', trans('reports.category_id'), ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::select('category',
(['0' => 'Select a Category'] + $categories),
null,
['class' => 'form-control'])
!!}
{!! $errors->first('category_id', '<p class="help-block">:message</p>') !!}
when i press button action return me blank page, any idea?
You don't have a form, so you're not submitting data to the correct page. You're sending a POST request to the same URL that you used to access the form, which is probably not what you want.
This guide will show you how to set up a Laravel form that points at a controller method which will allow you to capture input, validate it, and store it in the database.
http://www.easylaravelbook.com/blog/2015/02/09/creating-a-contact-form-in-laravel-5-using-the-form-request-feature/
solved
view:
{!! Form::select('category_id', $category, null, ['class' => 'form-control'] ) !!}
controller:
public function create()
{
$category = Category::lists('title','id');
return view('dash.reports.create')->with('category', $category);
}
Related
I recently set up the ability to tag posts on my site. I had everything working fine. Then as I was wrapping up I tested all my admin side forms again. The Add Tag form no longer does anything. It doesn't even flash an error or redirect after submission. The page just reloads at the same URL. The only changes to the site I have made since initial testing was move the forms to the admin side of the dev site. Here is some code to hopefully reveal what the mystery is. Also my edit tag form is doing similar thing. It has no flash message but redirects back to the index, like its supposed to but with no changes made to the tag. Ill include the edit code as well.
Add.ctp in src/Template/Admin/Tags/Add.ctp
<div class="tags form large-9 medium-8 columns content">
<?= $this->Form->create($tag) ?>
<div class="form-group">
<fieldset>
<h1 class="page-header">New Tag</h1>
<?php
echo $this->Form->input('name', ['class' => 'form-control']);
?>
</fieldset>
</div>
<?= $this->Form->button(__('Submit'), ['class' => 'btn btn-primary']) ?>
<?= $this->Form->end() ?>
</div>
Here is my Add funciton in my TagsController:
public function add()
{
$this->viewBuilder()->layout('admin');
$tag = $this->Tags->newEntity();
if ($this->request->is('post')) {
$tag = $this->Tags->patchEntity($tag, $this->request->data);
if ($this->Tags->save($tag)) {
$this->Flash->success(__('The tag has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The tag could not be saved. Please, try again.'));
}
$this->set(compact('tag'));
$this->set('_serialize', ['tag']);
}
Here is my Edit funciton in my TagsController:
public function edit($id = null)
{
$this->viewBuilder()->layout('admin');
$tag = $this->Tags->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$tag = $this->Tags->patchEntity($tag, $this->request->data);
if ($this->Tags->save($tag)) {
$this->Flash->success(__('The tag has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The tag could not be saved. Please, try again.'));
}
$this->set(compact('tag'));
$this->set('_serialize', ['tag']);
}
Edit.ctp in src/Template/Admin/Tags/Edit.ctp
<div class="tags form large-9 medium-8 columns content">
<?= $this->Form->create($tag) ?>
<div class="form-group">
<fieldset>
<h1 class="page-header">Edit Tag</h1>
<?php
echo $this->Form->input('name', array('class' => 'form-control'));
?>
</fieldset>
</div>
<?= $this->Form->button(__('Submit'), ['class' => 'btn btn-primary']) ?>
<?= $this->Form->end() ?>
</div>
Just as a side note. I started getting errors when creating a new post as well.
General error: 1364 Field 'section_id' doesn't have a default value
I did go into my DB and give the field a default value. But then when I fill out the form for a new post again, the error just moves to the next table column. I am assuming they are some how related since they popped up at the same time and because tags and posts are related to each other.
TagsTable:
class TagsTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('tags');
$this->displayField('name');
$this->primaryKey('id');
$this->hasMany('PostsTags', [
'foreignKey' => 'tag_id'
]);
}
/**
* Default validation rules.
*
* #param \Cake\Validation\Validator $validator Validator instance.
* #return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->requirePresence('name', 'create')
->notEmpty('name');
return $validator;
}
}
Tags Entity:
class Tag extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* #var array
*/
protected $_accessible = [
'*' => false,
'id' => false
];
}
When I place <?php debug($tag); ?> into my add.ctp view this is the out put it gives me:
object(App\Model\Entity\Tag) {
'[new]' => true,
'[accessible]' => [],
'[dirty]' => [],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Tags'
}
Again, in question always post debug pathEntity output, in your case debug($tag), also Tag Entity, your validation code, and how looks your db tags table.
Answer:
General error: 1364 Field 'section_id' doesn't have a default value
This means that you have not passed a value for this field.
You can change that table field to accept null or empty value and/or set default if not passed from application, or make validation in your TagsTable to be sure if submitted data valid before send to db.
After question updated:
protected $_accessible = [
'*' => false, <---- should be true
'id' => false
];
This means that all fields except id are accessible
I have a problem with making a page to allow people to edit their profile, the thing is that I have 3 form on one page (one for profile settings, second for social settings and the 3rd for the account settings) and I made 3 controllers to control each one, the problem is that I can't call 3 controllers at the same time for one route...
here is my profile.blade.php:
{!! Form::model($user, ['action' => ['ProfileController#updateProfile', 'id' => $user->id], 'method' => 'PUT']) !!}
...Some input to edit username, name, description settings...
{!! Form:close() !!}
{!! Form::model($user, ['action' => ['ProfileController#updateSocial', 'id' => $user->id], 'method' => 'PUT']) !!}
...Some input to set link to their social account...
{!! Form:close() !!}
{!! Form::model($user, ['action' => ['ProfileController#updateSettings', 'id' => $user->id], 'method' => 'PUT']) !!}
...Some input to update password or email...
{!! Form:close() !!}
Here is my web.php (routes):
Route::get('/profile/{urlid}', 'ProfileController#index')->name('profile');
Route::put('/profile/{urlid}', 'ProfileController#updateProfile');
Route::put('/profile/{urlid}', 'ProfileController#updateSocial');
Route::put('/profile/{urlid}', 'ProfileController#updateSettings');
And here is my ProfileController:
public function updateProfile(Request $request, $urlid)
{
$user = User::findOrFail($urlid);
$user->fname=$request->input('fname');
$user->lname=$request->input('lname');
$user->profile_title=$request->input('profile_title');
$user->profile_resume=$request->input('profile_resume');
$user->save();
return view('profile')->with([
'user' => $user
]);
}
public function updateSocial(Request $request, $urlid)
{
$user = User::findOrFail($urlid);
$user->perso_site=$request->input('perso_site');
$user->linkedin=$request->input('linkedin');
$user->twitter=$request->input('twitter');
$user->save();
return view('profile')->with([
'user' => $user
]);
}
public function updateSettings(Request $request, $urlid)
{
$user = User::findOrFail($urlid);
$user->password=$request->input('password');
$user->email=$request->input('email');
$user->save();
return view('profile')->with([
'user' => $user
]);
}
The thing is that all of those 3 forms are on the same page, and I get an error If I call the 3 functions at the same time
I tried with only one function, it work, everything is ok but with one function, only one form is working, I hope I will find some help, It's been almost 2 hours that I'm blocked with this problem..
So in conclusion: I have 3 forms on the same page, I need these 3 functions to make them work, but I can't call 3 functions for only one route.
Seperate your url's and set your Routes like taht:
Route::get('/profile/{urlid}', 'ProfileController#index')->name('profile');
Route::post('/profile/{urlid}', 'ProfileController#updateProfile')->name('update_profile');
Route::post('/profile/social/{urlid}', 'ProfileController#updateSocial')->name('update_social');
Route::post('/profile/settings/{urlid}', 'ProfileController#updateSettings')->name('update_settings');
and in the form blade use the route function for detting the action url like that ...
{!! Form::open(['url' => route('update_profile', ['urlid' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
...Some input to edit username, name, description settings...
{!! Form:close() !!}
{!! Form::open(['url' => route('update_social', ['urlid' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
...Some input to set link to their social account...
{!! Form:close() !!}
{!! Form::open(['url' => route('update_settings', ['urlid' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
...Some input to update password or email...
{!! Form:close() !!}
You route should looks like
Route::get('/profile/{urlid}', 'ProfileController#index')->name('profile');
Route::post('/profile/{profile_id}', 'ProfileController#updateProfile')->name('update_profile');
Route::post('/profile/{social_id}', 'ProfileController#updateSocial')->name('update_social');
Route::post('/profile/{settings_id}', 'ProfileController#updateSettings')->name('update_settings');
And your form in blade
{!! Form::open(['url' => route('update_profile', ['profile_id' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
//....
{!! Form:close() !!}
{!! Form::open(['url' => route('update_social', ['social_id' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
//....
{!! Form:close() !!}
{!! Form::open(['url' => route('update_settings', ['settings_id' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
//....
{!! Form:close() !!}
In your function
public function updateProfile(Request $request, $urlid)
{
$data = $request->all();
return $data; //check what you pass from the form...
//then after remove return
$user = User::findOrFail($urlid);
if($user)
{
$user->fname=$data['fname'];
$user->lname=$data['lname']
$user->profile_title=$data['profile_title']
$user->profile_resume=$data['profile_resume']
$user->update();
return view('profile')->with([
'user' => $user
]);
}
return "User not found";
}
And the first form for you: https://pastebin.com/JznW20iy
Your second two form: https://pastebin.com/NuDTtvFR
and function
public function updateSocial(Request $request, $urlid)
{
$data = $request->all();
return $data; //check what you pass from the form...
//then after remove return
$user = User::findOrFail($urlid);
if($user)
{
$user->perso_site=$data['perso_site'];
$user->linkedin=$data['linkedin']
$user->twitter=$data['twitter']
$user->update();
return view('profile')->with([
'user' => $user
]);
}
return "User not found";
}
public function updateSettings(Request $request, $urlid)
{
$data = $request->all();
return $data; //check what you pass from the form...
//then after remove return
$user = User::findOrFail($urlid);
if($user)
{
$user->email=$data['email'];
$user->password=$data['newPass']
$user->update();
return view('profile')->with([
'user' => $user
]);
}
return "User not found";
}
I am creating a form with a many-many relationship. I have a posts table and an activities table. There is a many to many link using pivot table. I am creating a form to add one or more activities to the posts. I am receiving an 'ErrorException' - Trying to get property of non-object. I cannot understand why this is not working.
I would be grateful for any assistance you can offer me.
My relevant code is below.
//Posts/create.blade.php
{!!Form::open(['action' => 'PostController#store','method' => 'POST', 'class'=>'form-group'])!!}
{{Form::bsText('title','',['placeholder' => 'Trip Name'])}}
{{Form::bsTextarea('body','',['placeholder' => 'Trip Description'])}}
{{Form::bsSubmit('submit')}}
{{Form::label('activities', 'Activity:') }}
<select class="form-control select2-multi" name="activities" multiple="multiple">
#foreach($activities as $activity)
<option value="{{ $activity->id }}">{{ $activity->activity_name}}
</option>
#endforeach
</select>
{!! Form::close() !!}
// PostsController
public function create()
{
$activities = Activity::all();
return view('posts.create')->withActivities($activities);
$posts = Post::all();
}
public function store(Request $request)
{
// Create a new post using the request data
// Save it to the database
$this->validate(request(), [
'title' => 'required',
'body' => 'required',
]);
$post = Post::create([
'title' =>request('title'),
'body' =>request('body'),
'user_id' => auth()->id(),
'activity_id' => id()
]);
// And then redirect to somewhere in application
return redirect()->route('posts.show', $post->id);
}
This error throw only when you have empty variable but you point in blade file to render / display for browser. Or if you retrieve records from DB then add findOrFail in query to prevent those kind of issues. Thank you.
I’m learning Cakephp3.3 and have run into a problem trying to validate a form prior to saving.
I created a new form in ‘src/Template/Users’ called ‘register.ctp’ and added an action called ‘register’ in ‘src/Controller/UsersController’.
I want to validate form submissions before saving but can’t figure out how to make this work.
FWIW, pre-save validation works perfectly for the ‘add’ and ‘edit’ forms, though I think this happens by default in Cakephp3.
Is there a way to make these same validation rules apply for the ‘register’ form?
FYI, the 'register' action is actually updating an existing user record previously created for an anonymous user.
Here's the controller action:
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
class UsersController extends AppController
{
//<snipped methods>
public function register()
{
if($this->request->session()->read('Auth.User'))
{
$id = $this->request->session()->read('Auth.User.id');
if ($this->request->is(['patch', 'post', 'put']))
{
$user = $this->Users->get($id, [
'contain' => []
]);
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user))
{
$this->Flash->success(__('Your free trial period has started.'));
return $this->redirect("/Home/index");
}
else
{
$this->Flash->error(__('We were unable to start your trial. Please, try again.'));
}
}
}
else
{
$this->Flash->error(__('Your demo session has expired. Please start again.'));
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
}
Here's the UsersTable Model with the validation rules:
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
}
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->email('email')
->requirePresence('email')
->notEmpty('An email address is required.');
$validator
->requirePresence('password')
->notEmpty('A password is required.');
$validator
->requirePresence('firstname')
->notEmpty('firstname')
->add('firstname', 'minlength',['rule' => ['minlength', 1]]);
$validator
->requirePresence('lastname')
->notEmpty('lastname')
->add('lastname', 'minlength',['rule' => ['minlength', 1]]);
$validator
->integer('status')
->requirePresence('status', 'create')
->notEmpty('status');
$validator
->add('role', 'inList', [
'rule' => ['inlist', ['admin','author','subscriber']],
'message' => 'Please enter a valid role.'
]);
$validator
->requirePresence('referer', 'create')
->allowEmpty('referer');
$validator
->integer('plan_id')
->requirePresence('plan_id', 'create')
->notEmpty('plan_id');
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
return $rules;
}
}
And here's the register.ctp form:
<div class="users form large-12 columns ">
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Sign Up For Your No-Risk Free Trial!') ?></legend>
<?= $this->Form->input('firstname'); ?>
<?= $this->Form->input('lastname'); ?>
<?= $this->Form->input('email'); ?>
<?= $this->Form->input('password'); ?>
</fieldset>
<?= $this->Form->button(__('Start My Free Trial Now')) ?>
<?= $this->Form->end() ?>
</div>
Any help would be greatly appreciated!
if you want to save then the Default validation rules will be apply. if you don't want to apply the default rule then just add the 'validate' => false param
$user = $this->Users->patchEntity($user, $this->request->data,['validate' => false])
if you want to custom validation rule only for register options then need to create new function in your TABLE
class UsersTable extends Table
{
public function validationRegister($validator)
{
$validator
->email('email')
->requirePresence('email')
->notEmpty('An email address is required.');
$validator
->requirePresence('password')
->notEmpty('A password is required.');
$validator
->requirePresence('firstname')
->notEmpty('firstname')
->add('firstname', 'minlength',['rule' => ['minlength', 1]]);
return $validator;
}
}
Now set the 'validate' => 'register' param in your controller newEntity or patchEntity Funciton
$user = $this->Users->patchEntity($user, $this->request->data,['validate' => 'register'])
Help my code works on xampp and php artisan serve localhost:8000
but in server hosting the validation fail. When I try to upload image it, returns Errors: The image field is required.
public function store(Request $request)
{
$this->validate($request, array(
'image' => 'mimes:jpeg,png,bmp|required|max:3000'
));
Session::flash('success', 'Image been uploaded.');
return redirect()->route('galleries.index');
}
html
{!! Form::open(['route' => 'galleries.store', 'class' => 'form-inline', 'files' => true]) !!}
{!! Form::file('image', ['required' => '']) !!}
{!! Form::submit('Upload', ['class' => 'btn btn-success']) !!}
{!! Form::close() !!}
Flash Data
Sometimes you may wish to store items in the session only for the next request. You may do so using the flash method. Data stored in the session using this method will only be available during the subsequent HTTP request, and then will be deleted. Flash data is primarily useful for short-lived status messages:
In this case you can use this source for upload file
$fileName = $this->getFileName($file);
$pathUpload = $this->createPath(sprintf('%s', $config['path']));
$media = $file->move($pathUpload, $fileName);
protected function createPath($paths)
{
if (!is_array($paths)) {
if (!\File::exists($paths)) {
\File::makeDirectory($paths, $mode = 0777, true, true);
}
} else {
foreach ($paths as $path) {
if (!\File::exists($path)) {
\File::makeDirectory($path, $mode = 0777, true, true);
}
}
}
return $paths;
}
Function createPath for create folder and set permission.
Function move using file_put_content method for upload your file