How can I make the href for a button use urls.py? - django-crispy-forms

I need to add a 'Cancel' button to my ModelForm, I am using crispy forms but when I add href='personnel-index' to redirect back to the list view, it does not. I've checked their documentation but no luck nor any luck on Google.

Sometimes the browser's 'Back' button does just as well as a 'Cancel' button in a web form, but if you are absolutely sure you need one, you can always use the HTML object in crispy forms. Something like this would work:
HTML("""<a class="classes-for-styling" href="/personnel/list/">Cancel</a>""")
And, even better, you can include context aware tags to avoid hard-coding urls into your form:
HTML("""<a class="classes-for-styling" href="{% url 'personnel-index' %}">Cancel</a>""")
Then it's just up to you to style your link so it looks like a button.

Not necessarily ideal, but this should handle most situations.
self.helper.add_input(Button('cancel', 'Cancel', css_class='btn-default', onclick="window.history.back()"))

Sorry, I can't comment the existing solution because my reputation isn't good enough. That's why I am adding the code example for HTML (crispy form object) solution that was proposed above:
class MoodForm(forms.ModelForm):
class Meta:
model = Mood
def __init__(self, *args, **kw):
super(MoodForm, self).__init__(*args, **kw)
self.helper = FormHelper()
layout = Layout(
ButtonHolder(
Submit('Save', 'Save', css_class='button white'),
HTML('<a class="btn btn-warning" href={% url "mood:list" %}>Cancel</a>'),
),
)
self.helper.add_layout(layout)
The most important stuff here is:
ButtonHolder(
Submit('Save', 'Save', css_class='button white'),
HTML('<a class="btn btn-warning" href={% url "mood:list" %}>Cancel</a>'),
)
It renders two buttons 'Save' and 'Cancel'.

Related

laravel backup raising 404 to return a view

In short what is happening is, when I try to access a route, Laravel shows a 404 error, with a short description "Page not Found, No query results for model [App\Models\Product] teste ".
Inside of my model I have the method "teste" which invokes a route.
public function teste($crud = false)
{
return '<a class="btn btn-xs btn-default" href="product/teste" data-toggle="tooltip" title="Just a demo custom button."><i class="fa fa-search"></i> Add Item</a>';
}
button image in the datatable line
Adding a button inside of ProductCrudController
$this->crud->addButton('top', 'bteste', 'model_function', 'teste', 'beginning');
Inside of custom.php I have tried already:
CRUD::resource('product/teste', 'ProductCrudController#teste');
Route::get('product/teste', 'ProductCrudController#teste');
Inside of my Controller I have my method named teste
public function teste(){
return view('vendor/backpack/crud/teste');
}
And finally inside of this path I have my view "which is pretty simple" and only retues a simple hello.
What is the purpose
I need to build a form which allows the user to add "a component" for the product once that the product is always customized. This means, a combination of components makes up a new product.
What I need is: Add a new button in the product line which when clicked gonna redirect the user to add all components which makes up this product. Same idea of an order which contain items.
I could not find by myself the possible options to fit my need.
Is that possible to be done by backpack? If so is there any example to be followed?
Thanks

Passing name of button on click to controller in web2py

Basically what i want is that in my view file i have a list of various restaurants,and in front of each of them is a "show" button,which on clicking should display three more buttons(dynamically),where each button performs some action regarding the corresponding restaurant name(like show menu,show reviews)(this action should be dynamic too). Can anybody help me with this implementation.
In the view you can place a link and a target container:
{{=A('the link', callback=URL('controller', 'function', args=[my_arg]), target="callback-target", _class="btn btn-default")}}
<div id="callback-target"></div>
If the link is clicked the function in controller is called and you can read the argument my_arg with:
def function():
data = request.args(0)
response.flash('Data received!')
return DIV('Return anything ...')
The returned data is displayed in <div id="callback-target"></div>

Best way to create an Ajax Image ActionLink

I want to create in ASP.NET MVC 3 a link (in Ajax) with an image as background and no text. I'm using this method that creates an ajax link manually:
<div class="icon icon_like"></div>
The div tag calls the class "icon icon_like" of CSS that will import an image.
My question, is the following:
There is no other way (maybe a helper) to being able to do this easily?
UPDATE:
gdoron redirected me to a good link but it was not quite what I wanted (no Ajax support). For me, the first torm's answer is better, I only made some few changes to make it universal:
First in the helper it supports now a routeValues and changing the section that is to be updated
#helper AjaxImageLink(string action, Object routeValues, string icon_name, string sectionToUpdate = "#result"){
<div class="icon #icon_name"></div>
}
About the use of that helper I'm using for the example in question:
#AjaxImageLink("Like", new { controller = "Article", like = 1, id = Model.Item1.ID }, "icon_like")
And it works as it should.
To be compliant with DRY principle you can easily wrap your link structure in an inline helper like :
#helper AjaxLink(string action, string controller, string icon_name){
<div class="icon #icon_name"></div>
}
other way would be to take ajax portion to unobtrusive reusable jquery binding :
</div>
$('.ajaxLink').click(function (e) {
e.preventDefault();
$("#result").load($(this).attr("href");
});
You can see this question.
There are many others examples for it in the internet just google "asp.net mvc image action link"
use ajax.actionlink inside html.Raw and replace ajax.actionlink text with image tag.
simple one line code.
#Html.Raw(#Ajax.ActionLink("[replacetext]", "Action", "Controller", new AjaxOptions { HttpMethod="Post"}).ToHtmlString().Replace("[replacetext]", ""))

web2py button with action and visual pudates

I have a view with a button and a DIV
I am trying to have this kind of functionality:
if the button is clicked - a controller method is executed ( i have the method, db.insert, etc.)
- if test (inside the controller method) is passed the button dissapears and the div appears ( I thought at using ajax - not to refresh the hole page)
whenever the page is refreshed the test has to be made again for the button to be visible or not
thanks
Something like this?
{{=DIV(A('click me',callback=URL('mycallback'),target="me"),_id="me")}}
def mycallback():
# do whatever you need to do
return DIV("I will appear in place of he link when you click")
I looked in more of your examples and I think my problem was simpler ( if there isn't any other solution)
So what I did was I used eval:
button in view :
<input id="b_normal" type="button" value="normal" onClick="ajax('{{=URL('db_test')}}',[],':eval')" />
and the controller method:
def db_test()
#tests and updates
return "jQuery('#b_normal').fadeOut();jQuery('#commDiv').show();"
for further refresh i used jquery, in view:
jQuery(document).ready(function(){
var flag = '{{=flag_normal}}';
if(flag == 'da')
jQuery('#b_normal').hide();
else jQuery('#commDiv').hide();
});
where *flag_normal* is sent by the main controller
I hope this is not too inefficient and if so, useful

Yii, ajax, Button. How to prevent multiple JS onclick bindings

(First of all English is not my native language, I'm sorry if I'll probably be mistaken).
I've created Yii Web app where is input form on the main page which appears after button click through ajax request. There is a "Cancel" button on the form that makes div with form invisible. If I click "Show form" and "Cancel" N times and then submit a form with data the request is repeating N times. Obviously, browser binds onclick event to the submit button every time form appears. Can anybody explain how to prevent it?
Thank you!
I've had the exact same problem and there was a discussion about it in the Yii Forum.
This basically happens because you are probably returning ajax results with "render()" instead or renderPartial(). This adds the javascript code every time to activate all ajax buttons. If they were already active they will now be triggered twice. So the solution is to use renderPartial(). Either use render the first time only and then renderPartial(), or use renderPartial() from the start but make sure the "processOutput" parameter is only set to TRUE the first time.
Solved!
There was two steps:
First one. I decided to add JS code to my CHtml::ajaxSubmitButton instance that unbind 'onclick' event on this very button after click. No success!
Back to work. After two hours of digging I realized than when you click 'Submit' button it raises not only 'click' event. It raises 'submit' event too. So you need to unbind any event from whole form, not only button!
Here is my code:
echo CHtml::submitButton($diary->isNewRecord ? 'Создать' : 'Сохранить', array('id' => 'newRecSubmit'));
Yii::app()->clientScript->registerScript('btnNewRec', "
var clickNewRec = function()
{
jQuery.ajax({
'success': function(data) {
$('#ui-tabs-1').empty();
$('#ui-tabs-1').append(data);
},
'type': 'POST',
'url': '".$this->createUrl('/diary/newRecord')."',
'cache': false,
'data': jQuery(this).parents('form').serialize()
});
$('#new-rec-form').unbind();
return false;
}
$('#newRecSubmit').unbind('click').click(clickNewRec);
");
Hope it'll help somebody.
I just run into the same problem, the fix is in the line that starts with 'beforeSend'. jQuery undelegate() function removes a handler from the event for all elements which match the current selector.
<?php echo CHtml::ajaxSubmitButton(
$model->isNewRecord ? 'Add week(s)' : 'Save',
array('buckets/create/'.$other['id'].'/'.$other['type']),
array(
'update'=>'#addWeek',
'type'=>'POST',
'dataType'=>'json',
'beforeSend'=>'function(){$("body").undelegate("#addWeeksAjax","click");}',
'success'=>'js:function(data) {
var a=[];
}',
),
array('id'=>'addWeeksAjax')
); ?>
In my example I've added the tag id with value 'addWeeksAjax' to the button generated by Yii so I can target it with jQuery undelegate() function.
I solved this problem in my project this way, it may not be a good way, but works fine for me: i just added unique 'id' to ajax properties (in my case smth like
<?=CHtml::ajaxLink('<i class="icon-trash"></i>',
$this->createUrl('afisha/DeletePlaceAjax',
array('id'=>$value['id'])),
array('update'=>'.data',
'beforeSend' => 'function(){$(".table").addClass("loading");}',
'complete' => 'function(){$(".table").removeClass("loading");}'),
array('confirm'=>"Уверены?",'id'=>md5($value['id']).time()))
?>
).
Of course, you should call renderPartial with property 'processOutput'=true. After that, everything works well, because every new element has got only one binded js-action.
text below copied from here http://www.yiiframework.com/forum/index.php/topic/14562-ajaxsubmitbutton-submit-multiple-times-problem/
common issue...
yii ajax stuff not working properly if you have more than one, and if
you not set unique ID
you should make sure that everything have unique ID every time...
and you should know that if you load form via ajax - yii not working
well with it, cause it has some bugs in the javascript code, with die
and live
In my opinion you should use jQuery.on function. This will fire up event on dynamically changed content. For example: you're downloading some list of images, and populate them on site with new control buttons (view, edit, remove). Example structure could looks like that:
<div id="img_35" class='img-layer'>
<img src='path.jpg'>
<button class='view' ... />
<button class='edit' ... />
<button class='delete' ... />
</div>
Then, proper JS could look like this ( only for delete, others are similiar ):
<script type="text/javascript">
$(document).on('click', '.img-layer .delete', function() {
var imgId = String($(this).parent().attr('id)).split('_')[1]; //obtain img ID
$.ajax({
url: 'http://www.some.ajax/url',
type : 'POST',
data: {
id: imgId
}
}).done({
alert('Success!');
}).fail({
alert('fail :(');
});
}
</script>
After that you don't have to bind and unbind each element when it has to be appear on your page. Also, this solutiion os simple and it's code-clean. This is also easy to locate and modify in code.
I hope, this could be usefull for someone.
Regards
. Simon

Resources