How do I redirect to my form after a Laravel failed form validation - laravel-5

When there is a failed validation , my form page was redirected to 'localhost' which is the php info page instead of form page to be displayed again. I don't know what's wrong. P. S I'm working with laravel 5.2.35

Try this
return redirect()->back()->with('failAuth', true);
At the page where your form is, you can add this line
<script>
var failAuth = "{{Session:has('failAuth')}}";
if (failAuth)
{
alert("Authentication failed. Please resubmit your form"); //or whatever code you wanna execute
}
</script>
Hope it helps =)

You can use following code to achieve this:
You can refer to this at Laravel Validation
if ($validator->fails()) {
return redirect('your_form_url')
->withErrors($validator)
->withInput($input_variable);//optional
}
You can then display these errors by referencing $errors variable in your view.
Note: The $errors variable is bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

Related

Laravel Livewire how to redirect before render

I want to redirect if Auth::user()->id is not equal to Ad->user_id
it does not work inside the mount or hydrate method.
$this->ad = Ad::where('id', $this->ad_id);
if ($this->ad->user_id != Auth::User()->id) {
return redirect()->route('dashboard');
}
You can redirect from mount() method. You can't redirect inside render as you would need to call return redirect('/') which would throw an error "render" method on [App\Http\Livewire\...] must return instance of [Illuminate\View\View]
function mount(){
if(condition fails){
return redirect()->to('someplace');
}
}
Livewire does not do backend redirects as far as I experienced, but rather uses JS to do them. So if you use the $this->redirect method, it will tell rendered component to perform the redirect. Some solutions I've seen on the web were in the render function, if you have an issue that results in a redirect being required, create an empty blade file with a simple div inside, and everywhere you need to redirect the user, set the render view as the blank one, and the FE will take the redirect. A pretty messy fix, but I did not see any better ones currently.
I tried everything but below-mentioned trick worked for me.
Rather than routing from the livewire component we can route from the livewire blade component by adding below code.
#php
$carts = \Cart::getContent();
if(count($carts) == 0)
{
$this->redirect('/shopping-cart/bag');
}
#endphp
Suggestions:
Don't use "return" while redirecting otherwise you might face some Front-end issues.
Don't use "route" while redirecting otherwise the code won't work.

How to repopulate form after form validation and also keep the URI?

I have a problem repopulating my form after validation fails. Problem is my url contains an additional uri which I access by clicking a link. This is what it looks like:
http://www.example.com/admin/trivia/add/5
At first trouble was that the segment 4 of the uri completely disappeared, so even though the validation errors showed and the form was repopulated, I lost my added uri.
Then I found in another question that the solution was to set form open like this:
echo form_open(current_url());
Problem is now it isn't showing any validation errors and the form is not repopulated. Is there a way to achieve this?
This is what my controller looks like:
function add()
{
$data = array('id' => $this->uri->segment(4));
if($_POST)
{
$this->_processForm();
}
$this->load->view('admin/trivia_form', $data);
}
And inside _processForm() I got all the validation rules, error message and redirecting in case success.
[edit] Here is my _processForm() :
function _processForm()
{
$this->load->library('form_validation');
//validation rules go here
//validation error messages
$this->form_validation->set_rules($rules);
$this->form_validation->set_error_delimiters('<div style="color:red">', '</div>');
if ($this->form_validation->run())
{
//get input from form and assign it to array
//save data in DB with model
if($this->madmin->save_trivia($fields))
{
//if save is correct, then redirect
}
else
{
//if not show errors, no redirecting.
}
}//end if validation
}
To keep the same url, you can do all things in a same controller function.
In your controller
function add($id)
{
if($this->input->server('REQUEST_METHOD') === 'POST')// form submitted
{
// do form action code
// redirect if success
}
// do your actual stuff to load. you may get validation error in view file as usual if validation failed
}
to repopulate the form fields you are going to need to reset the field values when submitting it as exampled here and to meke it open the same page you can use redirect() function as bellow:
redirect('trivia/add/5','refresh');
i don't know what you are trying to do, but try this to repopulate the form with the values user entered
<?php
echo form_input('myfield',set_value('myfield'),'placeholder="xyz"');
?>

ZF2 Session not lasting on redirect

My site uses multiple languages and my users can click on flags to set their desired language. When that flag is clicked, a Session should store that information and then i want my controller to redirect the user to another page. This i do with the following code:
<?php
public function setLangAction () {
$oLanguageCookie = new Container('language');
$oLanguageCookie->lang = $this->params ('langvar');
$this->redirect()->toRoute('loadpage', array('page' => 'home'));
}
?>
However, when i print_r($_SESSION) in the indexAction (the action where loadpage routes to), $_SESSION is empty.
Can somebody help me?
Depending where you param comes from you should execute
$this->params()->fromQuery('langvar');
$this->params()->fromPost('langvar');
unless it is a route parameter then you can use either:
$this->params()->fromRoute('langvar');
$this->params('langvar');

JToolbar::save() redirection

I'm going through the Joomla 2.5 tutorial to build a custom component. Now I'm facing an issue on the redirection after using JToolbar::save() or JToolBarHelper::cancel for that matter. By default Joomla wants to redirect to the default layout (from the edit layout). However I don't want it to do that. I want it to redirect back to another view. In Joomla 1.5 I would have done this through adding the function into the controller - something like
function cancel()
{
//redirects user back to blog homepage with Cancellation Message
$msg = JText::_( 'COM_BLOG_POST_CANCELLED' );
$this->setRedirect( 'index.php?option=com_jjblog&view=jjblog', $msg );
}
Now that works beautifully for the cancel function, however for save this is a much more complex thing. If I want to overwrite the url do I have to redirect the controller to the model and then write in all the code for the model interaction? Because that seems slightly excessive just for a url redirection like you would in Joomla 1.5?
Hope you have added the save toolbar code with the proper controller name like this
JToolBarHelper::save('controllerName.save');
Create a save function in appropriate controller.
Add the task in the form
Finnally make sure you have added form action withthe corresponding component name.
You can try this-
In the controller firstly you call the parent save function than redirect to url.
function save(){
parent::save();
$this->setredirect('index.php?option=com_mycomponent');
}
OK it didn't need to $this->setRedirect at all. Just needed me to change the value to
protected $view_list = 'jjBlog';
which then sets the redirects of everything back to that list view.
Source link for this is here.
Thanks for all the responses though!!
view.html.php
protected function addToolbar ()
{
JRequest::setVar ('hidemainmenu', false);
JToolBarHelper::title (JText::_ ('Configuration'), 'configuration.gif');
JToolBarHelper::save($task = 'save', $alt = 'JTOOLBAR_SAVE');
}
controller.php
public function save()
{
$mainframe = JFactory::getApplication();
$mainframe->enqueueMessage (JText::_ ('COM_SOCIALLOGIN_SETTING_SAVED'));
$this->setRedirect (JRoute::_ ('index.php', false));
}
I think you can use
global $mainframe;
$mainframe->redirect("index.php?option=com_user&task=activate&activation=".$activation);
If you are overriding joomla's default save function in your custom component like
function save( $task = 'CustomSave', $alt = 'Save' ) // or even same name Save
Inside your controller you can use the CustomSave as the task and use $mainframe for redirect.
or
$mainframe = &JFactory::getApplication();
$mainframe->redirect("index.php?option=com_user&task=activate&activation=".$activation);
Hope this may help you..

codeigniter : using flash data but no new page load?

Usually, I just set a $feedback var or array and then check for that to display in my views.
However, it occurred to me I should perhaps use flashdata instead.
The problem is sometimes - for say an edit record form, I may simply want to reload the form and display feedback - not redirect. when i use flashdata, it shows but then it shows on the next request as well.
What would be the best practice to use here?
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.
u use hidden field for that
I would use the validation errors from the Form validation class and load those directly to the view in its 2nd argument.
$this->form_validation->set_error_delimiters('<p>', '</p>');
$content_data = array();
if (!$this->form_validation->run()) {
$content_data['errors'] = validation_errors();
}
$this->load->view('output_page', $content_data);
Then check in your view whether $errors isset.
Controller:
$data['message'] = 'some message you want to see on the form';
$this->load->view('yourView', $data);
View:
if (isset ($message)) : echo $message; endif;
...

Resources