How to 'enable' and 'disable' buttons - codeigniter

I have two buttons in view that redirect to
own website
Customer Website
I am using 'codeigniter'. In this, I want to keep a condition the user can click on the "own website" button only one time. Then, that button should be disabled, i.e, only the "customer website" button should work.
To do this, I want to check if the customer id is present in the database. If yes, (i.e, there is customer id inserted) then, the "own website" button should be disabled.

If you're simply wanting to conditionally set HTML on load of page, you can do so with the below code (change it to apply to your db etc), but if you want to do it dynamically you will need to use a client side language to watch for events.
View Code:
// View - Own Site
<button class="button" id="own-button" data-customerId="<?= $customerId ?>" disabled="<?= $disabled ?>">Click Me!</button>
// View - Customer Site
<button class="button" id="customer-button">Click Me!</button>
CodeIgniter:
function index() {
$data["customerId"] = "1"; // Just an example
$data["disabled"] = $this->getButtonStatus($data["customerId"]);
$this->load->view("ownsite/index", $data);
}
// get current button status i.e. is there anything in the DB
private function getButtonStatus($customerId) {
if(!$customerId) {
return FALSE;
}
$this->load->database();
$disabled = $this->db->select("customerId")
->where("customerId", $customerId)
->get("myTable");
return $disabled->num_rows() > 0 ? TRUE : FALSE;
}

Related

Preserving language session ID from one domain to the next

I have two multi-lingual web sites. The main site and the shop site. On the main site detail page there is a "find in store" button. When the button is pressed, no matter what the language was set to on the main page, the shop page will open the product detail page in the default language (expected).
Is there a way to pass the session setting for language when redirecting to the shop site?
<?php
if (!session_id()) session_start();
if (!isset($_SESSION['languageID'])) {
$_SESSION['languageID'] = 1;//default value
}
?>
<?php
if (array_key_exists('german_x', $_POST)) {
$_SESSION['languageID'] = 1;
} else if (array_key_exists('english_x', $_POST)) {
$_SESSION['languageID'] = 2;
} else if (array_key_exists('french_x', $_POST)) {
$_SESSION['languageID'] = 3;
} else if (array_key_exists('spanish_x', $_POST)) {
$_SESSION['languageID'] = 4;
}
?>
The URL of the find in store button looks like this:
<input type="submit" name="goToShop" value="Find in store" />
Didn't get any answers, so I got creative. Maybe not the best or conventional way to go, but here is what I did, maybe it will help someone else:
Some of the language content is done with includes. I created an html page with a link to the detail page, that had the language session set in the desired language. So, while the English session was running, it would call detail_en.php, while Spanish it would call detail_es.php etc.
This is what the link looks like:
<input type="submit" name="goToShop" value="<?php echo $row_rscontent13['description15']; ?>" />

History inside state

I`am created ionic app that has one state called master {url: /master}. There are two buttons on the state view. Each button shows hidden div with text.
I want to implement history tracking by this rules:
When user clicks on first button then url should be appended with firstOpened=true
When user clicks on second button then url should be appended with secondOpened=true
Controllers should stay the same (no re-initialization needed)
Back button of browser should undo last action, for example: If user opens first div then back button should close this div and restore url without page reload.
If history of master state is empty, then back button should restore previous state if it exsits
If i use $state.go to change url, then ionic will reinitialize state and all controllers. It looks like i move from one view to another (from one state to another), but i dont want to change the state, i want to update url and push history. I want to use same state without re-initialization.
I`am created plunker without history tracking. Can somebody help me with implementig history tracking?
script.js (see ):
angular.module('starter', ['ionic'])
.config(function($stateProvider, $urlRouterProvider) {
var controller = 0;
$urlRouterProvider.otherwise("/master");
$stateProvider.state('master', {
url: '/master?firstOpened&secondOpened',
views: {
'default': {
templateUrl: 'content.html',
controller: function($scope, $ionicHistory, $stateParams, $state) {
console.log('Initing controller...');
controller = controller + 1;
$scope.controller = controller;
$scope.firstOpened = $stateParams.firstOpened
$scope.secondOpened = $stateParams.secondOpened
$scope.openFirst = function() {
$scope.firstOpened = true;
};
$scope.openSecond = function() {
$scope.secondOpened = true;
};
}
}
}
})
})
The point is, that you do not change the state on click. You are only changing the scope variables, but that doesn't mean any change to the URL or history.
To get history support, you need to change the state and put a ng-show on your sliders. I did it with ui-sref like this:
<ion-content>
<h1>Controller №{{::controller}}</h1>
<button class="button" ui-sref='master({firstOpened: true, secondOpened: false})'>Open first</button>
<button class="button" ui-sref='master({firstOpened: false, secondOpened: true})'>Open second</button>
<div style="background-color: #FF0000;" ng-show="{{firstOpened}}">
<h1>Slider 1</h1>
</div>
<div style="background-color: #00FF00;" ng-show="{{secondOpened}}">
<h1>Slider 2</h1>
</div>
</ion-content>
And your controller only needs to keep track of the stateParams, like you already did:
controller: function($scope, $ionicHistory, $stateParams, $state) {
console.log('Initing controller...');
controller = controller + 1;
$scope.controller = controller;
$scope.firstOpened = $stateParams.firstOpened;
$scope.secondOpened = $stateParams.secondOpened;
}
I've updated your plunker code here.
As you can see, I had to remove the slide animation, as it did not react properly on firstOpened and secondOpened values. But this is another issue and I am sure it's no big deal to get it to work again.

Checking a checkbox to submit to a link not working in Chrome

I have a link in a razor view (.NET MVC3) which is part of a sort function which shows all records (active and archived) or the active ones (the default on page load). It works fine in Firefox. But it only works when I click on the text part of the link not when the checkbox is checked for chrome and IE. Here is the code I've used.
<a id="lnkShowAll" href="#Url.Action("showAll", "myController", new { showOnlyActive = !Model.Active })" >
<input id="chkShowAll" type="checkbox"
#if(!Model.Active){
#: checked="checked"
} >
Show All (<span class="activeFont">Active</span> / <span class="archivedFont">Archived</span> )
</a>
This is the Controller but I doubt the problem is with the controller since no call is being made to it when the check box is checked
public ActionResult Index(bool showOnlyActive = true)
{
RecordList recordList = searchForRecordList(showOnlyActive);
return View("Index", recordList) ;
}
Does anyone have any Idea what I am missing?
I am still not sure why it works in firefox but not in Chrome and IE, but I found a solution that works for all.
I wrote an event for the click function of the link in jquery.
$("#lnkShowAll").click(function(event)
{
var link = $(this);
var target = link.attr("target");
if($.trim(target).length > 0)
{
window.open(link.attr("href"), target);
}
else
{
window.location = link.attr("href");
}
event.preventDefault();
});
And added a click function to trigger a click event of the link when the checkbox is checked/unchecked.
$("#chkShowAll").click(function(){
$("#lnkShowAll").click();
});
This ensures that the link is clicked whenever the checkbox is clicked on no matter what browser you are using.

Yii ClientSide Validation on Render Partial not Working

I have a Yii form which calls a render partial from another model (team has_many team_members). I want to call via ajax a partial view to add members in team/_form. All works (call, show, save) except for ajax validations (server and client side). If i submit form, member's model isn't validating, even in client side, it's not validating the required fields.
Any clue?
//_form
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'team-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>true
),
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
//Controller
public function actionMember($index)
{
$model = new TeamMember();
$this->renderPartial('_member',array(
'model'=> $model, 'index'=> $index
)
,false,true
);
}
public function actionCreate()
{
$model=new Team;
$members = array();
if(isset($_POST['Team']))
{
$model->attributes=$_POST['Team'];
if(!empty($_POST['TeamMember'])){
foreach($_POST['TeamMember'] as $team_member)
{
$mem = new TeamMember();
$mem->setAttribute($team_member);
if($mem->validate(array('name'))) $members[]=$mem;
}
}
$this->redirect(array('team/create','id'=>$model->id,'#'=>'submit-message'));
}
$members[]=new TeamMember;
$this->performAjaxMemberValidation($members);
$this->render('create',array(
'model'=>$model,'members'=>$members
));
}
//_member
<div class="row-member<?php echo $index; ?>">
<h3>Member <?php echo $index+1; ?></h3>
<div class="row">
<?php echo CHtml::activeLabel($model, "[$index]name",array('class'=>'member')); ?>
<?php echo CHtml::activeTextField($model, "[$index]name",array('class'=>'member')); ?>
<?php echo CHtml::error($model, "[$index]name");?>
</div>
</div>
ProcessOutput was set to true. No dice.
Switch renderPartial() to render(). No dice.
If you will look at the CActiveForm::run:
$cs->registerCoreScript('yiiactiveform');
//...
$cs->registerScript(__CLASS__.'#'.$id,"jQuery('#$id').yiiactiveform($options);");
Then you will understand that you validation will not work, because you render partial and not the whole page. And these scripts show up at the bottom of the page. So you should solve this by execute these scripts.
After you partial is rendered, try to get activeform script which should be stored at the scipts array:
$this->renderPartial('_member',array('model'=> $model, 'index'=> $index));
$script = Yii::app()->clientScript->scripts[CClientScript::POS_READY]['CActiveForm#team-form'];
after, send it with rendered html to page:
echo "<script type='text/javascript'>$script</script>"
Also remember before you will append recieved html on the page you should include jquery.yiiactiveform.js, if you not already did it(by render another form, or registerCoreScript('yiiactiveform')), on the page from calling ajax request. Otherwise javascript error will raised.
Hope this will help.
Edit:
Sorry I'm not understood that you are render part of form and not the whole. But you validation will not work exactly with the same issue. Because jQuery('#$id').yiiactiveform($options); script was not created for the field.
The actual problem is that the ActiveForm saves its attributes to be validated in the "settings" data attribute. I see you are already using indexes so what you need to add the new elements to this settings object in order for the validation to work. After the ajax response this is what must be done:
//Get the settings object from the form
var settings = $("#form").data('settings');
//Get all the newly inserted elements via jquery
$("[name^='YourModel']", data).each(function(k, v) {
//base attribute skeleton
var base = {
model : 'YourModel',
enableAjaxValidation : true,
errorCssClass : 'error',
status : 1,
hideErrorMessage : false,
};
var newRow = $.extend({
id : $(v).attr('id'),
inputID : $(v).attr('id'),
errorID : $(v).attr('id') + '_em_',
name : $(v).attr('name'),
}, base);
//push it to the settings.attribute object
settings.attributes.push(newRow);
});
//update the form
$("#form").data('settings', settings);
```
This way the ActiveForm will be aware of the new fields and will validate them.
Well, setting processOutput to true in renderPartial (in order to make client validation works on newly added fields) will not help in this case since it will only work for CActiveForm form and you don't have any form in your _member view (only input fields).
A simple way to deal with this kind of problem could be to use only ajax validation, and use CActiveForm::validateTabular() in your controller to validate your team members.

Constraining tank_auth views to a div on a web age

Hi Tank_auth & web Gurus!
I have tank_auth working with my CodeIgniter application. Currently, the login/register views of tank_auth take over the entire screen. On my website, I would like the login/register views to occupy a div that I define. For example, I want the login/pw fields to just appear in the top right corner and not take over the whole screen...Can you point me in the right direction? - I read somewhere that I'd have to somehow constrain the view in a div but for the life of me I did not understand how!
Much obliged,
Mmiz
Create div for the login. Create a view for the login. Populate the div with a javascript call to the view.
<?php
//controller
//users.php
class Users {
//...
public function div_login()
{
$this->load->view('div_login_view.php');
}
//...
//------------------------------------------
//view
//div_login_view.php
echo form_open('users/login');
echo form_input('username');
echo form_password('password');
echo form_submit('Login');
echo form_close();
//------------------------------------------
//index page (or whatever page you want the form on)
<div id="login_div"></div>
<script type="text/javascript">
$(document).ready(function(){
var login_form = $.get('/users/div_login');
if (login_form.status === 200){
$('#login_div').html(login_form.responseText)
}else{
alert('There was an error getting the login form.');
}
})
</script>

Resources