I practice my CodeIgnitor right now and I'm new to them still. I am doing the inquiry form and wanted to make sure that it checks the form is correctly verified. After clicking on the submit button, It will send the form to a corresponding email.
but I'm having issues saying getMethod() is deprecated and my submit button is not responding too.
In fact, I don't grasp what deprecated means are, and are there anybody who can assist me clarify this part and provides any other approach before using getMethod().
Can you guys check what I did wrong with the submit button too? If you have a better approach to validate the form and send the email to the corresponding that somewhat cleaner. It's also wonderful.
This is my code:-
config/Controller/Contact Controller.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class ContactController extends Controller
{
// CONTACT PAGE
public function contact()
{
//Library
helper(['form']);
//Contact Data Initiate
$contact_data = [];
$data = [
'meta_title' => 'Contact | MFD',
];
//Check request if it is post
if($this->request->getMethod() == 'post'){
// Setting Form Rules
$settings_rule = [
'email' => [
'name' => 'required|min_length[3]|max_length[20]',
'email' => 'required|valid_email',
'subject' => 'required',
],
'msg' => 'required',
];
if($this->validate($settings_rule)){
//Validation true send message successfully sent and return back to the same page
return view('page_templates/contact', $data);
}else {
// Will provide check list of error of the one we create
$contact_data['validation'] = $this->validator;
}
}
return view('page_templates/contact', $data);
}
views/page_templates/contact.php
<div class="col-lg-8 mt-5 mt-lg-0">
<?php if(isset($validation)) : ?>
<div class="error-message">
<?= $validation->listErrors(); ?>
</div>
<?php endif ?>
<form method="post" role="form" class="php-email-form">
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name"
value="<?= set_value('name'); ?>" placeholder="Your Name">
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email"
value="<?= set_value('email'); ?>" placeholder="Your Email">
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject"
value="<?= set_value('subject'); ?>" placeholder="Subject">
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" rows="5" placeholder="Message"><?= set_value('msg'); ?></textarea>
</div>
<!-- <div class="my-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div> -->
<div style="height: 10px;"></div>
<div class="text-left button">
<button type="submit" name="submit">Send Message</button>
</div>
</form>
</div>
Really appreciate it if anyone that can help me with this. Thank you
vscode also notified me the same, and then I added the line below before the controller class and it works fine.
/**
* #property IncomingRequest $request
*/
class ContactController extends Controller{
public function contact(){
}
}
What is the exact deprecation message that you are getting? And which version of CodeIgniter are you using?
Deprecation just means that the interface will be removed in future revisions.
But I just looked at the source and documentation and the method doesn't appear to be deprecated. The optional parameter $upper is deprecated though.
So you would not want to use $this->request->getMethod(TRUE | FALSE) since that wont be supported in the future. But $this->request->getMethod() should be fine.
As for your button problem... You didn't provide enough information.
For the client rendered button to respond to a click event you will need to add a listener. I am guessing you have not. It goes something like this.
<script>
let button = document.querySelector(".button button");
button.addEventListener("click", function(event) {
// Do your work here...
});
</script>
I am using CI4 and having the same issue, but the below solution working fine for me
if($this->request->getMethod() == 'post'){}
change to this
if ($this->request->getPost()) {}
if ($this->request->getGet()) {}
Related
I have 2 register and login form. The one is used to user and others is used to admin role.
In user role, I using from laravel authentication, is good and work well.
But, the problem is when I create custom register from admin role, its can't work well.
It can't store to database, when I check using echo function, it's not print anything just refresh the page.
Could you help me, what is wrong ???
this is my route
Route::get('/adminregister', 'Auth\LoginController#formreg')->name('admin-reg');
this is my controller
namespace App\Http\Controllers\Admin\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class AregisterController extends Controller
{
use RegistersUsers;
public function __construct()
{
// $this->middleware('guest');
}
public function create(Request $request)
{
$this->validate(request(),[
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
if ($request('confirmpassword') == $request('password')){
$user = User::create(request(['name','email' ,'password','is_admin' => True, ]));
// return redirect()->route('admin-login')->with('status', 'Successfully create account');;
}
else {
return redirect()->route('admin-reg')->with('status', 'Confirm Password not match');;
}
}
}
In this controller, fisrt I want to check the password will confirmation password then store it to database.
this is my view page
<form action ="{{ route('user-create') }}" method="POST" enctype="multipart/form-data" >
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row mb-3">
<div class="col-md-12">
<div class="form-floating mb-2 mb-md-0">
<input class="form-control" id="inputFirstName" type="text" placeholder="Enter your first name" name="name" />
<label for="inputFirstName">Name </label>
</div>
</div>
</div>
<div class="form-floating mb-3">
<input class="form-control" id="inputEmail" type="email" placeholder="name#example.com" name="email"/>
<label for="inputEmail">Email address</label>
</div>
<div class="row mb-3">
<div class="col-md-6">
<div class="form-floating mb-3 mb-md-0">
<input class="form-control" id="inputPassword" type="password" placeholder="Create a password" name="password" />
<label for="inputPassword">Password</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating mb-3 mb-md-0">
<input class="form-control" id="inputPasswordConfirm" type="password" placeholder="Confirm password" name="confirmpassword" />
<label for="inputPasswordConfirm">Confirm Password</label>
</div>
</div>
</div>
<div class="mt-4 mb-0">
<div class="d-grid"><button type="submit" class="btn btn-primary">Create account</button></div>
</div>
</form>
Do you have any suggestion of how to fix it? It cant store anything in database, and when I check it using " echo " there is nothing :)
Thank you
The confirmed rule is looking for a field name {field}_confirmation. So if you are trying to confirm the 'password' input it would be looking for a field named password_confirmation. So that input in the form needs to be changed to the name password_confirmation.
You won't need to compare the 2 password fields that are submitted since the confirmed rule has done that for you already (that is what it is for; to confirm that they match).
The Request class is not callable, $request(...). That will throw an error since it isn't callable (there is no __invoke method defined on it to make it callable).
To create the User you can get the fields you need easily with the only method:
$request->only('name', 'email', 'password')
You can add your is_admin value to the array returned from the only call:
User::create($request->only('name', 'email', 'password') + ['is_admin' => true])
You will have to make sure that the is_admin field is "fillable" on the Model.
In general you don't need to be calling request() any where in this method since you have a Request instance injected as $request already.
Also, your form isn't handling a file upload so you don't need enctype="multipart/form-data".
I'm brand new to Laravel and am working my way through the [Laravel 6 from Scratch][1] course over at Laracasts. The course is free but I can't afford a Laracasts membership so I can't ask questions there.
I've finished Section 6 of the course, Controller Techniques, and am having unexpected problems trying to extend the work we've done so far to add a few new features. The course has students build pages that let a user show a list of articles, look at an individual article, create and save a new article, and update and save an existing article. The course work envisioned a very simple article containing just an ID (auto-incremented in the database and not visible to the web user), a title, an excerpt and a body and I got all of the features working for that, including updating an existing article and saving it.
The update form sets method to POST but then uses a #METHOD('PUT') directive to tell the browser that it is actually supposed to do a PUT. This worked perfectly in the original code. However, now that I've added two more fields to the form, when I click Submit after editing an existing record, the save fails with this message:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The PUT method is not supported for this route. Supported methods: GET, HEAD, POST.
http://localhost:8000/articles
I don't understand why adding two fields to the form would cause this to break. Can someone enlighten me? I added the two new fields/columns to the migration and ran migrate:rollback and migrate. I've also added the new fields/columns to the fillable attribute and added validations for them in the ArticlesController.
Here is my routing:
Route::get('/articles', 'ArticlesController#index');
Route::post('/articles', 'ArticlesController#store');
Route::get('/articles/create', 'ArticlesController#create');
Route::get('/articles/{article}', 'ArticlesController#show');
Route::get('/articles/{article}/edit', 'ArticlesController#edit');
Route::put('/articles/{article}', 'ArticlesController#update');
//Route::delete('/articles/{article}', ArticlesController#destroy');
This is my ArticlesController:
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function index()
{
$articles = Article::latest()->get();
return view ('articles.index', ['articles' => $articles]);
}
public function show(Article $article)
{
return view('articles.show', ['article' => $article]);
}
public function create()
{
return view('articles.create');
}
public function store()
{
//Stores a NEW article
Article::create($this->validateArticle());
return redirect('/articles');
}
public function edit(Article $article)
{
return view('articles.edit', ['article' => $article]);
}
public function update(Article $article)
{
//Updates an EXISTING article
$article->update($this->validateArticle());
return redirect('/articles/', $article->id);
}
public function validateArticle()
{
return request()->validate([
'title' => ['required', 'min:5', 'max:20'],
'author' => ['required', 'min:5', 'max:30'],
'photopath' => ['required', 'min:10', 'max:100'],
'excerpt' => ['required', 'min:10', 'max:50'],
'body' => ['required', 'min:50', 'max:500']
]);
}
public function destroy(Article $article)
{
//Display existing record with "Are you sure you want to delete this? Delete|Cancel" option
//If user chooses Delete, delete the record
//If user chooses Cancel, return to the list of articles
}
}
Here's my edit form, edit.blade.php:
#extends('layout')
#section('content')
<div id="wrapper">
<div id="page" class="container">
<h1>Update Article</h1>
<form method="POST" action="/articles">
#csrf
#method('PUT')
<div class="form-group">
<label class="label" for="title">Title</label>
<div class="control">
<input class="form-control #error('title') errorborder #enderror" type="text" name="title" id="title" value="{{ $article->title }}">
#error('title')
<p class="errortext">{{ $errors->first('title') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="author">Author</label>
<div class="control">
<input class="form-control #error('author') errorborder #enderror" type="text" name="author" id="author" value="{{ $article->author }}">
#error('title')
<p class="errortext">{{ $errors->first('author') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="photopath">Path to Photo</label>
<div class="control">
<input class="form-control #error('photopath') errorborder #enderror" type="text" name="photopath" id="photopath" value="{{ $article->photopath }}">
#error('title')
<p class="errortext">{{ $errors->first('photopath') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="excerpt">Excerpt</label>
<div class="control">
<textarea class="form-control #error('excerpt') errorborder #enderror" name="excerpt" id="excerpt">{{ $article->excerpt }}</textarea>
#error('excerpt')
<p class="errortext">{{ $errors->first('excerpt') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="body">Body</label>
<div class="control">
<textarea class="form-control #error('body') errorborder #enderror" name="body" id="body">{{ $article->body }}</textarea>
#error('body')
<p class="errortext">{{ $errors->first('body') }}</p>
#enderror
</div>
</div>
<div class="control">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</div>
</div>
#endsection
Is there anything else you need to see?
[1]: https://laracasts.com/series/laravel-6-from-scratch/episodes/33?autoplay=true
Your Laravel route is:
Route::put('/articles/{article}', 'ArticlesController#update');
So your form action url should match that uri:
<form action="{{ url('/articles/'.$article->id) }}">
where the {article} parameter is the record id (you can read more about in the docs here).
Then in your controller update() method, you have:
return redirect('/articles/', $article->id);
which means redirect to /articles with status code $article->id (you can read more about in the docs here). I think you are trying to redirect to the show route, which is:
Route::get('/articles/{article}', 'ArticlesController#show');
So change the , (comma) to a . (dot) to concatenate the article id with the uri:
return redirect('/articles/' . $article->id);
The route in the form for /articles, However your route for updating should be /articles/{article}
Try this:
<form method="POST" action="/articles/{{ $article->id }}">
How can I set errorPlacement in Yii2 activeform or using kartik active form just after form-group?
Below are code for view file.
<div class="col-sm-6">
<div class="form-group field-signupform-value1 required">
<label class="control-label" for="signupform-value1">value1 Name</label>
<input type="text" id="signupform-value1" class="form-control" name="SignupForm[value1]" placeholder="value1 Name" aria-required="true">
<p class="help-block help-block-error"></p>
</div>
</div>
I want html code as below. should auto add after .
<div class="col-sm-6">
<div class="form-group field-signupform-value1 required">
<label class="control-label" for="signupform-value1">value1 Name</label>
<input type="text" id="signupform-value1" class="form-control" name="SignupForm[value1]" placeholder="value1 Name" aria-required="true">
</div>
<p class="help-block help-block-error"></p>
</div>
Looking at your inputs, it is not needed to change the replacement of the error message, though if you want to play with the input template properties, you can refer the following
<?php $form = ActiveForm::begin([
'fieldConfig'=>['template'=>'<div style="border:solid 1px black;padding-bottom:15px">{label}{input}{hint}</div>{error}']
]); ?>
in the above template properties, you can change the placement of error template or event add some HTML inside it, hope it will help you.
Edit:
I have added inline css to div, you can put your css class which is applying outer border.
I achieved by below code. Thank for kind suggestion.
<?php
$form = ActiveForm::begin([
'fieldConfig'=>['template'=>' <div class="custom">
{label}{input}
</div>
{error}',
'inputOptions' => [
'placeholder' => 'Username ...',
'class'=>'form-control',
]]
]); ?>
and given css to "custom" class for border-box
You can use another hidden input like this:
$form->field($model, "your_field")->hiddenInput([
'class' => 'hidden_input_val'
])->label(false) // (for validation messages)
To display error in HTML:
<?=Html::error($model, 'your_field', ['class' => 'help-block']) ?>
Then you just have to hide this hidden input's .help-block with css
I have followed this tutorial (https://mydnic.be/post/how-to-build-an-efficient-and-seo-friendly-multilingual-architecture-for-your-laravel-application) about laravel multilanguage and localization. Everything seems ok, except I want to CREATE a CRUD for inserting this posts with title and content in multiple language - and STORE it in database - and then read it out in index blade.
Can you show me an example of CRUD in this way in blade for CREATE and in Controller for CREATE and STORE function. How to make this to work?
This is my simple main CRUD, how to extend this to be able to creating and storing into multiple language when creating.
And how to extend the controller for storing in multiple language when using this translatable package from tutorial above (link).
CRUD:
<form method="POST" action="/posts">
#csrf
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea id="content" name="content" class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Publish</button>
</div>
</form>
CONTROLLER
public function store(Request $request)
{
$post = Post::all();
$this->validate(request(), [
'title' => 'required',
'content' => 'required'
]);
$post = new Post;
$post->title = $request->title;
$post->content = $request->content;
$post->save();
return redirect('/');
THANKS :)
I'm the author of the tutorial.
The whole point of that implementation is that you don't have to worry about the model locale at all. The locale is set through the URL "/en/..."
So if you make a POST request to your model store URL like so :
POST /en/post {payload}
The App Locale of your laravel application will be automatically set before you even reach the PostController#store method.
Then, you can simply create your model like you would usually do (like in your exemple, that's correct) , and the model will be stored with the according locale.
Now that your model is initially created with the defined locale, you should be able to edit it in another language.
So you can go to this URL: /en/post/:id/edit then switch to another locale : /fr/post/:id/edit and you will notice that all input of the translatable fields are blank. That's normal because the 'fr' translation of that model doesn't exist yet.
You can thus fill the form with the 'fr' translated field, then save (update the model). And the translation will be saved. Your model is now translated :)
Hope this helps !
PS you can have a look at the example code here https://github.com/mydnic/Laravel-Multilingual-SEO-Example
So based on the tutorial, you'll have a column in your posts table called locale
Then in your view, you can add a select field from which you can chose the locale
<div class="form-group">
<label for="locale">Locale</label>
<select id="locale" name="locale" class="form-control">
<option value="en">English</option>
<option value="fr">French</option>
</select>
</div>
Then in your controller add the following line:
$post->locale = $request->locale;
Put locale in your $fillable array within the post model.
THIS IS WORKING WELL IN THIS SITUATION:
CONTROLLER:
public function create()
{
return view('services.new');
}
public function store(Request $request)
{
$service = new Service();
$service->save();
$this->validate($request, [
'title2' => 'required|max:350',
'content2' => 'required'
]);
foreach (['en', 'bs'] as $locale) {
$service->translateOrNew('en')->title = $request->title;
$service->translateOrNew('en')->content = $request->content;
$service->translateOrNew('bs')->title = $request->title2;
$service->translateOrNew('bs')->content = $request->content2;
}
$service->translateOrNew('en')->title = $request->title;
$service->translateOrNew('en')->content = $request->content;
$service->translateOrNew('bs')->title = $request->title2;
$service->translateOrNew('bs')->content = $request->content2;
// $article->translateOrNew('en')->text = ['texten'];
// $article->translateOrNew('ka')->name = ['nameka'];
// $article->translateOrNew('ka')->text = ['textka'];
// return $article;
// exit();
$service->save();
return redirect()->back();
}
BLADE FOR CREATE + CSS (in background):
<form action="{{route('service.store')}}" method="POST">
{{csrf_field()}}
<div class="tabset">
<!-- Tab 1 -->
<input type="radio" name="tabset" class="radio1" id="tab1" aria-controls="marzen" checked>
<label for="tab1">Bosanski</label>
<!-- Tab 2 -->
<input type="radio" class="radio1" name="tabset" id="tab2" aria-controls="rauchbier">
<label for="tab2">Engleski</label>
{{-- <!-- Tab 3 -->
<input type="radio" name="tabset" id="tab3" aria-controls="dunkles">
<label for="tab3">Dunkles Bock</label> --}}
<div class="tab-panels">
<section id="marzen" class="tab-panel">
<h2>Dodaj novu uslugu</h2>
<div class="form-group">
<lebal>Naslov*(bs)</lebal>
<input type="text" class="form-control" name="title2">
</div>
<div class="form-group">
<lebal>Opis*(bs)</lebal>
<textarea class="form-control" name="content2"></textarea>
</div>
</section>
<section id="rauchbier" class="tab-panel">
<h2>Dodaj novu uslugu</h2>
<div class="form-group">
<lebal>Title (EN)</lebal>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<lebal>Description (EN)</lebal>
<textarea class="form-control" name="content"></textarea>
</div>
</section>
<section id="dunkles" class="tab-panel">
<h2>Tab3</h2>
</section>
</div>
<input type="submit" value="Submit">
</form>
WEB.PHP:
Route::post('/create',[
'uses' => 'ServicesController#store',
'as' => 'service.store'
]);
I have a small form in Laravel 5.4 which has a checkbox and a text box. The issue is that when I post the form, the checkbox value is not coming through the request. I have custom styling on the checkbox but surely it can't be that?
I've been looking at this for a while, and everything looks normal. My code is below:
<form method="post" action="{{ route('admin.settings.save') }}">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label><b>Site Name</b></label>
<p>This is the name of your LaravelFileManager instance.</p>
<input name="siteName" id="siteName" class="form-control" value="{{ \App\Helpers\ConfigHelper::getValue('site_name') }}" />
</div>
<div class="form-group">
<label><b>Footer Message</b></label>
<p>You can customise the footer message for the application.</p>
<div class="checkbox">
<label>
<input type="checkbox" name="showFooter" id="showFooter" checked="{{ \App\Helpers\ConfigHelper::getValue('show_footer_message') }}"> Show footer message
</label>
</div>
</div>
<button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Save Changes</button>
</div>
</div>
</form>
My controller code is as such:
public function saveSettings(Request $request) {
$siteName = $request->input('siteName');
$showFooter = $request->input('showFooter');
ConfigHelper::setValue('site_name', $siteName);
ConfigHelper::setValue('show_footer_message', $showFooter);
return redirect()->route('admin.settings')->with('result', 'Settings saved.');
}
My route:
Route::post('settings/save', ['uses' => 'Admin\SettingsController#saveSettings'])->name('admin.settings.save');
I've also done a vardump on the $request variable and even that is missing the check box value:
array(2) {
["_token"]=> string(40) "sgyO7Kkz1ljsYEZ1G5nkj4uVbmFZqiTMbpK9P6Bi"
["siteName"]=> string(16) "File Manager 1.0"
}
It's missing the 'showFooter' variable.
Not quite sure where to go with this one. Any help appreciated.
So I got this working in the end. Using help from the comments:
public function saveSettings(Request $request) {
$siteName = $request->input('siteName');
$showFooter = $request->has('showFooter');
ConfigHelper::setValue('site_name', $siteName);
ConfigHelper::setValue('show_footer_message', $showFooter);
return redirect()->route('admin.settings')->with('result', 'Settings saved.');
}
For some reason, using $request->input('showFooter') wasn't working properly. $request->get('showFooter') brings a result when true, so adding the ternary makes it work every time.