If statement cakephp input value and run a javascript code - javascript

I am trying to make an if statement with cakePHP but I'm really an amateur. I checked the cookbook and stackoverflow but couldn't find it. (using 2.x.x version of cake)
So what I'm trying to do is:- if the ticket-1-amount is not zero, remove the invisible class.
Something I tried but didn't work:-
if ( $('#ListTypeTicket-1-amount').val() != '' ) {
$("#invisibleBox").removeClass("invisible");
}
Also tried this:-
if (empty($this->request->data ['ticket-1-amount'] != 0)) {
echo '$("#invisibleBox").removeClass("invisible");</script>';
} ;
My cakePHP form:-
<?=$this->Form->input(
'ticket-1-amount',
array('label' => false,
'class' => 'ticket-1-amount',
'id' => 'ticket-1-amount')
); ?>
This is the actual div
<div id='invisibleBox' class="invisible">
..........
</div>

Keep things simple, Just try:
<div id='invisibleBox' class="<?php if($this->request->data['ticket-1-amount'] == 0) {echo 'invisible'}; ?>">
..........
</div>

Create a JavaScript file and put the code below inside it.
App = {
init: function () {
this.checkTicketAmount();
},
checkTicketAmount: function(){
if ($('#ticket-1-amount').val() != '0') {
$("#invisibleBox").removeClass("invisible");
}
}
};
$(document).ready(function () {
App.init();
});
After the page is loaded, jQuery will check the ticket amount value and remove the invisible class, or not.

Related

Triggering submit event after change when uploading image on Yii2 framework

I am trying to save an image type file by using jquery to trigger the submit. I encountered an issue where it triggers even when the change event is not done.
View create.php:
<?php \yii\bootstrap4\ActiveForm::begin([
'options' => [
'enctype' => 'multipart/form-data',
'id' => 'dynamic-form'
]
]) ?>
<button class="btn btn-primary btn-file">
Select Thumbnail
<input type="file" id="recipeThumbnail" name="recipe">
</button>
<?php \yii\bootstrap4\ActiveForm::end() ?>
In this view, i specify the id to call it in the javascipt file.
Js app.js:
$(function () {
'use strict';
$('#recipeThumbnail').change(ev => {
$(ev.target).closest('form').trigger('submit');
})
});
From my understanding here, the trigger('submit') should only run when there is a change which in this case an image file is selected. However, i suspect the event is triggered and it caused an error of Attempt to read property "name" on null from the model below on the line $this->name = $this->recipe->name;. My other suspicion would be error in the model but i cant wrap my head around where or how it could be.
Model recipe.php:
public function save($runValidaiton = true, $attributeNames = null)
{
$isInsert = $this->isNewRecord;
if ($isInsert) {
$this->recipe_id = Yii::$app->security->generateRandomString(16);
$this->name = $this->recipe->name;
}
$saved = parent::save($runValidaiton, $attributeNames);
if (!$saved) {
return false;
}
if ($isInsert) {
$recipePath = Yii::getAlias('#frontend/web/storage/thumbnail/' . $this->recipe_id . '.jpg');
if (!is_dir(dirname($recipePath))) {
FileHelper::createDirectory(dirname($recipePath));
}
$this->recipe->saveAs($recipePath);
}
return true;
}
Controller RecipeController.php:
public function actionCreate()
{
$model = new Recipe();
$model->recipe = UploadedFile::getInstanceByName('recipe');
if ($this->request->isPost) {
if (Yii::$app->request->isPost && $model->save()) {
return $this->redirect(['view', 'recipe_id' => $model->recipe_id]);
}
} else {
$model->loadDefaultValues();
}
return $this->render('create', [
'model' => $model,
]);
}
I hope i explained this well. Is this error actually caused by the js or something else and any insight on this issue is much appreciated:D
Insights from #ChrisG and #CBroe,
The issue was wrapping the input tag in a button tag which will click both button and input at the same time causing the error. An easy fix would be adding type="button" in the button tag.
But this is actually a broken HTML as an interactive element should not be nested into each other. The fix to this would be using form and labels with the button so that it is a decent html.

jQuery popover buttons (php)

I have a a button to generate presentations. I generate 8 presentation with one click, and then I can edit each one by clicking on its name. There I have another, smaller form. I want to have also some button there, that will let me choose which fields I want to edit. This applies to "place" part - you can specify the place, if you want to. I have a button to show/hide fields connected to place edition.
<div>
<?=
Html::button(Yii::t('app', 'Add new place'), [
'id' => "add-different-place-btn",
'class' => 'btn btn-success',
])
?>
<?=
Html::button(Yii::t('app', 'Delete new place'), [
'id' => "delete-different-place-btn",
'class' => 'btn btn-success',
])
?>
</div>
<br />
<div id="place-hidden-different">
<div id="place-name-hidden">
<?= $form->field($place, "[{$index}]name")->textInput()->label(Yii::t('app', 'New place')) ?>
</div>
<div id="place-city-hidden">
<?= $form->field($place, "[{$index}]city")->textInput() ?>
</div>
<div id="place-street-hidden">
<?= $form->field($place, "[{$index}]street")->textInput() ?>
</div>
<div id="place-postcode-hidden">
<?= $form->field($place, "[{$index}]post_code")->textInput() ?>
</div>
</div>
Then, in my jQuery part I figured out something like this. Notice that I'm really new to jQuery, so it can be something really obvious :)
$('.btn-popover-link').on('click', function () {
$(document).ready(function () {
$('#place-hidden-different').hide();
$('#delete-different-place-btn').hide();
$('#add-different-place-btn').on('click', function () {
$('#place-hidden-different').show();
$('#add-different-place-btn').hide();
$('#delete-different-place-btn').show();
});
$('#delete-different-place-btn').on('click', function () {
$('#place-hidden-different').hide();
$('#add-different-place-btn').show();
$('#delete-different-place-btn').hide();
});
});
});
But, instead of getting what I want to, I get things like that:
It looks ok. But it doesn't work. Nothing happens on clicking "Dodaj nowe miejsce" (Add new place). Morover, in other presentation I get full variety of that form - example below. None of the buttons is working at all, in some popovers there are no buttons at all, in some just not working.
What can cause this situation?
If I get it well, you are using the same ID #add-different-place-btn for each of the 8 presentations button.
If this is right, the code is working as expected: IDs must be unique !
You should move to a class selector like you did with .btn-popover-link.
Also you should move $('.btn-popover-link').on('click', function () {}); inside the $(document).on("ready", function() { ... here ... });.
Even better with $(window).on("load", function() {}); but it depends on the kind of code you are running.

Click a button to change the text of text input

I have this part of code in the Codeigniter controller named 'ajaxcalls' :
public function show_contact_persons($client_id) {
$data['contact_persons'] = $this->common_model->select_records('ci_contact_persons', 'client_id', $client_id);
//dump($data);
function echoArray ($array) {
foreach ($array as $key => $value)
{
if ( true == is_array($value) )
{
echoArray($value);
}
else
{
if ($key == 'contact_person_name') {
echo '<input type="button" value="'.$value.'" onclick="changeContact(987)" /><br />';
}
}
}
}
echoArray($data);
}
and then the JS part at the page which is calling the PHP file :
function changeContact(contact_name) {
document.getElementById('contact_person').value = contact_name;
}
I put the number '987' in this example because the code works only with NUMBERS. When I put text inside the bracket, or what I REALLY want to do :
onclick="changeContact('.$value.')"
then the script doesn't work. ONLY with numbers. What should I change to make it work with strings?
You are very close.
Use this instead :
onclick="changeContact("'.$value.'")"
Whats happening is the JS is rendering it as changeContact(stringValue); so its expecting it to be a defined variable.
Adding the quotations will pass it into the function as a string which will render as : changeContact("stringValue");

Adding JScript to a prestashop CMS page

prestashop v1.5.4.0
I want to add this click to open element made from CSS, HTML and JS located here http://codepen.io/anon/pen/Gqkxv
function openDoor(field) {
var y = $(field).find(".thumb");
var x = y.attr("class");
if (y.hasClass("thumbOpened")) {
y.removeClass("thumbOpened");
}
else {
$(".thumb").removeClass("thumbOpened");
y.addClass("thumbOpened");
}
}
what is the best method to place this in to a CMS page
My guess is since the CMS pages strip out most javascript tags and don't seem to allow you to attach exernal js files you will need to create an override of the cmsController.php.
You would need to create your external js file and css file and save them in the theme's js directory and css directory. The setMedia method is used to attach style/js files when that controller is called. You can override the cmsController.php and add this to the setMedia method
$this->addJS(_THEME_JS_DIR_.'yourjsfile.js');
$this->addCSS(_THEME_CSS_DIR_.'yourcssfile.css');
I believe that should work however, this will add these files to every cms page. The only way I can think to get around that is by getting the ID of the cms page(s) that you want it to appear on and run an if state on your addJS and addCSS functions.
example: You want it to show up on id_cms 4
if ((int)Tools::getValue('id_cms') == 4) {
$this->addJS(_THEME_JS_DIR_.'yourjsfile.js');
$this->addCSS(_THEME_CSS_DIR_.'yourcssfile.css');
}
or you want it to show on id_cms 4 and id_cms 6
if ((int)Tools::getValue('id_cms') == 4 || (int)Tools::getValue('id_cms') == 6) {
$this->addJS(_THEME_JS_DIR_.'yourjsfile.js');
$this->addCSS(_THEME_CSS_DIR_.'yourcssfile.css');
}
no need to add modules,
go to cms.tpl from your theme folder in prestashop,
add this
{if $cms->id==6}
{literal}
<script type="text/javascript" src="js/yourjsfile.js"></script>
{/literal}
{/if}
replace with your cms id and the name of your js file, then upload the file to js folder in prestahop root folder,
then go the prestahop panel, advanced parameters, performance, compile the templates and then launch your site --- the script will run only on the page selected
You can create a module and hook your js to backoffice header like this.
public function install()
{
if ( !$this->installTab()
|| !$this->registerHook('displayBackOfficeHeader'))
return false;
return true;
}
public function hookDisplayBackOfficeHeader()
{
//check if currently updatingcheck if module is currently processing update
if ($this->isUpdating() || !Module::isEnabled($this->name))
return false;
if (method_exists($this->context->controller, 'addJquery'))
{
$this->context->controller->addJquery();
$this->context->controller->addCss($this->_path.'views/css/gamification.css');
if (version_compare(_PS_VERSION_, '1.6.0', '>=') === TRUE)
$this->context->controller->addJs($this->_path.'views/js/gamification_bt.js');
else
$this->context->controller->addJs($this->_path.'views/js/gamification.js');
$this->context->controller->addJqueryPlugin('fancybox');
return $css_str.'<script>
var ids_ps_advice = new Array('.rtrim($js_str, ',').');
var admin_gamification_ajax_url = \''.$this->context->link->getAdminLink('AdminGamification').'\';
var current_id_tab = '.(int)$this->context->controller->id.';
</script>';
}
}
This a example show from prestashop core module gamification. After that you can write your own prestashop js code which you want.
In 2019 regarding PS 1.7 - we solved it here: https://www.prestashop.com/forums/topic/267834-how-to-insert-javascript-code-inside-a-page/
In short - add it directly to CMS content field with slight modifiations:
1) in class/Validation.php add
public static function isCleanHtmlWithScript($html, $allow_iframe = false)
{
$events = 'onmousedown|onmousemove|onmmouseup|onmouseover|onmouseout|onload|onunload|onfocus|onblur|onchange';
$events .= '|onsubmit|ondblclick|onclick|onkeydown|onkeyup|onkeypress|onmouseenter|onmouseleave|onerror|onselect|onreset|onabort|ondragdrop|onresize|onactivate|onafterprint|onmoveend';
$events .= '|onafterupdate|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditfocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onmove';
$events .= '|onbounce|oncellchange|oncontextmenu|oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondeactivate|ondrag|ondragend|ondragenter|onmousewheel';
$events .= '|ondragleave|ondragover|ondragstart|ondrop|onerrorupdate|onfilterchange|onfinish|onfocusin|onfocusout|onhashchange|onhelp|oninput|onlosecapture|onmessage|onmouseup|onmovestart';
$events .= '|onoffline|ononline|onpaste|onpropertychange|onreadystatechange|onresizeend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onsearch|onselectionchange';
$events .= '|onselectstart|onstart|onstop';
if (!$allow_iframe && preg_match('/<[\s]*(i?frame|form|input|embed|object)/ims', $html)) {
return false;
}
return true;
}
2) then in /classes/CMS.php around line #66 change
'content' => array('type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtml', 'size' => 3999999999999)
to
'content' => array('type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtmlWithScripts', 'size' => 3999999999999)
now you should be good to go

Codeigniter ajax call does not work properly

For example if I click 'vote up' button it successfully adds vote for the first post and displays the result in span element with class="rate_votes", but it also displays the same result in all the span elements with same class because of the following line:
$(".rate_votes").text(rate); //
How can I avoid that?
If I use
$(this).text(rate); //
it will not work properly because it does not know which span element to select. Could you help me please.
Here is my view:
<div>
<?php
foreach($results as $row){
$id = $row['id'];
$rate = $row['rate'];
?>
<div>
<?php
$data = array(
'name' => $id,
'class' => 'rate',
'content' => 'Vote Up'
);
echo form_button($data);
?>
<span class="rate_votes" >
<?php echo $rate; ?>
</span>
</div>
</div>
Here is my JS file:
$(document).ready(function() {
$(".rate").click(function(){
var self = this;
$(self).attr("disabled", true);
var id_like = $(self).attr("name");
$.post('filter/get_rate', { id_like: id_like }, function (data) {
var my_obj = data;
$.each(my_obj, function (i) {
var rate = my_obj[i].rate;
$(".rate_votes").text(rate); //
$(self).text("Voted!");
});
}, "json");
});
});
This has nothing to do with codeigniter :)
You bind the click event to an ID, #rate but that ID appears multiple times.
$data = array(
'name' => $id,
'id' => 'rate',
'content' => 'Vote Up'
);
echo form_button($data);
use a class instead.
When you select an ID that appears multiple times, only the first one is selected, thus only the first button works.
EDIT
Your comment sounds a bit strange, Given this code for example :
HTML:
<div class="foo">Foo</div>
<div class="foo">Foo</div>
<div class="foo">Foo</div>
<div class="foo">Foo</div>
Javascript/Jquery
$('.foo').click(function() { $(this).remove() });
The above code only removes the specific div being clicked, That is the event is only fired once and for that element only.
Doublecheck your javascript.
You have used:
$("#rate").click(function(){...})
Here "#rate" is an id and an id must be unique, use class like .rate. If you have multiple elements with same id on the page then only the first element of the page will be counted. So the following code is registering the click handler only on the first element with id rate:
$("#rate").click(function(){
//...
});
Give your elements a class instead, for example:
<button class='rate'>Rate</button>
<button class='rate'>Rate</button>
So this code will work on every button click:
$(".rate").click(function(){
var id_like = $(this).attr("name");
$(this).attr("disabled", true); // disables the current button
$('.rate').attr("disabled", true); // disable all the buttons with class rate
//...
});

Categories