ZF3 redirect()->toUrl() not redirecting - redirect

I'm having a weird issue with ZF3.
I have a vanilla form in the view and a jquery ajax to send it to the controller, something like this:
<form>some form</form>
<script>
$("#form").submit(function (e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "stats",
data: {name: 'TEST'} // name selected in the form
});
});
</script>
The controller for action stats looks like this:
$stat = new Stat();
$route_name = $this->params()->fromRoute('name', 'none');
$post_name = $this->params()->fromPost('name', 'none');
if(!strcmp($route_name, 'none')) // if no redirection yet
{
if(!strcmp($post_name, 'none')) // if no form was sent
{
// display the form to choose the customer
return new ViewModel([
'customer_list' => $stat->get_customer_list(),
]);
}
else // if the form was sent, get name and direct to /stats/someName
{
return $this->redirect()->toRoute('stats', ['name' => 'someName']);
}
}
else // after redirection, get the name in the URL and show some data about this customer
{
return new ViewModel([
'avg_time' => $stat->get_avg_time(rawurldecode($route_name)),
]);
}
The problem is that the redirection does not occure on the screen but I still get the route parameter if I print $route_name after submitting the form.
Anyway, the goal is to have a form with a select to choose the customer name and load the customer data into /stats/[name]. Am I going in the wrong direction ? And is the redirection issue a bug or my code is wrong ?

So there I solved it thx to rkeet, this is the form & jquery:
<form id="customer_choice" method="POST" action=""> some form </form>
<script>
$("#customer_choice").submit(function () {
$("#customer_choice").attr('action', 'stats/' + $("#customer_select").val())
});
</script>
And this is the controller (hope no customer is named 'none'):
$stat = new Stat();
$name = $this->params()->fromRoute('name', 'none');
if(!strcmp($name, 'none'))
{
return new ViewModel([
'customer_list' => $stat->get_customer_list(),
]);
}
else
{
return new ViewModel([
'avg_time' => $stat->get_avg_time($name),
]);
}
The result is basepath/stats/[customer name] and changing the url manually works as well.
(if you don't want changing the url manually to change the result, use fromPost instead of fromRoute)

Related

invisible reCAPTCHA javascript

I have the invisible reCAPTCHA set up, but it doesn't seem to want to call my callback function. My form looks like:
<form id='ContactAgentForm' name='ContactAgentForm' class='custom-form-widget-form standard_form' action='contact_agent' listing_id=1233445>
...
<div class='field captcha-field recaptcha_field' >
<div id='g-recaptcha-div' class="g-recaptcha" ></div>
</div>
...
<div class="field button-field">
<button class="button button-primary"><span>Send</span></button>
<a class="button button-cancel btn-close" href="#cancel"><span>Cancel</span></a>
</div>
</form>
In the javascript, I want to handle the fact that there might be multiple forms on the page, so I create a list of all the forms. For each form, I attach/render the reCAPTCHA logic, attaching my callback with the form passed as a parameter:
<script>
var $form_list = jQuery("form.custom-form-widget-form");
var onFormPageSubmit = function(token, $form ) {
console.log("Got here! ", token );
var field = $form.find('.g-recaptcha-response')[0];
field.value = token;
$form[0].submit();
};
var onloadCallback = function() {
$form_list.each( function() {
var $form = jQuery(this);
var $recaptcha = $form.find( ".g-recaptcha" );
if ( $recaptcha.length )
{
var recaptchaId = grecaptcha.render($recaptcha[0], {
'callback': function (token) { onFormPageSubmit(token, $form); },
'sitekey': "{$captcha_config.invisible_captcha_site_key}",
'size': 'invisible',
'badge': 'inline'
});
$form.data("recaptchaid", recaptchaId);
}
});
};
</script>
And just below that, I load the recaptcha/api.js file:
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onloadCallback"></script>
With some judicial 'console.log' statements, we get through all of the code EXCEPT for the callback (onFormPageSubmit). The "protected by reCAPTCHA" logo is there, but it seems that the form is just submitted, ignoring the reCAPTCHA call altogether.
All help appreciated.
Somewhere along the line, the validation function for the form was lost (it's in another file). The validation function was attached to the button, and it executed something like this:
$submit_button.on( 'click', function( event ) {
event.preventDefault();
// get the recaptchaid from form data
var $recaptcha_id = $form.data( "recaptchaid" );
if ( $recaptcha_id != undefined )
{
grecaptcha.execute($recaptcha_id);
}
} );
The "grecaptcha.execute" is the important thing - this is what triggers the actual reCAPTCHA call.

how multiple row delete using checkbox in yii2

How can I use in GridView delete selected object,in Yii 2 Framework such as following image:
[enter image description here][2]
Try this
<?=Html::beginForm(['controller/bulk'],'post');?>
<?=Html::dropDownList('action','',[''=>'Mark selected as: ','c'=>'Confirmed','nc'=>'No Confirmed'],['class'=>'dropdown',])?>
<?=Html::submitButton('Send', ['class' => 'btn btn-info',]);?>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'id',
],
]); ?>
<?= Html::endForm();?>
This is the controller:
public function actionBulk(){
$action=Yii::$app->request->post('action');
$selection=(array)Yii::$app->request->post('selection');//typecasting
foreach($selection as $id){
$e=Evento::findOne((int)$id);//make a typecasting
//do your stuff
$e->save();
}
}
Or Else
Follow all the steps given in this Link, You will Surely achive your goal.
Yii 2 : how to bulk delete data in kartik grid view?
https://stackoverflow.com/questions/27397588/yii-2-how-to-bulk-delete-data-in-kartik-grid-view/
You can use a column with checkboxes and bulk actions for each row selected.
Here is a related question:
Yii2 How to properly create checkbox column in gridview for bulk actions?
<?php
$url = Url::to(['user/delete']);
$this->registerJs('
$(document).on("click", "#delete_btn",function(event){
event.preventDefault();
var grid = $(this).data(\'grid\');
var Ids = $(\'#\'+grid).yiiGridView(\'getSelectedRows\');
var status = $(this).data(\'status\');
if(Ids.length > 0){
if(confirm("Are You Sure To Delete Selected Record !")){
$.ajax({
type: \'POST\',
url : \''.$url.'\' ,
data : {ids: Ids},
dataType : \'JSON\',
success : function($resp) {
if($resp.success){
alert(resp.msg);
}
}
});
}
}else{
alert(\'Please Select Record \');
}
});
', \yii\web\View::POS_READY);
?>
[1]: http://i.stack.imgur.com/iFjT1.png
I have succeeded in deleting multiple rows in gridview Yii2 by doing the following:
Create button in index.php
<p>
<button type="button" onclick="getRows()" class="btn btn-success">Delete Bulk</button>
</p>
Add javascript code in index.php to perform the event of getting the checked rows from the GridView widget.
<script>
function getRows()
{
//var user_id as row_id from the gridview column
// var list = [] is an array for storing the values selected from the //gridview
// so as to post to the controller.
var user_id;
var list = [];
//input[name="selection[]"] this can be seen by inspecting the checkbox from your //gridview
$('input[name="selection[]"]:checked').each(function(){
user_id = this.value;
list.push(user_id);
});
$.ajax({
type: 'post',
url:'index.php?r=student-detail-update/bulk',
data: {selection: list},
});
}
</script>
Put this code in your contoller
if ($selection=(array)Yii::$app->request->post('selection')) {
foreach($selection as $id){
$StudentDetailUpdates = StudentDetailUpdate::find()
->where(['user_id' => $id])
->all(); //....put your staff here
}

Keep select value on change with laravel

I am having a paginated backend table with db-data. The admin person can filter that table for data status. This happens via ajax. Everything works fine but I do not get the selected filter value to remain selected when I click on the second pagination link.
E.g. I choose select option: '1' => 'Active' so that only db-rows show up that have a status of 1. But when I then click on the second pagination link to see the next 20 rows then again it also displays the inactive db-rows. How would I get the selected option to remain selected in this situation? I tried Input::old('status') and passing $selected to view as below but no success. Thank you for any hint!
View:
<form id="filter_form" onsubmit="" action="<?php echo URL::action('countries#anyIndex'); ?>">
<?php echo Form::select('filter_status', funcs::get_status_options(), $selected, array('id' => 'filter_status')); ?>
</form>
Ajax:
$(function(){
$("#filter_status").on('change', function(){
frm = $("#filter_form");
frm.serialize();
status = $('#filter_status').val();
$.ajax({
type: "POST",
url: $(frm).attr('action'),
data: {status: status},
success: function(data){
$("#list").html(data.list);
},
dataType: "json"
});
});
});
Controller:
class countries extends BaseController {
public $filter = array(0,1,2);
function anyIndex()
{
$data['title'] = "Countries list";
if(Input::has('status')){
$status = Input::get('status');
if($status != 2){
$this->filter = array($status);
}
}
$d['items'] = $this->_getItems(20);
if(Request::ajax()){
$data['list'] = View::make('admin/countries/countries_list', $d)->withInput($status)->render();
return Response::json($data);
}
$data['selected'] = $this->filter;
$data['list'] = View::make('admin/countries/countries_list', $d);
return View::make('admin/admin_layout')->nest('view', 'admin/countries/countries_view', $data);
}
private function _getItems($paginate)
{
$items = Country::whereIn('status', $this->filter)->paginate($paginate);
return $items;
}
}

Zend: Redirect from form without validation

I have a form for the creation of new "groups". I now added a small "go back" image with which the user should be able to go back one step. I don't know why, but when I click this new image, the controller and action used for the form which I want to leave (/admin/creategroup) is called again with HTTP POST set. Therefore, the form validation is done, and I'm stuck at this form with the validation errors displayed.
This is a snippet of the code from my form with both image-buttons. I wan't the "go back"-image to redirect me to the specified controller without validating the form:
$this->addElement('image', 'btnBack', array (
'name' => 'btnBack',
'id' => 'btnBack',
'label' => '',
'title' => 'Go back',
'alt' => 'Go back',
'src' => '/img/undo.png',
'onClick' => "window.location='/admin/groupoverview'"
));
$this->addElement('image', 'btnSave', array (
'name' => 'btnSave',
'id' => 'btnSave',
'label' => '',
'title' => 'Save this new group',
'alt' => 'Save this new group',
'src' => '/img/save.png',
'onClick' => "document.forms[0].submit();"
));
Edit:
I already thought of the possibility to check in /admin/creategroup whether it was called from the 'btnBack'-image or the 'btnSave'-image and skip form validation and redirect correctly if the source was the 'btnBack'-image.
I just think that there should be a nicer solution to directly redirect from the form and circumvent calling /admin/creategroup again.
Edit2:
My view script:
<div id="createGroupMask">
<br/>
Use the form below to create a new group
<?php
$this->form->setAction($this->url());
echo $this->form;
?>
</div>
My action in the controller:
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
// Data for new group is valid
...
} else {
// Form data was invalid
// => This is where I land when pressing the 'back' image
// No further code here
}
}
$this->view->form = $form;
}
Now there is something to work with:
The isValid() loop is incorrect, your form will never evaluate as inValid with respect to the elements you've presented, you will never get to the else.
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
// Data for new group is valid
...
} else {
/* This is incorrect */
// Form data was invalid
// => This is where I land when pressing the 'back' image
// No further code here
}
}
$this->view->form = $form;
}
My problem is that I'm not sure what is going to be submitted from your form, I'm not really familiar with how your using "onClick" and what I presume is javascript. It looks like element btnBack should redirect on click and element btnSave should POST. However this does not seem to be happening.
I have done this type of thing in PHP and ZF with submit buttons, perhaps the flow of what I did will help:
NOTE: for this type of flow to work you must give the button element a label. The label is used as the submit value.
//psuedoCode
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
//I would probably opt to perform this task with a switch loop
if ($form->getValue('btnBack') === some true value) {
$this->_redirect('new url');
}
if ($form->getValue('btnSave') === some true value) {
//Process and save data
}
} else {
//Display form errors
}
$this->view->form = $form;
}
I think when all is said and done the crux of your problem is that you did not give your button elements a label.
I tried adding labels to my images, but this didn't work.
I also tried to use the isChecked() method on my btnBack-image like this:
if ($form->btnBack->isChecked()) {
// 'Go back' image was clicked so this is no real error, just redirect
}
This didn't work either.
I finally was able to check which image was clicked via the following method as answered in Zend form: image as submit button:
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
// Data for new group is valid
...
} else {
// Form data was invalid
if (isset($this->_request->btnBack_x)) {
// 'Go back' image was pressed, so this is no error
// -> redirect to group overview page
$this->_redirect('/admin/groupoverview');
}
}
}
$this->view->form = $form;
}
I guess this doesn't thoroughly answer the original question as the validation is still done and I'm only checking for this 'special case' where the 'Go back' image was clicked, but I'll mark it as answered anyways.
Tim Fountain suggested an even cleaner approach in my somewhat related question:
Zend forms: How to surround an image-element with a hyperlink?

Confirmation Dialog in Zend Framework

I'm building a Zend Application using doctrine repository classes to update, delete and insert data to the DB. These repositories are called from controller actions and they do exactly what they supposed to do. However, I'd like to add some confirmation dialogs to the application, so for example, if a user wants to edit or delete an item, a Confirm Edit or Delete dialog must first be opened and the data will be edited or deleted depending on what the user selects. Here's an example of some action code for updating a staff members details after the user has clicked on a zend form submit button.
public function updatestaffAction()
{
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$values = $form->getValues();
$user = $this->entityManager->find('\PTS\Entity\Staff', $values['staff_number']);
$staffValues = array('staff_number' => $values['staff_number'],
'title' => $values['title'],
'first_name' => $values['first_name'],
'last_name' => $values['last_name'],
'telephone' => $values['telephone'],
'cellphone' => $values['cellphone'],
'fax' => $values['fax'],
'email' => $values['email'],
'job_title' => $values['job_title']);
$this->staffRepository->saveStaff($staffValues);
$this->entityManager->flush();
}
}
The staff repository saveStaff method simply creates a new Staff object and persists that object if the staff member doesn't exists, or merges the new data if it's an existing staff member as is the case for the update code above.
So my question is, how can I change the action to only save the data once the user has clicked the yes button in a confirmation dialog. BTW, the dialog can be either a JQuery or Dojo dialog box.
When you create form's submit button, set js code:
$submit = new Zend_Form_Element_Submit('delete');
$submit->setAttrib(
'onclick',
'if (confirm("Are you sure?")) { document.form.submit(); } return false;'
);
Or, if you want to set dialogbox on link (if you don't have submit form):
onclick="if (confirm('Are you sure?')) { document.location = this.href; } return false;"
Code for showDialog:
$(function() {
$( "#dialog:ui-dialog" ).dialog( "destroy" );
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Are you sure": function() {
// PUT your code for OK button, for eg.
document.form.submit();
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});`
Thx, I used the second option like this way :
Delete
and it's worked :)