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
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";
}
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);
}
I am trying to work out the best way to do something. I have a form with a lot of fields, including a file input which allows multiple files to be uploaded.
All of this is linked to the model/form ReportingDoc
{!! Form::model(new App\ReportingDoc, [
'class'=>'form-horizontal',
'route' => ['projects.reportingDoc.store', $project->id],
'files' => true
]) !!}
<div class="form-group">
{!! Form::label('workType', 'Work Type:', array('class' => 'col-sm-5 control-label blue')) !!}
<div class="col-sm-7">
<select class="workType" name="workType">
<option value="recurring">Recurring</option>
<option value="adHoc">Ad-hoc</option>
</select>
</div>
</div>
//Lots of other inputs
<div class="form-group">
{!! Form::label('filePath', 'Supporting Documents:', array('class' => 'col-md-5 control-label green')) !!}
<div class="col-md-7">
{!! Form::file('filePath[]', array('multiple'=>true)) !!}
</div>
</div>
<div class="form-group">
{!! Form::submit('Save Data', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
The model looks like the following:
class ReportingDoc extends Model
{
protected $table = 'reporting_doc';
protected $guarded = [];
public function project()
{
return $this->belongsTo('App\Project', 'projectId');
}
}
So the model belongs to a Project. At the moment, the migration looks like the following:
public function up()
{
Schema::create('reporting_doc', function(Blueprint $table)
{
$table->increments('id');
$table->String('workType')->default('');
//all my other inputs
$table->String('filePath')->default('');
$table->timestamps();
});
Schema::table('reporting_doc', function (Blueprint $table) {
$table->integer('projectId')->unsigned()->default(0);
$table->foreign('projectId')->references('id')->on('projects')->onDelete('cascade');
});
}
In the controller for this route, I have my store method. At the moment it looks like the following:
public function store(Request $request, Project $project)
{
$workType = Input::get('workType');
//Other inputs
$projectId = $project->id;
$reportingDoc = new ReportingDoc();
$reportingDoc->workType = $workType;
//Other inputs
$reportingDoc->projectId = $projectId;
$dsReportingDoc->save();
return Redirect::route('projects.reportingDoc.create', $project->id)
->with('message', 'Files uploaded.');
/* Old part
$files = Input::file('filePath');
$file_count = count($files);
$uploadcount = 0;
if(isset($files)) {
foreach($files as $file) {
$destinationPath = public_path() .'/uploads/';
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::route('projects.reportingDoc.create', $project->id)
->with('message', 'Files uploaded.');
}
else {
return Redirect::route('projects.reportingDoc.create', $project->id)
->with('message', 'Something went wrong - Please try again.');
}
*/
}
As you can see, I have commented out the file part for now. What I was going to do was get the paths for all the uploaded files, and serialize them into
one field in the database - filePath.
However, to me this seems very messy. I would imagine it is best to have something like an uploads table which is linked to this model. I can then create an uploads object for each file that is uploaded.
One thing I am confused about is the form, and it being linked to my ReportingDoc Model. With this new approach, would I need to link it somehow to both models? ReportingDoc and Uploads?
Really, I am just looking for advice and guidance on the best way to achieve what I am after.
Many thanks
You are already almost done. The best way to do what you're trying to achieve is to create a ReportingDocUpload model which belongs to ReportingDoc, then remove the filePath field from Reporting Doc.
Your model should look like: class ReportingDocUpload { ... protected $fillable = ['filepath', 'reportingdoc_id']; ... }
Then to save your files, do this:
if($file_count) {
foreach($files as $file) {
$destinationPath = public_path() .'/uploads/';
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$rUpload = ReportingDocUpload::create(['filepath' => $filename, 'reportingdoc_id' => $reportingDoc->id]);
$uploadcount ++;
}
}
Don't forget to delete files from disk when the entry is deleted...
public static function boot()
{
parent::boot();
//delete associated file
static::deleting(function($docUpload){
try{
$filepath = public_path('uploads/').$docUpload->filepath;
if(file_exists($filepath))
{
unlink($filepath);
}
}
catch(\Exception $e)
{
//some error while deleteing
\Log::info('Error deleting: '.$filepath);
\Log::debug($e);
}
});
}
Cheers..
I have successfully added my own form (from the same module) into my custom template, but now I wish to load the taxonomy add term form (used by ubercart I think for product categories in the catalog vocab) into my template.
I have gotten this far with my module - filename simpleadmin.module
/**
* #file
* A module to simplify the admin by replacing add/edit node pages
*/
function simpleadmin_menu() {
$items['admin/products/categories/add'] = array(
'title' => 'Add Category',
'page callback' => 'simpleadmin_category_add',
'access arguments' => array('access administration pages'),
'menu_name' => 'menu-store',
);
return $items;
}
function simpleadmin_category_add() {
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
$output = drupal_get_form('taxonomy_form_term');
return theme('simpleadmin_category_add', array('categoryform' => $output));
}
function simpleadmin_theme() {
return array(
'simpleadmin_category_add' => array(
'template' => 'simpleadmin-template',
'variables' => array('categoryform' => NULL),
'render element' => 'form',
),
);
}
?>
And as for the theme file itself - filename simpleadmin-template.tpl.php, only very simple at the moment until I get the form to load into it:
<div>
This is the form template ABOVE the form
</div>
<?php
dpm($categoryform);
print drupal_render($categoryform);
?>
<div>
This is the form template BELOW the form
</div>
Its telling me that it is
Trying to get property of non-object in taxonomy_form_term()
and throwing up an error. Should I be using node_add() and passing the nodetype?
To render a taxonomy term form, the function should be able to know the vocabulary to which it belongs to. Otherwise how would it know which form to show? I think this is the proper way to do it.
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
if ($vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary_name')) {
$form = drupal_get_form('taxonomy_form_term', $vocabulary);
return theme('simpleadmin_category_add', array('categoryform' => $form));
}
To redirect your form use hook_form_alter
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
//get your vocabulary id or use print_r or dpm for proper validation
if($form_id == 'taxonomy_form_term' && $form['#vocabulary']['vid'] = '7' ){
$form['#submit'][] = 'onix_sections_form_submit';
}
}
function yourmodule_form_submit($form, &$form_state) {
$form_state['redirect'] = 'user';
}