How to set errorPlacement after form-group in Yii2 - validation

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

Related

CodeIgniter getMethod() Deprecated and Submit Button not functioning

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()) {}

Laravel 6 Validation Bug?

I have a problem about my Laravel project.
$request->validate(
[
'blogs_file' => 'required|image|mimes:jpeg,jpg,png|max:2048',
'blogs_title' => 'required|unique:App\Blogs,blogs_title',
'blogs_content' => 'required',
]);
I made a limit to blogs_file. It should only allowed jpg,png,jpeg and max 2 MB.
But when i try to put a mp4 file, it pass. What is the problem there?
I have already added enctype="multipart/form-data" to my form on blade page.
If i want to put an mp4 file or zip lower than 2 MB the validation works fine. But if i upload any kind of data upper than 2 MB; it passes. Actually, when i check to my db; blogs_file coming NULL on that way, but it returns with success message to user.
UPDATE:
my create.blade.php file;
<div class="box-body">
<form action="{{route('blogs.store')}}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label>Resim Seç</label>
<div class="row">
<div class="col-xs-12">
<input class="form-control" required name="blogs_file" type="file">
</div>
</div>
</div>
<div class="form-group">
<label>Başlık</label>
<div class="row">
<div class="col-xs-12">
<input class="form-control" required type="text" placeholder="Blog Başlığı..." name="blogs_title">
</div>
</div>
</div>
<div class="form-group">
<label>Sayfa Linki</label>
<div class="row">
<div class="col-xs-12">
<input class="form-control" placeholder="Sayfa linki girebilirsiniz(isteğe bağlı)"
name="blogs_slug" type="text">
</div>
</div>
</div>
<div class="form-group">
<label>İçerik</label>
<div class="row">
<div class="col-xs-12">
<textarea class="form-control" id="editor1" name="blogs_content"
required></textarea>
</div>
<script>
CKEDITOR.replace( 'editor1' );
</script>
</div>
</div>
<div class="form-group">
<label>Durum</label>
<div class="row">
<div class="col-xs-12">
<select name="blogs_status" class="form-control">
<option value="1">Aktif</option>
<option value="0">Pasif</option>
</select>
</div>
</div>
</div>
<div align="right" class="box-footer">
<button type="submit" class="btn btn-primary">Ekle</button>
</div>
</form>
</div>
route:
Route::resource('blogs','BlogController');
BlogController:
public function store(Request $request)
{
if (strlen($request->blogs_slug)>3)
{
$slug=Str::slug($request->blogs_slug);
} else {
$slug=Str::slug($request->blogs_title);
}
if ($request->hasFile('blogs_file'))
{
$request->validate(
[
'blogs_file' => 'required|file|mimes:jpeg,jpg,png|max:2048',
'blogs_title' => 'required|unique:App\Blogs,blogs_title',
'blogs_content' => 'required',
]);
$file_name=uniqid().".".$request->blogs_file->getClientOriginalExtension();
$request->blogs_file->move(public_path('images/blogs'),$file_name);
$request->blogs_file=$file_name;
}
$blog= new Blogs;
$blog->blogs_file=$request->blogs_file;
$blog->blogs_title=$request->blogs_title;
$blog->blogs_slug=$slug;
$blog->blogs_content=$request->blogs_content;
$blog->blogs_status=$request->blogs_status;
$blog->uniqid=uniqid();
$blog->save();
if ($blog)
{
return redirect(route('blogs.index'))->with('success','İşlem Başarılı!');
} else {
return back()->with('error','İşlem Başarısız!');
}
}
1st. You have missed file rule.
2nd. You may use either image rule (that validates a file to be jpeg, png, bmp, gif, svg, or webp) or use mimes:jpeg,jpg,png:
So your validation would be either:
'blogs_file' => 'required|file|mimes:jpeg,jpg,png|max:2048',
Or:
'blogs_file' => 'required|file|image|max:2048',
3rd. You've put your validation $request->validate inside an if, it's wrong and makes the problem! You may conditionally adding rules or use after validation hook for more complex validations instead.

How i will get current page title in hidden field, when i submit the form in laravel

I have a form which have name, email and phone. But i want current page title or url when user submit the form, Because I want to track the user page. Please let me know How i can do it.
This is my form code.
<form class="callus" method="post" action="{{url('/sendmailuser')}}">
#csrf
<div class="col-md-3 col-sm-6">
<div class="single-query form-group">
<input type="hidden" name="product_title" value="{{ request('request') }}" class="keyword-input" placeholder="Enter Your Name" required="">
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="single-query form-group">
<input type="text" name="user_name" class="keyword-input" placeholder="Enter Your Name" required="">
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="single-query form-group">
<input type="text" name="user_email" class="keyword-input" placeholder="Enter Your Email" required="">
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="single-query form-group">
<input type="text" name="user_phone" class="keyword-input" placeholder="Enter Your Phone" required="Field is required">
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="single-query form-group">
<input type="submit" value="submit now" class="btn-blue">
</div>
</div>
</form>
This is my Email send code...
public function sendyourmail(Request $r)
{
$validator = Validator::make($r->all(), [
'user_name' => 'required',
'user_email' =>'required',
'user_phone' =>'required',
'user_desc' =>'required',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator);
}
$data=[
'user_email' => $r->user_email,
'user_name' => $r->user_name,
'user_phone' => $r->user_phone,
'user_desc' => $r->user_desc,
];
Mail::send('mail', $data, function($message) use($data) {
$message->from($data['user_email'], 'Email Form Sumit');
$message->to('sumit#gmail.com')->cc('sumit#sumit.com');
$message->subject($data['user_desc']);
});
return redirect()->back()->with('message','Your Mail Has Been sent Successfully, We Will Get Back to You Shortly.');
}
You should define the title of the rendered page within the controller and past it as parameter to the view when you specify which template should be rendered.
public function sendyourmailform()
{
$title = 'Sample Page Title';
return view('email_template.blade.php', compact('title'));
}
Because the title variable is past to the template you can access it inside the template by rendering it twice inside the title section
#section('title')
{{ $title }}
#endsection
Inside the layout page which is extends by the template which render the form you should have define section named title like this
<head>
<title>
#section('title')
#endsection
<title>
</head>
And you have access to the title variable inside the template part which show the related form.
<form class="callus" method="post" action="{{url('/sendmailuser')}}">
#csrf
<div>
<input type="hidden" name="page_title" value="{{ $title }}">
</div>
<!-- ... -->
</form>

Bootstrap classes for laravel 5 form submit button

Below is the part of input field and submit button.
I want to increase the width of submit button as the input field using bootstrap.
Here is my code.
<div class="form-group col-md-6">
{!! Form::label('Event Photo') !!}
</div>
<div class="form-group col-md-6">
<input type='file' name='photo' id ='photo' class ='form-control'/>
</div>
<div class="form-group col-md-12">
{!! Form::submit('Add', array('class'=>'btn btn-primary')) !!}
</div>
But the button size can't get increased like that. Where am I wrong? How should I solve that?
The array() part of your form allows you to pass in any other parameters that you want.
Just as you are using it to define the class, you can use it to define the style:
<div class="form-group col-md-12">
{!! Form::submit('Add', array('class'=>'btn btn-primary', 'style' => 'width:50px;)) !!}
</div>
Just change 50px to whatever width you want to use.
Adding the class btn-lg will work.
You can find that in the documentation

Multiple forms with same inputs name check which form input has error Laravel

I have something like this in my code:
#foreach($cars as $key => $car)
{!!Form::open(['action' => 'CarController#Update'])!!}
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Color</label>
<div class="col-lg-6">
{!!Form::text('carColor', $car->color, ['class' => 'form-control input-sm'])!!}
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Price</label>
<div class="col-lg-6">
{!!Form::text('carPrice', $car->price, ['class' => 'form-control input-sm'])!!}
</div>
</div>
</div>
{!!Form::close()}
#endforeach
The objective of this view is to update a car's price and color. But there are a lot so there's one form per car. In case the inputs don't pass the validation, how can I know which form inputs are the invalid since the inputs are named the same.
The problem is that the laravel has a session of old inputs but not for forms.
But this task is easy with javascript or jquery.
#foreach($cars as $key => $car)
{!!Form::open(['action' => 'CarController#Update'])!!}
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Color</label>
<div class="col-lg-6">
{!!Form::text('carColor', $car->color, ['class' => 'form-control input-sm', 'id' => 'carColor'])!!}
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Price</label>
<div class="col-lg-6">
{!!Form::text('carPrice', $car->price, ['class' => 'form-control input-sm', 'id'=> 'carPrice'])!!}
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<input type="hidden" id="carID" value="{{ $car->id }}">
<button class="btn btn-warning" id="editDetails">edit</button>
</div>
</div>
{!!Form::close()}
#endforeach
and in your javascript
$('#editDetails').on('click', function () {
carColor = $(this).parent().parent().parent().find('#carColor').val();
carPrice = $(this).parent().parent().parent().find('#carPrice').val();
car_id = $(this).parent().parent().parent().find('#carID').val();
_token= $('meta[name="csrf-token"]').attr('content'); //add meta header in top head section see below
//here you can also check validation like check for empty fields
$.ajax({
url : 'url/to/edit/route',
method : 'patch', //this could be post. whatever you defined as your route
data : {
carColor : carColor,
carPrice : carPrice,
carId : carId,
_token : _token
},
success : function() {
alert('successful edit!');
//you can do something like
$(this).parent().parent().append('<p>success</p>');
//to show which line was successful
},
error : function(xhr,status,err) {
//you can do something like append an alert div to the parent form element of the erroneous input row.
$(this).parent().parent().append('<p>error editing here</p>');
}
});
});
add this meta tag with a csrf session as content in the head tag of your master layout
<meta name="csrf-token" content="{!! csrf_token() !!}">
Hope this would give you an idea on how you solve your problem.
EDIT
due to OP needing to handle this with no javascript
First add a hidden input of the key in foreach loop form to pass which row throws the error
<input type="hidden" id="key" value="{{ $key }}">
then in your controller you can add this to the error handling block
Session::flash('error', Input::get('key')); //use flash which behaves the same as as old input session
//a one time use session
and on inside the loop add an if statement checking for errors
#if(Session::has('error') || Session::get('error') == $key)
<div class="alert-box success">
<h2>error here</h2>
</div>
#endif
Hope this helps

Resources