How to get user_token value from the URL - twig

In an OpenCart framework version, 3.0.2.x, for the
URL = http://localhost/moreshop/admin/index.php?route=account/apisync&user_token=FARboCmeZHqQl8bITE3SRTenJscadbYc
I need to get the URL value from the parameter user_token that is written in the .twig format
Previously with OpenCart version 2.3.x.x, this was written in the .tpl file as
<input type="hidden" name="token" id="token" value="<?php echo $_GET['token']; ?>"/>
I had tried to assign the value =
{{ app.request.query.all }}
{{ app.request.query.get('user_token') }}
{{ app.request.get('user_token') }}
{{ _GET.user_token }}
But all the above value assigned with null. So how do I get the value of the user_token and assign into value=?

You should define it in your controller file:
$data['user_token'] = $this->session->data['user_token'];
Than you can call it in twig file:
<input type="hidden" name="User_token" id="user_token" value="{{ user_token }}"/>
you also can try call it {{ _GET.token }}

Alternative Solution: (This is not the exact solution to the question posted )
I had used JavaScript to catch hold of the user_token value and then pass it to AJAX in order to redirect to the particular URL
function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName, i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var user_token = getUrlParameter('user_token');
console.log(user_token);
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>

Related

how to get single value from input name field instead of array in NodeJS

I am trying to delete elements from the note list. when I try to match a single name to a list title, it shows an array of items.
i want to match
const input name ===day
and output should be "home" from input name field
but it show ["home","home","home","home"]
here is my delete form code:
<form action="/delete" method="POST">
<% for (let i=0; i<newListItems.length; i++) { %>
<div class="item">
<input type="checkbox" onChange="this.form.submit()" name="checkboxname" value="<%=newListItems[i]._id%>">
<p><%= newListItems[i].name %></p>
</div>
<input type="hidden" name="listName" value="<%= listTitle %>"></input>
<% } %>
</form>
app.js code:
app.post("/delete", function (req, res) {
const deleteItem = req.body.checkboxname
const listName = req.body.listName
console.log(listName)
if (listName === day) {
console.log("hello")
} else {
console.log("custome list value")
}
})
There is 4 hidden inputs rendered with same name listName.
So your request payload will be fulfilled with array of values from all of these inputs.
Move hidden input outside of PHP loop.
The point is to make one input with name='listName' instead of four

how to add specific comment to post in django post

I have posts that, user can add comments to, but i unable to add those comments to that specific posts, here is the code that I'm following:-
the code is working fine with models and the only issue is when comment added, its added to only one post, rather than specific comment to specific post
HTML Code
<div class="quote-comment-box">
<form method="POST" class="com">
{% csrf_token %}
<input placeholder="Your thought" type="text" name="quote-comment" class="comment-input" id="{{ quote.id }}" title="{{ quote.user.id }}" data="{{ request.user }}">
<button type="submit" href="{% url 'micro__blog:quote_comment' %}" class="comment-button">POST</button>
</form>
<div class="content" id="content">
</div>
</div>
js code
$('.comment-button').click(function (params) {
csrftoken()
var index = $('.comment-button').index(this)
var comment = $( ".comment-input" ).eq(index).val()
var id = $( ".content" ).eq(index).attr('id')
params.preventDefault()
$.ajax({
url:$(this).attr("href"),
data:{
'blog_id' : $( '.comment-input' ).eq(index).attr('id'),
'blog_user' : $( '.comment-input' ).eq(index).attr('title'),
'comment' : $( ".comment-input" ).eq(index).val(),
},
type:'POST',
dataType: 'json',
success: function (res, status) {
if (res['status'] == 'ok') {
$('.comment-input').eq(index).val('');
var content = $('.content').eq(index)
console.log(index, content)
const div = document.createElement('div');
div.className = "comment-added"
div.innerHTML = `
<span class="user">` + $( ".comment-input" ).eq(index).attr('data') + `</span>
<span class="text">` + comment + `</span>`;
document.getElementById('content').appendChild(div);
console.log(res.status)
} else {
console.log(res.status)
}
},
error: function (res) {
console.log(res.status);
}
})
Here is view code
def quote_comment(request):
if request.method == 'POST':
blog_id = request.POST.get('blog_id')
blog_user = request.POST.get('blog_user')
comment = request.POST.get('comment')
current_user = User.objects.get(id = request.user.id)
if blog_id and blog_user and comment and current_user:
blog_id = Quote.objects.get(id = blog_id)
blog_user = User.objects.get(id=blog_user)
try:
QuoteComment.objects.get_or_create(user=current_user,blog_id=blog_id,blog_user_id=blog_user,comment=comment)
return JsonResponse({'status':'ok'})
except User.DoesNotExist:
return JsonResponse({'status':'error'})
return JsonResponse({'status':'error'})
and url
path('quote_comment/', views.quote_comment, name="quote_comment"),
A view that renders this template
def index(request):
quotes= Quote.objects.all()
return render(request=request, template_name="dashboard.html",context={'quotes':quotes})
to render on quotes im suing for loop like this
{% for quote in quotes %}
{% endfor %}

Symfony 4 How to add an attribute to a twig using jquery?

I'm trying to do a form with symfony 4. It works fine. But I have a problem.
I have a field to write a comment. By default, it's not required.
However, I would like to change this using jquery.
This is what I tried to do.
Here, it's my twig:
<div class="information" id="informationForm">
{{ form_row(recordForm.category) }}
{{ form_row(recordForm.information) }}
{{ form_label(recordForm.comment) }}
{{ form_widget(recordForm.comment, {'attr': {'class': 'comment'}}) }}
{{ form_errors(recordForm.comment) }}
<button id="add_information_button" class="btn btn-primary">Ajouter un renseignement</button>
<button id="count_div" class="btn btn-primary">Compter</button>
<button class="remove_information_button btn btn-primary">Supprimer un renseignement</button>
</div>
Here it's the javascript:
$('.information')
.on("change", ".record_to_information_form_information", function (event) {
event.preventDefault();
var $commentState = $(this).find('option:selected').data('comment')
//Test: to know if i received the attribute
console.log($commentState)
if($commentState===false){
//the field isn't required
// {{ form_widget(recordForm.comment, {'attr': {'required': 'false'}}) }}
}else{
//the field is required
// {{ form_widget(recordForm.comment, {'attr': {'required': 'true'}}) }}
}
})
;
Do you have any suggestions?
You can toggle required property value from your jQuery code.
I assume that data-comment attribute has type boolean and it's always set, so your toggle statement can look as follows:
$('.information')
.on("change", ".record_to_information_form_information", function (event) {
event.preventDefault();
var $commentState = $(this).find('option:selected').data('comment');
//Test: to know if i received the attribute
console.log($commentState);
$('.comment').prop('required', $commentState);
});
If you need to do something else in your if-else statement, you can just leave your condition as you provided in sample:
if ($commentState === false) {
//the field isn't required
$('.comment').prop('required', false);
} else {
//the field is required
$('.comment').prop('required', true);
}

ejs 2 custom delimiter

EJS2 can only do character to be use with angle brackets for open/close:
ejs.delimiter = '$';
ejs.render('<$= users.join(" | "); $>', {users: users});
I would like to use {{ }} instead of <% %>, previous version will allow this esj.open = '{{' and esj.close = '}}'.
Any help?
EJS has been updated & changed maintainers, so the main site is found here: https://ejs.co/
and the Github is here: https://github.com/mde/ejs
Unlike previous versions of EJS, you can't use completely custom delimiters now - you can use 'partial' custom delimiters - the first set of brackets aren't optional, but the following character is. To set up a custom delimiter you can do the following:
// app.js
const ejs = require('ejs');
ejs.delimiter = '?';
app.get('/', (req, res) => {
res.render('index', {
myVariable: 'Hey!'
});
});
// index.ejs
<div>
<p>
<?=myVariable ?>
</p>
</div>
// index.html (rendered output)
<div>
<p>
Hey!
</p>
</div>
You can add a complete options object and other things, but hopefully that gets you started if you want to change the default delimiters.
Documentation states that custom delimiters are supported:
https://github.com/tj/ejs#custom-delimiters
This isn't possible without modifying the module's source code.
My solution to using custom delimiters is be doing a string replace on the template
const template = fs.readFileSync(path.join(__dirname, './template.html'), 'utf8').replace('{{', '<%').replace('}}', '%>')
const render = ejs.compile(template)
This allows me to declare my template like this:
{{ if (someVar) { }}
{{= someVar }}
{{ } }}

Flashdata not render in view

im try print an alert report before a submit form.
The constroller check that entity was valid and inform the result:
$estado = Array();
if(count($errors) > 0){
$estado['alert'] = 'alert-error';
$estado['message'] = $errors->get(0);
}else{
$estado['alert'] = 'alert-success';
$estado['message'] = "Usuario creado correctamente";
}
$this->getRequest()->getSession()->getFlashBag()->add('status',$estado);
return $this->redirect($this->generateUrl('alta_usuario'));
So, in the view:
{% if app.session.flashbag.has('status') %}
<div class="alert {{ app.session.get('status').alert }}">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ app.session.get('status').message }}
</div>
{% endif %}
But Symfony fails with the next message:
Impossible to access an attribute ("alert") on a NULL variable ("")
In the profiler the Flashdata is:
status : [{"alert":"alert-error","message":{}}]
Two questions:
1) Why "message" is null ? the entity has an error and $errors->get(0) should be get the first error ?
2) Why can't access the $estado values from the view ?.
Any ideas ?.
This question is much similar as below link.
You can find the answer at
Am I using the Symfony flash variables the wrong way?

Resources