PHP code to upload multiple files with database - php

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');
?>

Related

The search result are all the data in the database instead of a specific data

When i go to the search box and type a specific roll number, it shows all the data in my database instead of the data that i have entered by roll number. i'm new to php and codeigniter.
Here's the Model:
<?php
class Stud_Model extends CI_Model {
function __construct() {
parent::__construct();
}
public function insert($data) {
if ($this->db->insert("stud", $data)) {
return true;
}
}
public function delete($roll_no) {
if ($this->db->delete("stud", "roll_no = ".$roll_no)) {
return true;
}
}
public function update($data,$old_roll_no) {
$this->db->set($data);
$this->db->where("roll_no", $old_roll_no);
$this->db->update("stud", $data);
}
public function get_results($search_term='default')
{
// Use the Active Record class for safer queries.
$this->db->select('*');
$this->db->from('stud');
$this->db->like('roll_no',$search_term);
// Execute the query.
$query = $this->db->get();
// Return the results.
return $query->result_array();
}
}
?>
The Controller:
<?php
class Stud_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->database(); //manual connection to the database
}
public function index() {
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->helper('form');
$this->load->view('Stud_view',$data);
}
public function add_student_view() {
$this->load->helper('form');
$this->load->view('Stud_add');
}
public function add_student() {
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name'),
'surname' => $this->input->post('surname'),
'mname' => $this->input->post('mname'),
'mobileno' => $this->input->post('mobileno'),
'email' => $this->input->post('email'),
'homeadd' => $this->input->post('homeadd')
);
$this->Stud_Model->insert($data);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function update_student_view() {
$this->load->helper('form');
$roll_no = $this->uri->segment('3');
$query = $this->db->get_where("stud",array("roll_no"=>$roll_no));
$data['records'] = $query->result();
$data['old_roll_no'] = $roll_no;
$this->load->view('Stud_edit',$data);
}
public function update_student(){
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name'),
'surname' => $this->input->post('surname'),
'mname' => $this->input->post('mname'),
'mobileno' => $this->input->post('mobileno'),
'email' => $this->input->post('email'),
'homeadd' => $this->input->post('homeadd')
);
$old_roll_no = $this->input->post('old_roll_no');
$this->Stud_Model->update($data,$old_roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function delete_student() {
$this->load->model('Stud_Model');
$roll_no = $this->uri->segment('3');
$this->Stud_Model->delete($roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function execute_search()
{
$this->load->model('Stud_Model');
// Retrieve the posted search term.
$search_term = $this->input->post('search');
// Use a model to retrieve the results.
$data['records'] = $this->Stud_Model->get_results($search_term);
// Pass the results to the view.
$this->load->view('result_view',$data);
}
}
?>
The View:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
Add
<br>
<?php
echo form_open('Stud_controller/execute_search');
echo form_input(array('roll_no'=>'search'));
echo form_submit('search_submit','Submit');
?>
</br>
<br>
<table border = "1">
<?php
$i = 1;
echo "<tr>";
echo "<td>Sr#</td>";
echo "<td>Roll No.</td>";
echo "<td>First Name</td>";
echo "<td>Surname</td>";
echo "<td>Middle Name</td>";
echo "<td>Mobile/Telephone No.</td>";
echo "<td>Email Address</td>";
echo "<td>Home Address</td>";
echo "<td>Edit</td>";
echo "<td>Delete</td>";
echo "<tr>";
?>
<?php foreach($records as $r) {
echo "<tr>";
echo "<td>".$i++."</td>";
echo "<td>".$r->roll_no."</td>";
echo "<td>".$r->name."</td>";
echo "<td>".$r->surname."</td>";
echo "<td>".$r->mname."</td>";
echo "<td>".$r->mobileno."</td>";
echo "<td>".$r->email."</td>";
echo "<td>".$r->homeadd."</td>";
echo "<td><a href = '".base_url()."stud/edit/".$r->roll_no."'>Edit</a></td>";
echo "<td><a href = '".base_url()."stud/delete/".$r->roll_no."'>Delete</a></td>";
echo "<tr>";
}
?>
</table>
</body>
</html>
And the result view of the search box:
<!DOCTYPE html>
<head>
<table border = "1">
<?php
echo "<tr>";
echo "<td>Roll No.</td>";
echo "<td>First Name</td>";
echo "<td>Surname</td>";
echo "<td>Middle Name</td>";
echo "<td>Mobile/Telephone No.</td>";
echo "<td>Email Address</td>";
echo "<td>Home Address</td>";
echo "<tr>";
?>
<?php foreach($records as $r) {
echo "<tr>";
echo "<td>".$r['roll_no']."</td>";
echo "<td>".$r['name']."</td>";
echo "<td>".$r['surname']."</td>";
echo "<td>".$r['mname']."</td>";
echo "<td>".$r['mobileno']."</td>";
echo "<td>".$r['email']."</td>";
echo "<td>".$r['homeadd']."</td>";
echo "<tr>";
}
?>
</table>
</head>
</html>
For example if I type 1 in the search box it will display all the data like this:
Sr# Roll No. First Name Surname Middle Name Mobile/Telephone No. Email Address Home Address
1 1 Charles Xavier Howlett 1234567891011 xaviercharles#gmail.com 9912 east street
2 2 Nancy Hopkins Johnson 09108873512 nancehp#gmail.com 3628 north street
instead of showing roll number one only.
You have a wrong parameter on your input search form, if you supply an array as a parameter, it will produce a name => value attribute pair.
So you could change the search form view to :
...
<?php
echo form_open('Stud_controller/execute_search');
echo form_input(array('name'=>'search'));
echo form_submit('search_submit','Submit');
?>
...

Cakephp 2.X disable/enable syntax

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);
}
});

When my controller function loads a view, the URL has the controller name and function still in the URL. How can I get rid of this?

Basically my function checks to see if something is in a database. If it's found it returns true and carries on to the next view. However, if it returns false it reloads the home.php view but it seems to still leave URI segments in the URL...
example:
www.example.com/index.php/home/checkSearchFields
How to I get it to get rid of the 'home/checkSearchFields'?
Thanks for your help.
home.php (view)
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
var base_url = window.location.origin;
function getStates(value) {
$.post(base_url + "/buildings/getstates.php",{partialState:value},function(data){
$("#results").html(data);
});
}
function myFunction(){
var target = event.target || event.srcElement;
var str = target.innerHTML;
console.log(str);
document.getElementById("stateSearch").value = str ;
$( "#results" ).empty();
}
</script>
</head>
<body>
<div id="container">
<h1>Room Finder</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('home/checkSearchFields'); ?>
<div class="searchfield">
Building: <br/>
<input type="text" name="building" onkeyup="getStates(this.value)" id="stateSearch" autocomplete="off"/>
</div><!-- closes searchfield -->
<div class="searchfield">
Room #: <br/>
<input type="text" name="roomNum" autocomplete="off"/><br/>
</div><!-- closes searchfield -->
<div class="submit">
<input type="submit" value="Submit" name="submit" />
</div><!-- closes submit -->
</form>
<div id="results"></div>
home.php (Controller)
class home extends CI_Controller {
public function index()
{
$this->load->view('home');
}
public function checkSearchFields(){
$this->form_validation->set_rules('building', 'Building', 'required|callback_verifyBuilding');
$this->form_validation->set_rules('roomNum', 'RoomNum', 'required');
$roomNumber = $this->session->userdata('roomNumber'); // going to be checked to see if null
if($this->form_validation->run() == false){
$this->load->view('home');
}else{
$this->load->view('worked');
}
}
public function verifyBuilding(){
$buildings = $this->input->post('building');
$roomNum = $this->input->post('roomNum');
$this->load->model('BuildingModel');
if($this->BuildingModel->userSearch($buildings, $roomNum)){
return true;
}else{
$this->form_validation->set_message('verifyBuilding', 'Incorrect Building Name or Room Number... Please try again...');
return false;
}
}
}
buildingmodel.php (Model)
class BuildingModel extends CI_Model{
public function userSearch($buildings, $roomNum){
$this->db->select('*');
$this->db->from('buildings');
$this->db->where('buildingName', $buildings);
$query = $this->db->get();
if($query->num_rows() == 1){
foreach($query->result_array() as $row)
{
$buildingID = $row['buildingID'];
$buildingName = $row['buildingName'];
$buildingLocation = $row['buildingLocation'];
$imagePath = $row['imagePath'];
}
$userSearch = array(
'buildingID' => $buildingID,
'buildingName' => $buildingName,
'buildingLocation' => $buildingLocation,
'imagePath' => $imagePath,
);
$this->session->set_userdata($userSearch);
//query DB for the room numbers
$this->db->select('*');
$this->db->from('rooms');
$this->db->where('buildingID', $buildingID);
$this->db->where('roomNumber', $roomNum);
$query2 = $this->db->get();
if($query2->num_rows() == 1){
foreach($query2->result_array() as $row)
{
$roomID = $row['roomID'];
$roomNumber = $row['roomNumber'];
$roomCode = $row['roomCode'];
$office = $row['office'];
$location = $row['location'];
$roomName = $row['roomName'];
}
$userSearch = array(
'roomID' => $roomID,
'roomNumber' => $roomNumber,
'roomCode' => $roomCode,
'office' => $office,
'location' => $location,
'roomName' => $roomName,
);
$this->session->set_userdata($userSearch);
}
return true;
}else{
return false;
}
}
}
As you said, it just loads the view. Which view is loaded, has nothing to do with how the URL looks like.
You could replace this:
if($this->form_validation->run() == false){
$this->load->view('home');
}else{
$this->load->view('worked');
}
with this:
if($this->form_validation->run() == false){
redirect('home');
}else{
$this->load->view('worked');
}
When it fails, it redirects you to the homepage.

codeigniter validating from textbox value(jquery) from array(php)

I want to validate whether my 3 input's are the same as the value in the array.
<?php
$aylength = 0;
$resultacyear = array();
foreach($academicyear->result() as $ay)
{
$item = array(
'tahunakademik' => $ay->Tahun_Akademik,
'idsemester' => $ay->ID_Semester,
'idlevelyear' => $ay->ID_Level_Year
);
$resultacyear[]= $item;
$aylength++;
}
?>
<script type="text/javascript">
$('#btn_save').click(function() {
<?php $inc = 0; ?>
for(i=0;i<parseInt(<?php echo $aylength?>);i++)
{
if($('#txt_tahunAkademik').val()=="<?php echo $resultacyear[$inc]['tahunakademik'] ?>" && $('#cb_semester').val()=="<?php echo $resultacyear[$inc]['idsemester'] ?>" && $('#cmb_YearLevel').val()=="<?php echo $resultacyear[$inc]['idlevelyear'] ?>")
{
alert ("Data already exists!!");
return false;
break;
}
else
{
<?php $inc++; ?>
return false;
}
}
});
</script>
When i tried, it didn't validate or even checks the value.
Is something wrong with my validation??

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