Cakephp 2.X disable/enable syntax - php

I'm using the following example
http://jsfiddle.net/nc6NW/1/
Yet when I change this to formhelper syntax the Jquery does not re-enable the disabled save functionality. How does one remove this attribute given this function
<div id="newArticleForm">
<?php
echo $this->Form->create('Post', array('action' => 'add'));
echo $this->Form->input('article_title',array('type' => 'text', 'id'=>'ArticleHeader','div'=>false,'label'=>false,'class'=>'centertext',"placeholder"=>"Article Header"));
echo $this->Html->para(null,'<br>', array());
echo $this->Form->input('article_link',array('type' => 'text', 'id'=>'ArticleLink','div'=>false,'label'=>false,'class'=>'centertext',"placeholder"=>"Article Link"));
echo $this->Html->para(null,'<br>', array());
echo $this->Form->button('Cancel', array('type' => 'reset'), array('inline' => false));
echo $this->Form->button('Save', array('type' => 'submit', 'disabled'=>true), array('inline' => false));
echo $this->Form->end();
?>
</div>
<script>
$(':text').keyup(function() {
if($('#ArticleHeader').val() != "" && $('#ArticleLink').val() != "") {
$('#submit').removeAttr('disabled');
} else {
$('#submit').attr('disabled', true);
}
});
</script>

Solved it, sorry for wasting everyone's time
submit had the wrong identifier, needed a colon not a hash.
i.e.
$(':text').keyup(function() {
if($('#ArticleHeader').val() != "" && $('#ArticleLink').val() != "") {
$(':submit').removeAttr('disabled');
} else {
$(':submit').attr('disabled', true);
}
});

Related

PHP code to upload multiple files with database

I have issue with multiple file upload in cakephp.
I try to upload multiple files and need to insert multiple entries in table, but I am unable to do this.
For Ex - if I upload 3 photos from form then need to be inserted 3 rows in table with their file name.
public function add() {
$this->Driver->create();
if ($this->request->is('post')) {
for($i=1;$i<4;$i++)
{
if(empty($this->data['Driver']['document'.$i]['name'])){
unset($this->request->data['Driver']['document'.$i]);
}
if(!empty($this->data['Driver']['document'.$i]['name']))
{
$file=$this->data['Driver']['document'.$i];
$ary_ext=array('jpg','jpeg','xls','docx'); //array of allowed extensions
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
if(in_array($ext, $ary_ext))
{
move_uploaded_file($file['tmp_name'], APP . 'outsidefiles' .DS. time().$file['name']);
$this->request->data['Driver']['document'.$i] = time().$file['name'];
}
}
}
if ($this->Driver->save($this->request->data))
{
//echo "<pre>";print_r($this->request->data); exit();
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'add'));
}
else
{
$this->Session->setFlash('Unable to add your post.');
}
}
}
add.ctp
<h1>Add Post</h1><?php
echo $this->Form->create('Driver', array('url' => array('action' => 'add'), 'enctype' => 'multipart/form-data'));
echo $this->Form->input('address',array('div' => false, 'class' => 'form-control user-name'));
for($i=1; $i<4; $i++)
{
?>
<div id="attachment<?php echo $i;?>" <?php if($i !=1) echo "style='display:none;'";?> >
<div>
<?php echo $this->Form->input('document'.$i,array('type'=>'file','label' => false,'div' => false));?>
</div>
<div id="attachmentlink<?php echo $i;?>" <?php if($i==3) echo "style='display:none;'";?>>Add Another Attachment</div>
</div>
<?php } ?>
<?php
echo $this->Form->end('Save');
?>
Plz try this
public function add() {
$this->Driver->create();
if ($this->request->is('post')) {
for($i=1;$i<4;$i++)
{
if(empty($this->data['Driver']['document'][$i]['name'])){
unset($this->request->data['Driver']['document'.$i]);
}
if(!empty($this->data['Driver']['document'][$i]['name']))
{
$file=$this->data['Driver']['document'][$i];
$ary_ext=array('jpg','jpeg','xls','docx'); //array of allowed extensions
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
if(in_array($ext, $ary_ext))
{
move_uploaded_file($file['tmp_name'], APP . 'outsidefiles' .DS. time().$file['name']);
$this->request->data['Driver']['document'][$i] = time().$file['name'];
}
}
}
if ($this->Driver->save($this->request->data)){
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'add'));
}else{
$this->Session->setFlash('Unable to add your post.');
}
}
}
CakePHP 2 Field naming conventions
echo $this->Form->input('Modelname.0.fieldname');
echo $this->Form->input('Modelname.1.fieldname');
in your view file
//for($i=1; $i<4; $i++)..
echo $this->Form->input('Driver.'.$i.'.document', array('type' => 'file'));
in your controller like
$this->request->data['Driver'][$i]['document']['name'] // where name is uploaded document filename
Use Model::saveMany(array $data = null, array $options = array())
Method used to save multiple rows of the same model at once...
if ($this->Driver->saveMany($this->request->data))...
UPDATE your code
<?php
public function add()
{
if ($this->request->is('post')) {
for($i=1;$i<4;$i++)
{
if(empty($this->request->data['Driver'][$i]['document']['name'])){
unset($this->request->data['Driver'][$i]['document']);
}
if(!empty($this->request->data['Driver'][$i]['document']['name']))
{
$time = time(); // <-------------
$file=$this->request->data['Driver'][$i]['document'];
$ary_ext=array('jpg','jpeg','xls','docx'); //array of allowed extensions
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
if(in_array($ext, $ary_ext))
{
move_uploaded_file($file['tmp_name'], APP . 'outsidefiles' .DS. $time.$file['name']);
$this->request->data['Driver'][$i]['document'] = $time.$file['name'];
}
}
}
$this->Driver->create();
if ($this->Driver->saveMany($this->request->data))
{
//echo "<pre>";print_r($this->request->data); exit();
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
else
{
$this->Session->setFlash('Unable to add your post.');
}
}
}
add.ctp
<h1>Add Post</h1>
<?php
echo $this->Form->create('Driver', array( 'type' => 'file'));
//echo $this->Form->input('address',array('div' => false, 'class' => 'form-control user-name')); ????
for($i=1; $i<4; $i++)
{
?>
<div id="attachment<?php echo $i;?>" <?php if($i !=1) echo "style='display:none;'";?> >
<div>
<?php echo $this->Form->input('Driver.'.$i.'.document',array('type'=>'file','label' => false,'div' => false));?>
</div>
<div id="attachmentlink<?php echo $i;?>" <?php if($i==3) echo "style='display:none;'";?>>Add Another Attachment</div>
</div>
<?php } ?>
<?php
echo $this->Form->end('Save');
?>

How to make auto complete form in cakephp?

I am trying to make an auto complete function in CakePHP but did not succeed. I tried the following code.
public function find() {
if ($this->request->is('ajax')) {
$this->autoRender = false;
$country_name = $this->request->data['Country']['name'];
$results = $this->Country->find('all', array(
'conditions' => array('Country.name LIKE ' => '%' . $country_name . '%'),
'recursive' => -1
));
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
echo json_encode($results);
}
}
// Form and jquery
<?php
echo $this->Form->create('Country', array('action' => 'find'));
echo $this->Form->input('name',array('id' => 'Autocomplete'));
echo $this->Form->submit();
echo $this->Form->end();
?>
<script type="text/javascript">
$(document).ready(function($){
$('#Autocomplete').autocomplete({
source:'/countries/find',
minLength:2
});
});
</script>
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
Breaks your JSON structure.
Keep in mind that autocomplete by default expects "label" and value keys in your JSON table, so all the script should do after fetching DB records is:
$resultArr = array();
foreach($results as $result) {
$resultArr[] = array('label' =>$result['Country']['name'] , 'value' => $result['Country']['name'] );
}
echo json_encode($resultArr);
exit(); // may not be necessary, just make sure the view is not rendered
Also, I would create the URL to your datasource in the jQuery setup by
source:'<?=$this->Html->url(array("controller" => "countries","action"=> "find")); ?>',
And try to comment-out (just to make sure if the condition is not met by the request when autocomplete makes its call)
if ($this->request->is('ajax')) {
condition

Cakephp ajax delete with j query

i've found this http://www.jamesfairhurst.co.uk/posts/view/ajax_delete_with_cakephp_and_jquery/ tutorial on the web, but it was for cakephp 1.3.
After making some adjustements to it , i try to run it, but something is going wrong. While the record gets deleted(as it should be), it refreshed the page. It's like Ajax and Jquery are not working.
Below is my code
The Controller Action
function delete($id=null) {
// set default class & message for setFlash
$class = 'flash_failure';
$msg = 'Invalid User Id';
// check id is valid
if($id!=null && is_numeric($id)) {
// get the Item
$item = $this->User->read(null,$id);
// check Item is valid
if(!empty($item)) {
$user = $this->Session->read('Auth.User');
// $exists=$this->User->find('count',array('conditions'=>array("User.username" => $user)));
if($item['User']['username']==$user['username']){
$msg = 'You cannot delete yourself!';
}
// try deleting the item
else if($this->User->delete($id)) {
$class = 'flash_success';
$msg = 'User was successfully deleted';
} else {
$msg = 'There was a problem deleting User, please try again';
}
}
}
// output JSON on AJAX request
if(/*$this->RequestHandler->isAjax()*/$this->request->is('ajax')) {
$this->autoRender = $this->layout = false;
echo json_encode(array('success'=>($class=='flash_failure') ? FALSE : TRUE,'msg'=>"<p id='flashMessage' class='{$class}'>{$msg}</p>"));
exit;
}
// set flash message & redirect
$this->Session->setFlash($msg,$class,array('class'=>$class));
$this->redirect(array('action'=>'manage'));
}
The View
<?php //view/users/manage.ctp ?>
<h1 class="ico_mug">Users</h1>
<?php echo 'Add User '.$this->Html->link($this->Html->image("add.jpg"), array('action' => 'register'), array('escape' => false));//print_r ($users); ?>
</br>
<table id="table">
<tr>
<th>ID</th>
<th>Username</th>
<th>Last Login</th>
<th>Options</th>
</tr>
<!-- Here is where we loop through our $posts array, printing out post info -->
<?php foreach ($users as $rs): ?>
<tr>
<?php echo $this->Html->script('jquery'); ?>
<td class="record">
<?php echo $rs['User']['id']; ?>
</td>
<td class="record"><?php echo $rs['User']['username']; ?></td>
<td class="record"><?php if(!$rs['User']['last_login']) {echo "Never Logged In";} else {echo $rs['User']['last_login'];} ?></td>
<td class="record"> <?php echo $this->Html->link($this->Html->image("edit.jpg"), array('action' => 'edit',$rs['User']['id']), array('escape' => false));?>
<?php
$user = $this->Session->read('Auth.User');
if($rs['User']['username']!=$user['username'])
echo $this->Html->link($this->Html->image("cancel.jpg"), array('action' => 'delete',$rs['User']['id']), array('escape' => false),array('class'=>'confirm_delete'));?>
<?php
if($rs['User']['username']!=$user['username'])
// simple HTML link with a class of 'confirm_delete'
echo $this->Js->link('Delete',array('action'=>'delete',$rs['User']['id']),array('escape' => false),array('class'=>'confirm_delete'));
?></td>
</tr>
<?php endforeach; ?>
<div class="paging">
<?php echo $this->Paginator->prev('<< ' . __('previous'), array(), null, array('class'=>'disabled'));?>
| <?php echo $this->Paginator->numbers();?>
| <?php echo $this->Paginator->next(__('next') . ' >>', array(), null, array('class' => 'disabled'));?>
</div>
</table>
<div id='ajax_loader'></div>
The Jquery
// on dom ready
$(document).ready(function(){
// class exists
if($('.confirm_delete').length) {
// add click handler
$('.confirm_delete').click(function(){
// ask for confirmation
var result = confirm('Are you sure you want to delete this?');
// show loading image
$('.ajax_loader').show();
$('#flashMessage').fadeOut();
// get parent row
var row = $(this).parents('tr');
// do ajax request
if(result) {
$.ajax({
type:"POST",
url:$(this).attr('href'),
data:"ajax=1",
dataType: "json",
success:function(response){
// hide loading image
$('.ajax_loader').hide();
// hide table row on success
if(response.success == true) {
row.fadeOut();
}
// show respsonse message
if( response.msg ) {
$('#ajax_msg').html( response.msg ).show();
} else {
$('#ajax_msg').html( "<p id='flashMessage' class='flash_bad'>An unexpected error has occured, please refresh and try again</p>" ).show();
}
}
});
}
return false;
});
}
});
Please take in mind that i'm very new to all this Jquery and Ajax thing, as well as in cakephp.
What is causing that behaviour ? (also if i try to remove the redire from the controller, i get a message that "view delete was not found" )
First of all check cookbook for HtmlHelper::link and JsHelper::link. Not sure what version of cake you have, so just switch to the right one.
The thing is - none of your Delete links has class confirm_delete (use firebug or some debugging tool) - so the link gets clicked but the javascript is never executed, that's why you get redirected.
In your case it would be:
echo $this->Html->link($this->Html->image('cancel.png'), array('controller' => 'users', 'action' => 'delete', $rs['User']['id']), array('escape'=>false, 'class'=>'confirm_delete') );
and
echo $this->Js->link('Delete', array('controller' => 'users', 'action'=>'delete', $rs['User']['id']), array('escape' => false, 'class'=>'confirm_delete'));
Then I see $('.ajax_loader').hide(); but in your view is element with id="ajax_loader", so the selector should be $('#ajax_loader').hide();
Same with $('#ajax_msg').html(, double check you have that element on page with the id="ajax_msg"
Hope it helps you further;)

How do insert and retrieve checkbox value using codeigniter?

My problem is, I key in the sibling details in the first row textboxs and i select the check box no error display. If i didn't select the checkbox its display the below error. Can you give some idea? i am new for CodeIgniter.
I got error message: (How i can solve the error)
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: controllers/registration.php
Line Number: 288
Below my Code:
foreach($querystud_frm->result() as $row)
{
echo "<tr><td>".$i.")</td>";
$data=array('name'=>'s_sibling_name[]','class'=>'textbox','value'=>$row->s_sibling_name,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_nric[]','class'=>'textbox','value'=>$row->s_sibling_nric,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$sib_dob=date('d-m-Y',strtotime(trim($row->s_sibling_dob)));
$data=array('name'=>'s_sibling_dob[]','class'=>'textbox','value'=>$sib_dob,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_relation[]','class'=>'textbox','value'=>$row->s_sibling_relation,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_occupation[]','class'=>'textbox','value'=>$row->s_sibling_occupation,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$data=array('name'=>'s_sibling_income[]','class'=>'textbox','value'=>$row->s_sibling_income,'style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
$sib_yes = $row->s_sibling_yes;
echo $sib_yes;
if($sib_yes == 'YES')
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'YES', 'checked' => TRUE);
echo "<td >".form_checkbox($data)."</td>";
}
else
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'NO', 'checked' => FALSE);
echo "<td >".form_checkbox($data)."</td>";
}
echo "</tr>";
$i++;
}
if($i<10)
{
$var=array("s_sibling_name","s_sibling_nric","s_sibling_dob","s_sibling_relation","s_sibling_occupation","s_sibling_income");
for($j=$i;$j<=10;$j++)
{
echo "<tr><td>".$j.")</td>";
foreach($var as $value)
{
$value=$value.'[]';
$data_val=array('name'=>$value,'class'=>'textbox','value'=>'','style'=>'text-transform:uppercase;');
echo "<td>".form_input($data_val)."</td>";
}
if($sib_yes == 'YES')
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'YES', 'checked' => TRUE);
echo "<td >".form_checkbox($data)."</td>";
}
else
{
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'NO', 'checked' => FALSE);
echo "<td >".form_checkbox($data)."</td>";
}
echo "</tr>";
}
unset($var);
}
$querystud_frm->free_result();
}
else
{
$var=array("s_sibling_name","s_sibling_nric","s_sibling_dob","s_sibling_relation","s_sibling_occupation","s_sibling_income");
$var_sib=array("s_sibling_yes");
for($i=1;$i<=10;$i++)
{
echo "<tr><td>".$i.")</td>";
foreach($var as $value)
{
$name=$value.'[]';
$data=array('name'=>$name,'class'=>'textbox','value'=>'','style'=>'text-transform:uppercase;');
echo "<td >".form_input($data)."</td>";
}
$data= array('name' => 's_sibling_yes[]', 'id' => 's_sibling_yes', 'value' => 'YES', 'checked' => FALSE);
echo "<td >".form_checkbox($data)."</td>";
echo "</tr>";
}
unset($var,$i,$data,$var_sib);
}
controller/registration.php
if($this->input->post('siblingsfrm'))
{
$this->data['nric']=$this->input->post('s_nric');
//echo $this->input->post('name');
$name=$this->input->post('s_sibling_name');
$nric=$this->input->post('s_sibling_nric');
$dob=$this->input->post('s_sibling_dob');
//$dob=strtotime($dob);
//$dob=date('Y-m-d',strtotime($dob));
$relation=$this->input->post('s_sibling_relation');
$occupation=$this->input->post('s_sibling_occupation');
$income=$this->input->post('s_sibling_income');
$sib_yes=$this->input->post('s_sibling_yes');
$sib_id=$this->input->post('s_sibling_id');
//print_r($sib_id);
//print_r($name);
//exit();
//$this->load->helper('date');
for($i=0;$i<count($name);$i++)
{
if($name[$i]!='')
{
$income[$i]=trim($income[$i]);
if($income[$i]=='')
$income[$i]=0;
if($sib_yes[$i]!= 'YES')
$sib_yes[$i]='NO';
$date=date('Y-m-d',strtotime(trim($dob[$i])));
$insert_values=array('s_nric'=>$this->data['nric'],'s_sibling_name'=>strtoupper(trim($name[$i])),
's_sibling_nric'=>strtoupper(trim($nric[$i])),'s_sibling_dob'=>$date,
's_sibling_relation'=>strtoupper(trim($relation[$i])),
's_sibling_occupation'=>strtoupper(trim($occupation[$i])),
's_sibling_income'=>strtoupper(trim($income[$i])),
's_sibling_yes'=>trim($sib_yes[$i]));
if(is_array($sib_id) && isset($sib_id[$i]) )
{
$where=array('s_sibling_id'=>$sib_id[$i]);
$this->db->update('si_student_siblings',$insert_values,$where);
}
else
{
//print_r($insert_values);
$this->db->insert('si_student_siblings',$insert_values);
}
}
}
$this->data['level']=7;
}
The problem is that if a checkbox wasn't checked, it won't send any data at all to the server. So, this line of code...
$name=$this->input->post('s_sibling_name');
...will actually set the $name variable to FALSE (see $this->input->post() documentation in the guide)
Thus, the first time through your loop, your code is looking for the array item at $name[0], when in fact $name is not even an array, it's FALSE.
You could surround your for loop with an if/else statement to solve this problem (not the most elegant solution, but it would work):
if (is_array($name) && count($name) > 0)
{
for($i=0;$i<count($name);$i++)
{
if($name[$i]!='')
//etcetera...
}
}

CakePHP - Saving one session variable deletes another

I'm using session variables in CakePHP to store my relevant user Twitter and Facebook data, when the user logs in if he has linked his Twitter and FB accounts this information is saved in the session variable next to my own user data.
I have a screen where the user can link and unlink said social network data, the problem is the following:
Let's say I have both networks connected, I decide to disconnect from Facebook, the session variable for Facebook is deleted. Now I wish to reconnect to Facebook, I click on the Connect button, the Facebook data is saved but for some reason it deletes the Twitter variable.
The way my process works is the following:
1) User clicks on connect button.
2) User is directed to social network auth.
3) User is directed to a function that takes the required data, saves it in a session variable called NetworkData and is directed back to the page where he clicked the button.
4) The NetworkData is extracted, set as the according social network (Facebook or Twitter) in the session and is deleted from the session.
Code is as follows:
This is the function that the user is directed after login in to Twitter or FB:
function retrieve_network($page) {
$networkData = null;
$this->autoRender = false;
$this->layout = 'ajax';
if(isset($_GET['oauth_token'])) {
$token = $this->TwitterHelper->setOAuthToken($_GET['oauth_token']);
$userinfo = $this->TwitterHelper->getTwitterUserInfo();
$networkData = array(
'TwitterData' => array(
'username' => $userinfo['username'],
'name' => $userinfo['name'],
'token' => $token->oauth_token,
'token_secret' => $token->oauth_token_secret
)
);
} else if (isset($_GET['code'])) {
$token = $this->FacebookHelper->facebook->getAccessToken();
$userinfo = $this->FacebookHelper->getUserInfo();
$networkData = array(
'FacebookData' => array(
'username' => $userinfo['username'],
'name' => $userinfo['name'],
'email' => $userinfo['email'],
'token' => $token,
'link' => $userinfo['link'],
)
);
}
$this->Session->write('NetworkData', $networkData);
if($page == 'settings') {
$this->redirect(array('controller' => 'fonykers', 'action' => 'settings/networks'));
}
}
This is the function that retrieves what's in network data and sets it to the session:
function settings($tab) {
$this->layout = 'frontend';
$this->Fonyker->recursive = -1;
$this->TwitterData->recursive = -1;
$this->FacebookData->recursive = -1;
if(!$this->checkSessionCookie()) {
$this->redirect(array('controller' => 'pages', 'action' => 'home'));
}
$fields = array(
'Fonyker.id',
'Fonyker.username',
'Fonyker.name',
'Fonyker.email',
'Fonyker.gender',
'Fonyker.birthdate',
'Fonyker.image_url'
);
$fonyker = $this->Fonyker->find('first', array(
'conditions' => array(
'Fonyker.fonykid' => $this->Session->read('Fonyker.Fonyker.fonykid')
),
'fields' => $fields
));
$this->Fonyker->set($fonyker);
$this->data = $fonyker;
if($this->Session->read('NetworkData')) {
$networkData = $this->Session->read('NetworkData');
$this->Session->delete('NetworkData');
if($networkData['TwitterData']) {
$networkData['TwitterData']['fonyker_id'] = $fonyker['Fonyker']['id'];
if($this->TwitterData->save($networkData)) {
$this->Session->write('TwitterData', $networkData['TwitterData']);
}
} else if($networkData['FacebookData']) {
$networkData['FacebookData']['fonyker_id'] = $fonyker['Fonyker']['id'];
if($this->FacebookData->save($networkData)) {
$this->Session->write('FacebookData', $networkData['FacebookData']);
}
}
}
pr($this->Session->read());
if(!$this->Session->read('TwitterData')) {
$this->TwitterHelper->setTwitterObj();
$this->set('twitterUrl', $this->TwitterHelper->twitterObj->getAuthorizeUrl(null, array('oauth_callback' => 'http://127.0.0.1/fonykweb/pages/retrieve_network/settings')));
} else {
$this->set('twitterUrl', '#');
}
if(!$this->Session->read('FacebookData')) {
$this->set('facebookUrl', $this->FacebookHelper->facebook->getLoginUrl(array('redirect_uri' => 'http://localhost/fonykweb/pages/retrieve_network/settings','scope' => 'email,user_birthday,publish_stream,offline_access')));
} else {
$this->set('facebookUrl', '#');
}
$this->set('tab', $tab);
}
This is the function that removes the network if the user wishes:
function remove_network($network) {
$this->autoRender = false;
$this->Fonyker->recursive = -1;
$this->TwitterData->recursive = -1;
$this->FacebookData->recursive = -1;
$response = null;
if($network == 'twitter') {
$twitterData = $this->TwitterData->find('first', array(
'conditions' => array(
'TwitterData.fonyker_id' => $this->Session->read('TwitterData.fonyker_id')
)
));
if($this->TwitterData->delete($twitterData['TwitterData']['id'], false)) {
$this->TwitterHelper->setTwitterObj();
$twitterUrl = $this->TwitterHelper->twitterObj->getAuthorizeUrl(null, array('oauth_callback' => 'http://127.0.0.1/fonykweb/pages/retrieve_network/settings'));
$this->Session->delete('TwitterData');
$response = json_encode(array('ok' => true, 'url' => $twitterUrl));
} else {
$response = json_encode(array('ok' => false));
}
}
if($network == 'facebook') {
$facebookData = $this->FacebookData->find('first', array(
'conditions' => array(
'FacebookData.fonyker_id' => $this->Session->read('FacebookData.fonyker_id')
)
));
if($this->FacebookData->delete($facebookData['FacebookData']['id'], false)) {
$facebookUrl = $this->FacebookHelper->facebook->getLoginUrl(array('redirect_uri' => 'http://localhost/fonykweb/pages/retrieve_network/settings','scope' => 'email,user_birthday,publish_stream,offline_access'));
$this->Session->delete('FacebookData');
$response = json_encode(array('ok' => true, 'url' => $facebookUrl));
} else {
$response = json_encode(array('ok' => false));
}
}
echo $response;
}
View code:
<script type="text/javascript">
$(document).ready(function() {
var splitUrl = window.location.href.split('/');
$('#' + splitUrl[splitUrl.length - 1] + '-tab').addClass('active-tab');
$('#' + splitUrl[splitUrl.length - 1] + '-tab').children().addClass('active-tab');
});
</script>
<div class="prepend-1 prepend-top span-23">
<div class="tabs span-22">
<ul>
<li id="account-tab">
<a href="<?php echo $html->url(array('controller' => 'fonykers', 'action' => 'settings'), true); ?>/account">
Account
</a>
</li>
<li id="password-tab">
<a href="<?php echo $html->url(array('controller' => 'fonykers', 'action' => 'settings'), true); ?>/password">
Password
</a>
</li>
<li id="notifications-tab">
<a href="<?php echo $html->url(array('controller' => 'fonykers', 'action' => 'settings'), true); ?>/notifications">
Notifications
</a>
</li>
<li id="networks-tab">
<a href="<?php echo $html->url(array('controller' => 'fonykers', 'action' => 'settings'), true); ?>/networks">
Social Networks
</a>
</li>
</ul>
</div>
<div class="tab-content prepend-top prepend-1">
<?php
if($tab == 'account') {
echo $this->element('settings/account');
} else if ($tab == 'password') {
echo $this->element('settings/password');
} else if ($tab == 'notifications') {
echo $this->element('settings/notifications');
} else {
echo $this->element('settings/networks');
}
?>
</div>
</div>
Element code:
<script type="text/javascript">
$(document).ready(function(){
var deleteNetwork = function(network, button) {
$.ajax({
url: '<?php echo $html->url('/fonykers/remove_network/', true); ?>' + network,
dataType: 'json',
type: 'POST',
success: function(response) {
if(response.ok) {
button.replaceWith('<a id="'+network+'-connect" class="connect-button connect" href="'+response.url+'" class="span-3">Connect</a>');
}
}
});
}
if($('#twitter-connect').attr('href') == '#'){
$('#twitter-connect').addClass('connected');
$('#twitter-connect').html('Connected');
} else {
$('#twitter-connect').addClass('connect');
$('#twitter-connect').html('Connect');
}
if($('#facebook-connect').attr('href') == '#'){
$('#facebook-connect').addClass('connected');
$('#facebook-connect').html('Connected');
} else {
$('#facebook-connect').addClass('connect');
$('#facebook-connect').html('Connect');
}
$('.connected').hover(
function() {
$(this).removeClass('connected');
$(this).addClass('disconnect');
$(this).html('Disconnect')
},
function() {
$(this).removeClass('disconnect');
$(this).addClass('connected');
$(this).html('Connected')
}
);
$('#twitter-connect').click(function(event) {
if($(this).attr('href') == '#') {
event.preventDefault();
deleteNetwork('twitter', $(this));
}
});
$('#facebook-connect').click(function(event) {
if($(this).attr('href') == '#') {
event.preventDefault();
deleteNetwork('facebook', $(this));
}
});
});
</script>
<div class="span-4 prepend-top">
<div class="span-4">
<div class="span-1">
<?php echo $html->image('twitter-connect.png', array('alt' => 'Twitter', 'class' => 'span-1', 'style' => 'height:40px;width:40px')); ?>
</div>
<div class="span-3 last">
<a id="twitter-connect" class="connect-button" href="<?php echo $twitterUrl; ?>" class="span-3"></a>
</div>
</div>
<div class="span-4 prepend-top">
<div class="span-1">
<?php echo $html->image('facebook-connect.png', array('alt' => 'Twitter', 'class' => 'span-1', 'style' => 'height:40px;width:40px')); ?>
</div>
<div class="span-3 last">
<a id="facebook-connect" class="connect-button" href="<?php echo $facebookUrl; ?>"></a>
</div>
</div>
</div>
Sorry for the long post.
In your retrieve_network action, which I am assuming you call when a user reconnects to a particular service, you are overwriting the NetworkData session variable
if you find 1 particular Service has been connected to:
if(isset($_GET['oauth_token'])) {...}
OR
if(isset($_GET['code'])) {...}
You set $networkData to the returned services object and then overwrite the whole session via:
$this->Session->write('NetworkData', $networkData);
Following your code, I would always check to see if an existing service is currently in session and if so do not overwrite the whole session, just add the particular data to the existing NetworkData session array:
if($this->Session->read('NetworkData.TwitterData')){
$facebookData = array(
'username' => $userinfo['username'],
'name' => $userinfo['name'],
'email' => $userinfo['email'],
'token' => $token,
'link' => $userinfo['link'],
);
$this->Session->write('NetworkData.FacebookData', $facebookData);
}
Note: This is just an example showing how you can achieve this. I would refactor that method with better logic for this particular situation, perhaps storing TwitterData and FacebookData in their own separate arrays as opposed to a larger more complex NetworkData array. Additionally, you can access $_GET params via $this->params['url']['paramname'] to maintain cakePHP convention.
I think the issue is that you are replacing network data, instead of merging it.
This means that when you login with FB for example, you replace any twitter data with FB, instead of keeping them both.
I'm hoping that maybe instead of
$this->Session->write('NetworkData', $networkData);
that
$this->Session->write('NetworkData', array_merge($networkData, $this->Session->read('NetworkData'));
might work.
Otherwise, it seems to me the session deleting code shouldn't be interacting for one to delete the other. I could have missed something in skimming it though. I'd do some echo()ing / debugging to follow the code execution paths.

Categories