I am developing custom theme from scratch and creates a custom post type and getting this warning while editing custom post type. I also design custom Meta box with two input fields and using nonce in it. Any help removing these warning?
//Custom Metabox
function register_book_meta_box(){
add_meta_box('book_meta_box_id', 'Book Detail','design_book_meta_box','books','advanced','high');
}
add_action('add_meta_boxes','register_book_meta_box');
function design_book_meta_box($post){
wp_nonce_field(basename(__FILE__),'book_cpt_nonce')
?>
<div>
<label for="book-author">Author Name </label>
<input type="text" name="book-author" placeholder="Author Name" value="<?php echo get_post_meta( $post->ID, 'book-author-key', true );?>">
</div>
<div>
<label for="year">Published Year</label>
<input type="number" id="year" name="year" min="1455" max="2020" value="<?php echo get_post_meta( $post->ID, 'book-year-key', true );?>">
<span id="errorMsg" style="display:none;">Published Year Must be range from 1455 - 2020</span>
</div>
<?php
}
function save_book_meta_data($post_id)
{
if(!isset($_POST['book_cpt_nonce']) || !wp_verify_nonce($_POST['book_cpt_nonce'],basename(__FILE__))){
return $post_id;
}
if (array_key_exists('book-author', $_POST)) {
update_post_meta( $post_id,'book-author-key', $_POST['book-author']
);
}
if (array_key_exists('year', $_POST)) {
update_post_meta( $post_id,'book-year-key', $_POST['year']
);
}
}
add_action('save_post', 'save_book_meta_data');
Related
I'm trying to update a field after submitting in the following form:
<form action="{{ route("comments.update") }}" method="post">
#csrf
<input type="hidden" name="commentIDToEdit" id="commentID">
<div class="md-form mb-5">
<i class="fas fa-comment"></i>
<label for="toEditComment"></label>
<textarea name="toEditCommentary" id="toEditComment" cols="3" rows="5" style="resize: none"
class="form-control"></textarea>
</div>
<div class="modal-footer d-flex justify-content-center">
<button type="submit" class="btn btn-default">Modificar</button>
</div>
</form>
I have the CommentsController, where I process the data from the form. Here is the code:
public function updateComment()
{
request()->validate([
"toEditCommentary" => "min:10|max:500"
]);
if (Session::has("username") && getWarningCount(User::whereUsername(session("username"))->value("email")) > 0) {
Caveat::where("commentID", request("commentIDtoEdit"))
->update(["updatedComment" => request("toEditCommentary")]);
} else {
die("No se cumple la condición");
}
if (Comment::where("commentID", request("commentIDToEdit"))->exists()) {
Comment::where("commentID", request("commentIDToEdit"))
->update(["commentary" => request("toEditCommentary")]);
}
return back();
}
Curiosly, the comment is updated in his table, but not the warning. I was thinking in the fillable property in the model, but I don't have it, instead this, I have the following code:
protected $guarded = [];
const UPDATED_AT = null;
const CREATED_AT = null;
Your hidden input is named commentIDToEdit, but in the Controller you fetch the Caveat using request("commentIDtoEdit") (different case).
What you wrote:
Caveat::where("commentID", request("commentIDtoEdit"))
What you should have done: (note the different casing)
Caveat::where("commentID", request("commentIDToEdit"))
This is because in the view, the input name is commentIDToEdit, not commentIDtoEdit.
I have a form with 3 radio buttons. The IDs are unique in the form, and all three have the same name, namely "vehicle_type". The radio buttons are generated correctly when I do source view
<input type="radio" name="vehicle_type" id="type_vehicle" value="1">
<input type="radio" name="vehicle_type" id="type_trailer" value="2" checked>
<input type="radio" name="vehicle_type" id="type_plant" value="3">
I have no validation rule set for the radio group, yet my form complains that the field is required.
I can confirm that there is no validation rule by running:
echo $this->form_validation->has_rule('vehicle_type');
It indicates no validation. Using that call on another field, i.e., client_name, returns "boolean: 1"
Why would the field try to validate if there is no validation rule set?
EDIT
I am using Wiredesignz HMVC in my project, so the Form_validation class is extended.
if ($this->form_validation->run($this)) {
$test = do_file_upload($post_data);
} else {
var_dump(validation_errors());
// echos "The Vehicle type field is required"
}
This problem only occurs with radio buttons:
All other forms without radio buttons validate correctly using the same check: ($this->form_validation->run($this)
My form validation is set with this function:
public function set_form_validation_rules($data)
{
foreach ($data as $field) {
if (!empty($field['validation']['rules'])) {
if (!is_array($field['validation']['rules'])) {
$this->form_validation->set_rules($field['name'], $field['label'], $field['validation']['rules']);
} else {
foreach ($field['validation']['rules'] as $fv) {
$this->form_validation->set_rules($field['name'], $field['label'], $fv);
}
}
}
}
}
And the radio button is defined as:
$data['fields']['type_plant'] = [
'name' => 'vehicle_type',
'id' => 'type_plant',
'input_class' => 'input-group width-100',
'color' => 'red',
'value' => 3,
'validation' => '',
'checked' => ($posts['vehicle_type'] == 3)
];
The other two radio buttons in the group are the same, just have different values and IDs.
Use this,
$this->form_validation->set_rules('vehicle_type', 'Vehicle type', 'required');
Load library for form validation and other helpers in application/config/autoload.php
$autoload['libraries'] = array('form_validation');
$autoload['helper'] = array('form', 'url');
In your controller file :
$this->form_validation->set_rules('vehicle_type', 'Vehicle Type', 'required');
In your view file use below code for printing validation errors
<?php echo validation_errors(); ?>
The answers given above tells me how to use form validation. It is not what I requested. I am far beyond that - as they all worked, except for radio buttons. As it turns out, passing the validation array incorrectly to the function in the $data array. Once I passed the data correctly, the form validation also worked.
Hey Bro Try this maybe it can help
This method is very simple
In form
<div class="form-group">
<label for="vehicle_type" class="col-sm-3 control-label">vehicle</label>
<div class="col-sm-9">
<div class="col-md-3">
<label><input type="radio" name="vehicle_type" id="vehicle_type" value="1"> ONE </label>
</div>
<div class="col-md-3">
<label><input type="radio" name="vehicle_type" value="2"> TWO </label>
</div>
<div class="col-md-3">
<label><input type="radio" name="vehicle_type" value="3"> THREE </label>
</div>
<small class="info help-block"></small>
</div>
</div>
Set Your Controller
public function add_save(){
if ($this->input->post('vehicle_type') == "1"){
}else if($this->input->post('vehicle_type') == "2"){
}else if($this->input->post('vehicle_type') == "3"){
}else{
$this->form_validation->set_rules('vehicle_type', 'Vehicle', 'required');
}
if ($this->form_validation->run()) {
$save = [
'vehicle_type' => $this->input->post('vehicle_type')
];
$this->model_yourmoderl->add($save);
} else {
$this->data['errors'] = $this->form_validation->error_array();
}
$this->response($this->data);
}
I am getting this error what would be the reason for this
"Undefined variable: quotation"
QuotationController.php
public function update(Request $request, Quotation $quotation)
{
{
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->save();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
}
public function edit(Quotation $quotation)
{
return view('employees.quotations.edit', compact('quotation'));
//return view('employees.quotations.edit')->with('quotation');
}
......................................................................
routes look like this
Route::post('/quotation', 'Employee\QuotationController#store')->name('employee.quotation.store');
Route::get('/quotation', 'Employee\QuotationController#index')->name('employee.quotation.index');
Route::get('/quotation/create', 'Employee\QuotationController#create')->name('employee.quotation.create');
Route::put('/quotation/{quotation}', 'Employee\QuotationController#update')->name('employee.quotation.update');
Route::get('/quotation/{quotation}', 'Employee\QuotationController#show')->name('employee.quotation.show');
Route::delete('/quotation/{quotation}', 'Employee\QuotationController#destroy')->name('employee.quotation.destroy');
Route::get('/quotation/{quotation}/edit', 'Employee\QuotationController#edit')->name('employee.quotation.edit');
employees.quotations.edit.blade.php looks like this
#section('left-menu')
#endsection
#section('right-menu')
#endsection
#section('content')
<h1>Update a Quotation</h1>
<br><br>
<form action="{{ route('employee.quotation.update',$quotation->id) }}" method="post">
#method('PUT')
#csrf
<div class="form-group">
<label for="inputJobDescription">Description</label>
<textarea class="form-control" rows="2" id="inputQuoteDescription" name="description" placeholder="Description">{{$quotation->description}}
</textarea>
</div>
<div class="form-group row">
<label for="inputQty" class="col-2 col-form-label">Qty</label>
<div class="col-10">
<input type="text" class="form-control" id="inputQty" name="qty" value="{{$quotation->qty}}" oninput="quotation_calculate()" onchange="quotation_calculate()">
</div>
</div>
<div class="form-group row">
<label for="inputEachPrice" class="col-2 col-form-label">Each Price</label>
<div class="col-10">
<input type="text" class="form-control" id="inputEachPrice" name="each_price" value="{{$quotation->each_price}}" oninput="quotation_calculate()" onchange="quotation_calculate()">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
#endsection
#section('pagescript')
#stop
What am i missing here ? I am already passing $quotation to the edit view
You are obviously not passing the $quotation variable through your route. You are also using the $quotation as an object; that tells me you don't intend passing it through the route. Try the following code:
public function update(Request $request, $quotation_id)
{
$quotation = Quotation::findOrFail($quotation_id);
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->update();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message) use ($quotation){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
This should work.
Why are you using double brackets to declare a function ? Why not:
public function update(Request $request, Quotation $quotation)
{
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->save();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
I think you need to pass $quotation into the closure:
Mail::send(['text' => 'mail'], $info, function ($message) use ($quotation) {
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com', 'John Doe')->subject('Quotation');
$message->from('from#gmail.com', 'The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
I want to validate three radio button inputs using codeigniter form validation rule:
HTML Page
<form action="<?php echo base_url('register')" ?> method="POST">
<input type="radio" name="cars" value="BMW">
<input type="radio" name="cars" value="Ferrari">
<input type="radio" name="cars" value="Jaguar">
<input type="submit" name="submitter">
</form>
Controller
public function register()
{
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
i know what to do here
}
else
{
i know what to do here
}
}
How to do form validation in codeigniter for radio button in my case ?
Load library for form validation and other helpers in application/config/autoload.php
$autoload['libraries'] = array('form_validation');
$autoload['helper'] = array('form', 'url');
In your controller
public function register()
{
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
echo "success";
}
else
{
$this->load->view('welcome_message');
}
}
In your view file use below code for printing validation errors
<?php echo validation_errors(); ?>
To show form error use form_error() function and to show all error use <?php echo validation_errors(); ?>
HTML PAGE
<form action="<?php echo base_url('register'); ?>" method="POST">
<?php echo form_error('cars'); ?>
<input type="radio" name="cars" value="BMW">
<input type="radio" name="cars" value="Ferrari">
<input type="radio" name="cars" value="Jaguar">
<input type="submit" name="submitter">
</form>
Controller
public function register(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
echo "i know what to do here"; //die;
}
else
{
echo "i know what to do here"; //die;
}
$this->load->view('welcome_message'); // your html view page
}
I think you are looking for in_list validation as an addition to required that has been mentioned by the others.
$this->form_validation->set_rules('cars', 'Cars', 'required|in_list[BMW,Ferrari,Jaguar]');
Also, as a self-reminder, since it took me 1 year to know about this.
I was wondering if some Laravel guys can help out.
I have a form in which i have 2 radio buttons, when the form submits it goes through the validator, if the validator fails it comes back to the form, populates the fields with the input and displays error messages.
I cant seem to do this for radio buttons, if one is clicked when the form is submitted and there was an error, it comes back to the form with everything filled out EXCEPT the radio button that was checked is now empty.
My radio buttons are as follows:
<input type="radio" name="genre" value="M" class="radio" id="male" />
<input type="radio" name="genre" value="F" class="radio" id="female" />
<span class="error">{{ $errors->first('genre') }}</span>
Any help would be greatly appreciated.
You can try this using Laravel's out of the box HTML radio...
Laravel Docs Form checkboxes and Radio
Using blade,
{{ Form::radio('genre', 'M', (Input::old('genre') == 'M'), array('id'=>'male', 'class'=>'radio')) }}
{{ Form::radio('genre', 'F', (Input::old('genre') == 'F'), array('id'=>'female', 'class'=>'radio')) }}
Or just php,
echo Form::radio('genre', 'M', (Input::old('genre') == 'M'), array('id'=>'male', 'class'=>'radio'));
echo Form::radio('genre', 'F', (Input::old('genre') == 'F'), array('id'=>'female', 'class'=>'radio'));
You could do this:
<input type="radio" name="genre" value="M" class="radio" id="male" <?php if(Input::old('genre')== "M") { echo 'checked="checked"'; } ?> >
<input type="radio" name="genre" value="F" class="radio" id="female" <?php if(Input::old('genre')== "F") { echo 'checked="checked"; } ?> >
The bug is known :
- https://github.com/laravel/laravel/issues/2069
- https://github.com/laravel/framework/issues/1564
You have a temporary solution in the second link.
I've just stumbled into this and I don't want to keep repeating such conditions on every form, so I've created a function on my Helper class.
Helper.php:
class Helper {
// other functions
public static function oldRadio($name, $value, $default = false) {
if(empty($name) || empty($value) || !is_bool($default))
return '';
if(null !== Input::old($name)) {
if(Input::old($name) == $value) {
return 'checked';
} else {
return '';
}
} else {
if($default) {
return 'checked';
} else {
return '';
}
}
// Or, short version:
return null !== Input::old($name) ? (Input::old($name) == $value ? 'checked' : '') : ($default ? 'checked' : '');
}
}
So, now on my forms, I just use it like this:
<label>Please select whatever you want</label>
<div class="radio-inline"><label><input type="radio" name="whatever" value="1" required {{ Helper::oldRadio('whatever', '1', true) }}> One</label></div>
<div class="radio-inline"><label><input type="radio" name="whatever" value="2" {{ Helper::oldRadio('whatever', '2') }}> Two</label></div>
<div class="radio-inline"><label><input type="radio" name="whatever" value="3" {{ Helper::oldRadio('whatever', '3') }}> Three</label></div>
Each option passes its name and value to the helper function and the previously selected one will print 'checked'. Additionally, an option can pass 'true' as the third parameter so it gets selected if there was no old input.
Using with the Bootstrap & Automatic checking
Add this code at end of file: app/start/global.php
//...
Form::macro('radio2', function($group ='group-name', $value_model = 'value-model', $label ='label-radio', $value_radio = 'value-radio', $attrs = array())
{
$item = "<div class='radio'>";
$item .= "<label>";
$item .= Form::radio($group, $value_radio, ($value_model == $value_radio) ? true : false, $attrs);
$item .= $label;
$item .= "</label>";
$item .= "</div>";
return $item;
});
In your view.php
{{ Form::radio2('status', Input::old('status'), 'Online', '1', array()) }}
{{ Form::radio2('status', Input::old('status'), 'Offline', '0', array()) }}
Final result:
I tried simply using Input::get() instead of Input::old().... and it's worked!!{{Form::radio('estado','V',(Input::get('estado')=="V"))}}
My approach is a nested shorthand if/else statement with blade syntax. This solution considers also the initial value that is set in the database.
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="sex" id="male" value="male"{!! ((old('sex') == 'male') ? ' checked="checked"' : ((empty(old('sex')) && $user->sex == 'male') ? ' checked="checked"' : '')) !!}/>
<label class="form-check-label" for="male">Männlich</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="sex" id="female" value="female"{!! ((old('sex') == 'female') ? ' checked="checked"' : ((empty(old('sex')) && $user->sex == 'female') ? ' checked="checked"' : '')) !!}/>
<label class="form-check-label" for="female">Weiblich</label>
</div>
Tested with Laravel 5.7.