Category: CakePHP


First of all, Happy New Year! :) I’ve been busy these past weeks. But I would like to spare some time today and share a little but useful tip on how to remove null or empty array values before finally saving it to the database. I recently stumble upon this issue and have found the set::filter core utility really helpful.

In certain situations that you encounter this.

[Product] => Array
        (
            [0] => Array
                (
                    [id] => 35
                    [url] => item35.php
                )

            [1] => Array
                (
                [id] =>     
                [url] => 
                )

        )

Basically you just add the utility before saving the data to remove the array values.

<?php 
$this->data = Set::filter($this->data);
$this->Product->save($this->data);
?>

That’s about it. :)

It took me a couple of searches before finally got to solve the issue with having a validation for select box and not being able to display the error message. Tried a couple of solutions over the net then finally got the simple and efficient one. :)

Add this below your form select.

<?php echo $form->error('nameofselectbox');?>

That’s it! :)

A month ago I made this Constant Contact component for a specific project. I’ve decided now to share it to you guys, it might save you some time :)

By the way, make sure you have a Constant Contact developer account to be able to access it. For more info read here.

constant_contact.php


<?php

class ConstantContactComponent extends Object {


/**
  * The username for the Constant Contact API
  * @access public
  * @var string
  */
  var $api_user = null;

  /**
  * The password for the Constant Contact API
  * @access public
  * @var string
  */
  var $api_pass = null;

  /**
  * The API key for this product.
  * @access public
  * @var string
  */
  var $api_key = null;


/**
  * Start CURL operation
  * @param $url, $entry, $type
  * @return response and httpcode

  */

function startCurl($url, $entry, $type){

$handle = curl_init();
$userNamePassword = $this->api_key . '%' . $this->api_user . ':' . $this->api_pass ;
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($handle, CURLOPT_USERPWD, $userNamePassword);

if ($type == 'post' ){
curl_setopt($handle, CURLOPT_POST, 1);
curl_setopt($handle, CURLOPT_POSTFIELDS , $entry);
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
} 
if ($type =='put'){
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($handle, CURLOPT_POSTFIELDS, $entry);
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
}

if ($type == 'delete'){
curl_setopt($handle, CURLOPT_POST, 1);
curl_setopt($handle, CURLOPT_POSTFIELDS , $entry);
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "DELETE");
}

if ($type == 'bulk') {
curl_setopt($handle, CURLOPT_POST, 1);
curl_setopt($handle, CURLOPT_POSTFIELDS , $entry);
curl_setopt ($handle, CURLOPT_HTTPHEADER, Array("Content-Type: application/x-www-form-urlencoded"));
}

$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);

return array($response, $code);
}

 /**
  * Create Contact
  * @param string $detail contains the array of all the details to added on this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */


function createContact($detail){

$entry = '
<entry xmlns="http://www.w3.org/2005/Atom">
<title type="text"> </title>
<updated>' . date('c') . '</updated>
<author></author>
<id>data:,none</id>
<summary type="text">Contact</summary>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/">
<EmailAddress>'. $detail['email_address'] .'</EmailAddress>
<EmailType>HTML</EmailType>
<Name>'. $detail['name'] .'</Name>
<FirstName>'. $detail['first_name'] .'</FirstName>
<MiddleName>'. $detail['middle_name'] .'</MiddleName>
<LastName>'. $detail['last_name'] .'</LastName>
<JobTitle>'. $detail['job_title'] .'</JobTitle>
<CompanyName>'. $detail['company_name'] .'</CompanyName>
<HomePhone>'. $detail['home_phone'] .'</HomePhone>
<WorkPhone>'. $detail['work_phone'] .'</WorkPhone>
<Addr1>'. $detail['address_1'] .'</Addr1>
<Addr2>'. $detail['address_2'] .'</Addr2>
<Addr3>'. $detail['address_3'] .'</Addr3>
<City>'. $detail['city'] .'</City>
<StateCode>'. $detail['state_code'] .'</StateCode>
<StateName>'. $detail['state_name'] .'</StateName>
<CountryCode>'. $detail['country_code'] .'</CountryCode>
<CountryName>'. $detail['country_name'] .'</CountryName>
<PostalCode>'. $detail['postal_code'] .'</PostalCode>
<SubPostalCode>'. $detail['subpostal_code'] .'</SubPostalCode>
<Note>'. $detail['note'] .'</Note>
<CustomField1>'. $detail['custom_field_1'] .'</CustomField1>
<CustomField2>'. $detail['custom_field_2'] .'</CustomField2>
<CustomField3>'. $detail['custom_field_3'] .'</CustomField3>
<CustomField4>'. $detail['custom_field_4'] .'</CustomField4>
<CustomField5>'. $detail['custom_field_5'] .'</CustomField5>
<CustomField6>'. $detail['custom_field_6'] .'</CustomField6>
<CustomField7>'. $detail['custom_field_7'] .'</CustomField7>
<CustomField8>'. $detail['custom_field_8'] .'</CustomField8>
<CustomField9>'. $detail['custom_field_9'] .'</CustomField9>
<CustomField10>'. $detail['custom_field_10'] .'</CustomField10>
<CustomField11>'. $detail['custom_field_11'] .'</CustomField11>
<CustomField12>'. $detail['custom_field_12'] .'</CustomField12>
<CustomField13>'. $detail['custom_field_13'] .'</CustomField13>
<CustomField14>'. $detail['custom_field_14'] .'</CustomField14>
<CustomField15>'. $detail['custom_field_15'] .'</CustomField15>
<OptInSource>ACTION_BY_CUSTOMER</OptInSource>
<ContactLists>
<ContactList id="http://api.constantcontact.com/ws/customers/' . $this->api_user . '/lists/1" />
</ContactLists>
</Contact>
</content>
</entry>';


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts";

list($response, $code) = $this->startCurl($url, $entry, 'post'); 

//var_dump($code);

if ($code > 199 && $code < 300){ $output =  "Added Contact" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;


}


 /**
  * Obtain Contact Information
  * @param string $id contains the specific id for this contact.
  * @return xml 
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function obtainContactInfo($id){

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, '', ''); 

return $response;


}


 /**
  * Update Contact Information
  * @param string $id contains the id for this contact.
  * @param string $detail contains the array of all the details to be updated to this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function updateContactInfo($id, $detail){

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, ' ', ' '); 

$test = $this->xml2array($response);


$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<link href="/ws/customers/' . $this->api_user . '/contacts/'.$id.'" rel="edit" />
<id>http://api.constantcontact.com/ws/customers/' . $this->api_user . '/contacts/'. $id .'</id>
<title type="text">Contact: </title>
<updated>2010-02-01T00:03:11.502Z</updated>
<author>
<name>Constant Contact</name>
</author>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/" id="http://api.constantcontact.com/ws/customers/' . $this->api_user . '/contacts/'. $id .'">
<Status>Active</Status>';
if (isset($detail['email_address'])){ $entry .= '<EmailAddress>'.$detail['email_address'].'</EmailAddress>'; } else { $entry .= '<EmailAddress>'.$test[0]['elements'][4]['text'].'</EmailAddress>';  }
if (isset($detail['email_type'])){ $entry .= '<EmailType>'.$detail['email_type'].'</EmailType>'; } else { $entry .= '<EmailType>'.$test[0]['elements'][5]['text'].'</EmailType>';  }
if (isset($detail['name'])){ $entry .= '<Name>'.$detail['name'].'</Name>'; } else { $entry .= '<Name>'.$test[0]['elements'][6]['text'].'</Name>';  }
if (isset($detail['first_name'])){ $entry .= '<FirstName>'.$detail['first_name'].'</FirstName>'; } else { $entry .= '<FirstName>'.$test[0]['elements'][7]['text'].'</FirstName>';  }
if (isset($detail['middle_name'])){ $entry .= '<MiddleName>'.$detail['middle_name'].'</MiddleName>'; } else { $entry .= '<MiddleName>'.$test[0]['elements'][8]['text'].'</MiddleName>';  }
if (isset($detail['last_name'])){ $entry .= '<LastName>'.$detail['last_name'].'</LastName>'; } else { $entry .= '<LastName>'.$test[0]['elements'][9]['text'].'</LastName>';  }
if (isset($detail['job_title'])){ $entry .= '<JobTitle>'.$detail['job_title'].'</JobTitle>'; } else { $entry .= '<JobTitle>'.$test[0]['elements'][10]['text'].'</JobTitle>';  }
if (isset($detail['company_name'])){ $entry .= '<CompanyName>'.$detail['company_name'].'</CompanyName>'; } else { $entry .= '<CompanyName>'.$test[0]['elements'][11]['text'].'</CompanyName>';  }
if (isset($detail['home_phone'])){ $entry .= '<HomePhone>'.$detail['home_phone'].'</HomePhone>'; } else { $entry .= '<HomePhone>'.$test[0]['elements'][12]['text'].'</HomePhone>';  }
if (isset($detail['work_phone'])){ $entry .= '<WorkPhone>'.$detail['work_phone'].'</WorkPhone>'; } else { $entry .= '<WorkPhone>'.$test[0]['elements'][13]['text'].'</WorkPhone>';  }
if (isset($detail['address_1'])){ $entry .= '<Addr1>'.$detail['address_1'].'</Addr1>'; } else { $entry .= '<Addr1>'.$test[0]['elements'][14]['text'].'</Addr1>';  }
if (isset($detail['address_2'])){ $entry .= '<Addr2>'.$detail['address_2'].'</Addr2>'; } else { $entry .= '<Addr2>'.$test[0]['elements'][15]['text'].'</Addr2>';  }
if (isset($detail['address_3'])){ $entry .= '<Addr3>'.$detail['address_3'].'</Addr3>'; } else { $entry .= '<Addr3>'.$test[0]['elements'][16]['text'].'</Addr3>';  }
if (isset($detail['city'])){ $entry .= '<City>'.$detail['city'].'</City>'; } else { $entry .= '<City>'.$test[0]['elements'][17]['text'].'</City>';  }
if (isset($detail['state_code'])){ $entry .= '<StateCode>'.$detail['state_code'].'</StateCode>'; } else { $entry .= '<StateCode>'.$test[0]['elements'][18]['text'].'</StateCode>';  }
if (isset($detail['state_name'])){ $entry .= '<StateName>'.$detail['state_name'].'</StateName>'; } else { $entry .= '<StateName>'.$test[0]['elements'][19]['text'].'</StateName>';  }
if (isset($detail['country_code'])){ $entry .= '<CountryCode>'.$detail['country_code'].'</CountryCode>'; } else { $entry .= '<CountryCode>'.$test[0]['elements'][20]['text'].'</CountryCode>';  }
if (isset($detail['country_name'])){ $entry .= '<CountryName>'.$detail['country_name'].'</CountryName>'; } else { $entry .= '<CountryName>'.$test[0]['elements'][21]['text'].'</CountryName>';  }
if (isset($detail['postal_code'])){ $entry .= '<PostalCode>'.$detail['postal_code'].'</PostalCode>'; } else { $entry .= '<PostalCode>'.$test[0]['elements'][22]['text'].'</PostalCode>';  }
if (isset($detail['subpostal_code'])){ $entry .= '<SubPostalCode>'.$detail['subpostal_code'].'</SubPostalCode>'; } else { $entry .= '<SubPostalCode>'.$test[0]['elements'][23]['text'].'</SubPostalCode>';  }
if (isset($detail['note'])){ $entry .= '<Note>'.$detail['note'].'</Note>'; } else { $entry .= '<Note>'.$test[0]['elements'][24]['text'].'</Note>';  }
if (isset($detail['custom_field_1'])){ $entry .= '<CustomField1>'.$detail['custom_field_1'].'</CustomField1>'; } else { $entry .= '<CustomField1>'.$test[0]['elements'][25]['text'].'</CustomField1>';  }
if (isset($detail['custom_field_2'])){ $entry .= '<CustomField2>'.$detail['custom_field_2'].'</CustomField2>'; } else { $entry .= '<CustomField2>'.$test[0]['elements'][26]['text'].'</CustomField2>';  }
if (isset($detail['custom_field_3'])){ $entry .= '<CustomField3>'.$detail['custom_field_3'].'</CustomField3>'; } else { $entry .= '<CustomField3>'.$test[0]['elements'][27]['text'].'</CustomField3>';  }
if (isset($detail['custom_field_4'])){ $entry .= '<CustomField4>'.$detail['custom_field_4'].'</CustomField4>'; } else { $entry .= '<CustomField4>'.$test[0]['elements'][28]['text'].'</CustomField4>';  }
if (isset($detail['custom_field_5'])){ $entry .= '<CustomField5>'.$detail['custom_field_5'].'</CustomField5>'; } else { $entry .= '<CustomField5>'.$test[0]['elements'][29]['text'].'</CustomField5>';  }
if (isset($detail['custom_field_6'])){ $entry .= '<CustomField6>'.$detail['custom_field_6'].'</CustomField6>'; } else { $entry .= '<CustomField6>'.$test[0]['elements'][30]['text'].'</CustomField6>';  }
if (isset($detail['custom_field_7'])){ $entry .= '<CustomField7>'.$detail['custom_field_7'].'</CustomField7>'; } else { $entry .= '<CustomField7>'.$test[0]['elements'][31]['text'].'</CustomField7>';  }
if (isset($detail['custom_field_8'])){ $entry .= '<CustomField8>'.$detail['custom_field_8'].'</CustomField8>'; } else { $entry .= '<CustomField8>'.$test[0]['elements'][32]['text'].'</CustomField8>';  }
if (isset($detail['custom_field_9'])){ $entry .= '<CustomField9>'.$detail['custom_field_9'].'</CustomField9>'; } else { $entry .= '<CustomField9>'.$test[0]['elements'][33]['text'].'</CustomField9>';  }
if (isset($detail['custom_field_10'])){ $entry .= '<CustomField10>'.$detail['custom_field_10'].'</CustomField10>'; } else { $entry .= '<CustomField10>'.$test[0]['elements'][34]['text'].'</CustomField10>';  }
if (isset($detail['custom_field_11'])){ $entry .= '<CustomField11>'.$detail['custom_field_11'].'</CustomField11>'; } else { $entry .= '<CustomField11>'.$test[0]['elements'][35]['text'].'</CustomField11>';  }
if (isset($detail['custom_field_12'])){ $entry .= '<CustomField12>'.$detail['custom_field_12'].'</CustomField12>'; } else { $entry .= '<CustomField12>'.$test[0]['elements'][36]['text'].'</CustomField12>';  }
if (isset($detail['custom_field_13'])){ $entry .= '<CustomField13>'.$detail['custom_field_13'].'</CustomField13>'; } else { $entry .= '<CustomField13>'.$test[0]['elements'][37]['text'].'</CustomField13>';  }
if (isset($detail['custom_field_14'])){ $entry .= '<CustomField14>'.$detail['custom_field_14'].'</CustomField14>'; } else { $entry .= '<CustomField14>'.$test[0]['elements'][38]['text'].'</CustomField14>';  }
if (isset($detail['custom_field_15'])){ $entry .= '<CustomField15>'.$detail['custom_field_15'].'</CustomField15>'; } else { $entry .= '<CustomField15>'.$test[0]['elements'][39]['text'].'</CustomField15>';  }
$entry .='
<ContactLists>
<ContactList id="http://api.constantcontact.com/ws/customers/' . $this->api_user . '/lists/1">
<link xmlns="http://www.w3.org/2005/Atom" href="/ws/customers/' . $this->api_user . '/lists/1" rel="self" />
<OptInSource>ACTION_BY_CONTACT</OptInSource>
<OptInTime>2010-02-01T00:03:11.439Z</OptInTime>
</ContactList>
</ContactLists>
<Confirmed>false</Confirmed>
<InsertTime>2010-02-01T00:03:11.335Z</InsertTime>
<LastUpdateTime>2010-02-01T00:03:11.502Z</LastUpdateTime>
</Contact>
</content>
</entry>';


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;


list($response, $code) = $this->startCurl($url, $entry, 'put'); 

//var_dump($code);

if ($code > 199 && $code < 300){ $output =  "Updated Contact" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;


}


 /**
  * Search Contact By Email Address
  * @param email $email contains email address to be search on and return contact information.
  * @return xml
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function searchContactByEmail($email){

$emailAddress = str_replace("%40", "@", $email);

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts?email=".$emailAddress;

list($response, $code) = $this->startCurl($url, ' ', ' '); 

return $response;

}


 /**
  * Create Contact List - Add a group
  * @param string $detail contains the array of all the details to be created for this group.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function createContactList($detail){

$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<id>data:,</id>
<title/>
<author/>
<updated>2008-04-16</updated>
<content type="application/vnd.ctct+xml">
<ContactList xmlns="http://ws.constantcontact.com/ns/1.0/">
<OptInDefault>false</OptInDefault>
<Name>'. $detail['name'] .'</Name>
<SortOrder>'. $detail['sort_order'] .'</SortOrder>
</ContactList>
</content>
</entry>';

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/lists";

list($response, $code) = $this->startCurl($url, $entry, 'post'); 

//var_dump($code);

if ($code > 199 && $code < 300)
    { $output =  "Added Contact list" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;


}

 /**
  * Obtain Contact List - returns all groups on the list
  * @return xml
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function obtainListContact(){

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/lists";

list($response, $code) = $this->startCurl($url, ' ', ' '); 

return $response;

}


 /**
  * Obtain Contact List (group) Information
  * @param string $id contains the id for this Contact list.
  * @return xml
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function obtainContactListInfo($id){

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/lists/".$id;

list($response, $code) = $this->startCurl($url, ' ', ' '); 

return $response;


}


 /**
  * Update Contact List Information
  * @param string $id contains the id for this Contact list (group).
  * @param string $detail contains the array of all the details to be updated to this Contact List (group).
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */
function updateContactListInfo($id, $detail){

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/lists/".$id;

list($response, $code) = $this->startCurl($url, ' ', ' '); 

$test = $this->xml2array($response);


$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<link href="/ws/customers/'. $this->api_user .'/lists/'. $id .'" rel="edit" />
<id>http://api.constantcontact.com/ws/customers/'. $this->api_user .'/lists/'. $id .'</id>
<title type="text"></title>
<updated>2010-02-01T00:09:52.589Z</updated>
<author>
<name>Constant Contact</name>
</author>
<content type="application/vnd.ctct+xml">
<ContactList xmlns="http://ws.constantcontact.com/ns/1.0/" id="http://api.constantcontact.com/ws/customers/'. $this->api_user .'/lists/'. $id .'">
<OptInDefault>false</OptInDefault>';
if (isset($detail['name'])){ $entry .= '<Name>'.$detail['name'].'</Name>'; } else { $entry .= '<Name>'.$test[0]['elements'][4]['text'].'</Name>';  }
if (isset($detail['short_name'])){ $entry .= '<ShortName>'.$detail['short_name'].'</ShortName>'; } else { $entry .= '<ShortName>'.$test[0]['elements'][5]['text'].'</ShortName>';  }
$entry .= '<DisplayOnSignup>No</DisplayOnSignup>';
if (isset($detail['sort_order'])){ $entry .= '<SortOrder>'.$detail['sort_order'].'</SortOrder>'; } else { $entry .= '<SortOrder>'.$test[0]['elements'][7]['text'].'</SortOrder>';  }
$entry .='     
<Members id="http://api.constantcontact.com/ws/customers/'. $this->api_user .'/lists/'. $id .'"></Members>
</ContactList>
</content>
</entry>';

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/lists/".$id;

list($response, $code) = $this->startCurl($url, $entry, 'put'); 

//var_dump($code);

if ($code > 199 && $code < 300){ $output =  "Updated Contact List" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;



}



 /**
  * Add Contact to a Contact List (group)
  * @param string $id contains the id for this contact.
  * @param string $detail contains the array of all the details to be updated to this contact.
  * @param string $contact contains the array of all the ids of Contact Lists (groups) that will be added to this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */


function addContactToContactList($id, $detail, $contact){


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, ' ', ' '); 

$test = $this->xml2array($response);


$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<link href="/ws/customers/' . $this->api_user . '/contacts/'. $id .'" rel="edit" />
<id>http://api.constantcontact.com/ws/customers/' . $this->api_user . '/contacts/'. $id .'</id>
<title type="text"></title>
<updated>2010-02-01T00:03:11.502Z</updated>
<author>
<name>Constant Contact</name>
</author>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/" id="http://api.constantcontact.com/ws/customers/' . $this->api_user . '/contacts/'. $id .'">
<Status>Active</Status>
<EmailAddress>'.$test[0]['elements'][4]['text'].'</EmailAddress>
<OptInSource>ACTION_BY_CONTACT</OptInSource>
<ContactLists>';

for($a=0; count($contact) > $a; $a++ ){
        
$entry .= '<ContactList id="http://api.constantcontact.com/ws/customers/' . $this->api_user .'/lists/'.$contact[$a].'"></ContactList>';
}
 

$entry .= '</ContactLists>
<Confirmed>false</Confirmed>
<InsertTime>2010-02-01T00:03:11.335Z</InsertTime>
<LastUpdateTime>2010-02-01T00:03:11.502Z</LastUpdateTime>
</Contact>
</content>
</entry>';


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, $entry, 'put'); 

var_dump($code);

if ($code > 199 && $code < 300){ $output =  "Added Contact to List" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;



}


 /**
  * Add Multiple Contact to a Contact List (group)
  * @param string $detail contains the array of all the email addresses, first names and last names.
  * @param string $contact contains the id of Contact List (group).
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function addMultipleContactToContactList($detail, $contact){


$parameters = "activityType=SV_ADD";
$parameters .= "&data=";
$csvContacts = "Email+Address%2CFirst+Name%2CLast+Name%0A";


foreach ($detail as $key => $value):

$csvContact[] = str_replace("@", "%40", $key).'%2C+'.$value['first_name'].'%2C+'.$value['last_name'].'%0A';

endforeach;

$csvContacts .= implode("", $csvContact); 

//$parameters .= urlencode($csvContacts);
$parameters .= $csvContacts;
$parameters .= "&lists=".urlencode( 'http://api.constantcontact.com/ws/customers/'. $this->api_user .'/lists/'.$contact);

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/activities";

list($response, $code) = $this->startCurl($url, $parameters, 'bulk'); 

var_dump($code);

if ($code > 199 && $code < 300)
    { $output =  "Added Multiple Contact" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;

}


 /**
  * Opting in a Subscriber - Add Contact to a specific group and be removed to the do not mail list.
  * @param string $id contains the id for this contact.
  * @param string $email contains the email address for this contact.
  * @param string $contact contains the array of all the ids of Contact Lists (groups) that will be added to this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function OptInSubscriber($id, $email, $contact){


$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<link href="/ws/customers/' . $this->api_user . '/contacts/'.$id.'" rel="edit" />
<id>http://api.constantcontact.com/ws/customers/' . $this->api_user . '/contacts/'.$id.'</id>
<title type="text">Contact: </title>
<updated>2010-01-28T11:33:03.035Z</updated>
<author>
<name>Constant Contact</name>
</author>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/" id="http://api.constantcontact.com/ws/customers/' . $this->api_user .' /contacts/'.$id.'">
<Status>Do Not Mail</Status>
<EmailAddress>' . $email.'</EmailAddress>
<OptInSource>ACTION_BY_CONTACT</OptInSource>
<ContactLists>';

for($a=0; count($contact) > $a; $a++ ){
      
$entry .= '<ContactList id="http://api.constantcontact.com/ws/customers/' . $this->api_user .'/lists/'.$contact[$a].'">
<link xmlns="http://www.w3.org/2005/Atom" href="/ws/customers/' . $this->api_user .'/lists/'.$contact[$a].'" rel="self" /></ContactList>';
}


$entry .= '</ContactLists>
<Confirmed>false</Confirmed>
<InsertTime>2010-01-28T10:20:23.857Z</InsertTime>
<LastUpdateTime>2010-01-28T11:33:03.035Z</LastUpdateTime>
</Contact>
</content>
</entry>';



$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, $entry, 'put'); 

var_dump($code);

if ($code > 199 && $code < 300)
    { $output =  "Added Contact" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;


}


 /**
  * Opt out a Subscriber - Contact will added to the do not mail list.
  * @param string $id contains the id for this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */


function OptOutSubscriber($id){


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, ' ', 'delete'); 

var_dump($code);

if ($code > 199 && $code < 300)
    { $output =  "Opt Out Subscriber" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;


}


 /**
  * Remove Contact from Contact List - Remove Contact from all lists.
  * @param string $id contains the id for this contact.
  * @param string $email contains the email address for this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function removeContactFromContactList($id, $email){

$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<link href="/ws/customers/' . $this->api_user .' /contacts/'.$id.'" rel="edit" />
<id>http://api.constantcontact.com/ws/customers/' . $this->api_user .' /contacts/'.$id.'</id>
<title type="text"></title>
<updated>2010-01-28T11:33:03.035Z</updated>
<author>
<name>Constant Contact</name>
</author>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/" id="http://api.constantcontact.com/ws/customers/' . $this->api_user .' /contacts/'.$id.'">
<Status>Do Not Mail</Status>
<EmailAddress>'.$email.'</EmailAddress>
<Confirmed>false</Confirmed>
<InsertTime>2010-01-28T10:20:23.857Z</InsertTime>
<LastUpdateTime>2010-01-28T11:33:03.035Z</LastUpdateTime>
</Contact>
</content>
</entry>';


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, $entry, 'delete'); 

var_dump($code);

if ($code > 199 && $code < 300)
    { $output =  "Remove Contact from any subscription" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;

}


 /**
  * Convert an xml to array form
  * @param string $xml contains the xml.
  * @return array

  */

function xml2array($xml) {
        $xmlary = array();
                
        $reels = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*)<\/\s*\\1\s*>)/s';
        $reattrs = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/';

        preg_match_all($reels, $xml, $elements);

        foreach ($elements[1] as $ie => $xx) {
                $xmlary[$ie]["name"] = $elements[1][$ie];
                
                if ($attributes = trim($elements[2][$ie])) {
                        preg_match_all($reattrs, $attributes, $att);
                        foreach ($att[1] as $ia => $xx)
                                $xmlary[$ie]["attributes"][$att[1][$ia]] = $att[2][$ia];
                }

                $cdend = strpos($elements[3][$ie], "<");
                if ($cdend > 0) {
                        $xmlary[$ie]["text"] = substr($elements[3][$ie], 0, $cdend - 1);
                }

                if (preg_match($reels, $elements[3][$ie]))
                        $xmlary[$ie]["elements"] = $this->xml2array($elements[3][$ie]);
                else if ($elements[3][$ie]) {
                        $xmlary[$ie]["text"] = $elements[3][$ie];
                }
        }

        return $xmlary;
}

 


}

main_controller.php – Sample Usage of the component

<?php
class MainController extends AppController {

	var $name = 'Main';
	var $helpers = array('Html', 'Form');
	var $components = array('ConstantContact');

	function index(){

	$this->ConstantContact=& new ConstantContactComponent(null);

	$this->ConstantContact->api_key = 'API KEY YOU GOT'; 
	$this->ConstantContact->api_user = 'YOUR USERNAME';
	$this->ConstantContact->api_pass = 'AND PASSWORD'; 


	
	//Create Contact

	$detail = array(
	'first_name'=>'Heinz',
	'last_name'=>'Montenegro',
	'name'=>'Heinz Montenegro',
	'email_address'=>'heinzmontenegro@gmail.com'
        );
	$output = $this->ConstantContact->createContact($detail);
	echo $output;
	
	
	//Obtain Contact Information
	$id = 5;
	$output = $this->ConstantContact->obtainContactInfo($id);
	echo '<pre>'.htmlentities($output).'</pre>';
	

	//Update Contact Information
	$id = 5;
	$detail = array(
	'first_name'=>'Tomas',
	'last_name'=>'Gatchalian',
	'name'=>'Tomas Gatchalian',
	'email_address'=>'tomasgatchalian@mail.com'
        );
	$output = $this->ConstantContact->updateContactInfo($id, $detail);
	echo $output;
       

	//Search Contact by Email
	$email = 'tomasgatchalian@mail.com';
	$output = $this->ConstantContact->searchContactByEmail($email);
	echo '<pre>'.htmlentities($output).'</pre>';
	

	//Create Contact List

	$detail = array(
	'name'=>'Heinz Club',
	'sort_order'=>'80'
        );
	$output = $this->ConstantContact->createContactList($detail);
	echo $output;
	

	//Obtain List of Contacts
	$output = $this->ConstantContact->obtainListContact();
	echo '<pre>'.htmlentities($output).'</pre>';


	//Obtain Contact List Information
	$id = 5;
	$output = $this->ConstantContact->obtainContactListInfo($id);
	echo '<pre>'.htmlentities($output).'</pre>';


	//Update Contact List Information
	$id = 5;
	$detail = array(
	'name'=>'Tomas Club',
	'sort_order'=>'80'
        );
	$output = $this->ConstantContact->updateContactListInfo($id, $detail);
	echo $output;
	
	
	//Add Contact to Contact Lists
	$id = 6;
	$contact = array('4','5');
	$output = $this->ConstantContact->addContactToContactList($id, $detail, $contact);
	echo $output;
	

	//Bulk Adding of Contacts to a Contact List
	$detail = array (
	'heinzmontenegro@gmail.com'=> array(
	'first_name'=>'Heinz',
	'last_name'=>'Montenegro'
	), 
	'tomasgatchalian@mail.com'=>array(
	'first_name'=>'Tomas',
	'last_name'=>'Gatchalian'
	)
	);
	$contact = 3;
	$output = $this->ConstantContact->addMultipleContactToContactList($detail, $contact);
	echo $output;
	

	//OptInSubscriber
	$id = 5;
	$email = 'tomasgatchalian@mail.com';
	$contact = array('1','5','3','4');
	$output = $this->ConstantContact->OptInSubscriber($id, $email, $contact);
	echo $output;
	

	//Opt out a Subscriber
	$id = 6;
	$output = $this->ConstantContact->OptOutSubscriber($id);
	echo $output;


	//Remove Contact from any list
	$id = 6;
	$email = 'tomasgatchalian@mail.com';
	$output = $this->ConstantContact->removeContactFromContactList($id, $email);
	echo $output;
		
	}
}
?>

If you have any questions to this post, I’d be glad to know. :)

One thing that is essential in having a calendar for a web application is the capability to have a go to date that will enable a user to go directly and display a specific date. On the FullCalendar plugin, I made use of the gotoDate method. It is not complicated, you just have to create a form that will ask a user to input the desired date to view, and a javascript function that will trigger the gotoDate method.

Note: I advise you to read my previous post ( CakePHP and jQuery FullCalendar plugin (Part I – Retrieve events from database)) first regarding this plugin.

Add this to your index page where the calendar is displayed. (ie. app/views/calendar/index.ctp)


<script type='text/javascript'>


function gotodate(userdate){
  
var dateinput = new Date(userdate); // userdate is what the user has inputted.

$('#calendar')
     	.fullCalendar('changeView', 'basicDay')  // we called the changeView method to display basicDay view.
     	.fullCalendar('gotoDate', dateinput);  // here's where we call the gotoDate method to do the magic.

}

</script>

Hope this helps! If you have any suggestions or corrections feel free to do so :) By the way, you could also check out Part I – Retrieve from database and Part II – Editable feature :)

FullCalendar plugin has an editable feature that makes it possible to update events by dragging and dropping posts anywhere within the calendar. This time, I’ll be sharing on how I’ve utilized this feature, as well as on how to update the events on the database.

Note: I advise you to read my previous post ( CakePHP and jQuery FullCalendar plugin (Part I – Retrieve events from database)) first regarding this plugin.

So let’s begin!

Add this to your index page where the calendar is displayed. (ie. app/views/calendar/index.ctp)


// include this in the FullCalendar script...

editable: true,

eventDrop: function(event) {	// Make sure to read the plugin's documentation :)

var dt = new Date(event.start);   // event.start is the new date where you dragged and dropped the event post.
var yr = dt.getFullYear();
var dy = dt.getDate();
var mth = dt.getMonth()+1;
var hrs = dt.getHours();
var mns = dt.getMinutes();

var newdate = yr+'-'+mth+'-'+dy;  // pass this date to the database via post.

$.post("http://www.yoursite.com/calendar/edit/id:"+event.id+"/date:"+newdate, function(data){});

} 

On your controller (ie. app/controllers/calendar_controller.php), create the edit function.


function edit($id=null){

$this->Event->id = $this->params['named']['id'];
 // By the way I made use of the params to get the values.
$this->Event->saveField('event_date',$this->params['named']['date']);

}

So that’s about it. :) You can also use the eventResize: function(), this feature will let you resize or extend the date duration of an event.

Also check out Part I – Retrieve from database and Part III gotoDate method :)

This week I’ve incorporated the jQuery’s FullCalendar plugin to the project I’m working. It was a bit challenging task but really glad to make it worked. :) I hope to help someone and share what I did to make this task possible.

First, I assume that you have already checked out the FullCalendar demo and downloaded the source code. You’re now in the process of incorporating it to your web application.

So to get things started, you need to include the jQuery script and FullCalendar script plus css in your default layout page. (ie. app/views/layout/default.ctp)

<?php echo $javascript->link('jquery-1.3.2'); ?>
<?php echo $javascript->link('fullcalendar.min'); ?>

// jquery ui purpose for this has something to do with the editing part of the FullCalendar plugin

<?php echo $javascript->link('ui.core'); ?> 
<?php echo $javascript->link('ui.draggable'); ?>
<?php echo $javascript->link('ui.resizable'); ?>

<?php echo $html->css('fullcalendar'); ?> 

On your controller, let’s create the code that will retrieve calendar events from the database. (ie. app/controllers/calendar_controller.php)


function index() {

// get all the events from the database.
$events = $this->Event->find('all');

// insert rows to an array.
for ($a=0; count($events)> $a; $a++){

$rows[]= '{"id":'.$events[$a]['Event']['id'].', "title":"'.events[$a]['Event']['name'].'", "start":"'.$events[$a]['Event']['event_date'].'", "className":"'.$events[$a]['Event']['type'].'","type":"'.$events[$a]['Event']['type'].'"}';

}

// convert the array to a string.
if ($rows){
$convertojson = implode(",", $rows);
}

// pass the string to the json variable. this will then be passed  and printed to the javascript code.
$this->set('json',"[".$convertojson."]"); 

}

On your views add the index page for displaying the calendar. (ie. app/views/calendar/index.ctp )


<script type='text/javascript'>

$(document).ready(function() {
	 
$('#calendar').fullCalendar({
		
	header: {
		left: 'prev,next today',
		center: 'title',
		right: 'month,agendaWeek,agendaDay'
		},
	events: <?php echo $json; ?> // this is where we call the php variable
	
});
)};
</script>

<div id='calendar' style='width: 900px; margin: 0 auto;'></div>

So that’s it! You could also check out Part II – Editable feature and Part III gotoDate method :)

I recently worked on incorporating validation for importing CSV type of file. Since I’m already using the Valid8 (jQuery) plugin, I just made used of it and found a way to validate file extensions.

By the way, before you even go further I suggest you read the documentation of the plugin first. :)

So to get things started, you need to include the jQuery script and Valid8 (jQuery) plugin in your default layout page. (For me it was the default.ctp, ie. app/views/layout/default.ctp)

<?php echo $javascript->link('jquery-1.3.2'); ?>
<?php echo $javascript->link('jquery.valid8-1.2.2'); ?>

Then go to your views page where you need to do the validations. (ie. app/views/posts/import.ctp). Basically what I added was the custom function ( confirmFiletype() ) that will validate if the file extension was true or not, depending on what type of file you need to restrict. For me, what I need was to make sure that the type of file is CSV format.

 
<script>

$('#submit').click(function(){
if ( $('#PostFile').isValid() != true){
 $('#PostFile').focus();
return false;
}
});


$('#PostFile').valid8({	regularExpressions: [
		{expression: /^.+$/, errormessage: 'Inserting a file is required'}
		],
		jsFunctions:[
		{ 'function': confirmFiletype, 'values': function(){
			return {filetype: $('#PostFile').val()}
		}}
		]
});

      
function confirmFiletype(args){
var str=args.filetype;
if(str.lastIndexOf(".csv")==-1) // I made used of the lastIndexof and check if the file was with the extension csv on it.
return {valid:false, message:'File must be in csv format.'}
else
return {valid:true}
}

</script>

<?php 

echo $form->create('Lead', array('enctype' => 'multipart/form-data', 'action' => 'import') ); 

echo $form->file('Lead.File');

echo $form->end('Import');

?>

So that’s it. Hope this helps :)

CakePHP and jQuery

With the project I’m working on right now, I needed to make the details page clickable and edit in place (no need to display another page with a form). The first thing that popped in my mind was the jQuery’s jEditable plugin. I haven’t used it before, and it was the first time I incorporated it to a web application. I was glad that I applied it successfully and it worked smoothly.

So to get things started, you need to include the jQuery script and jEditable plugin in your default layout page. (For me it was the default.ctp ie. app/views/layout/default.ctp)

<?php echo $javascript->link('jquery-1.3.2'); ?>
<?php echo $javascript->link('jquery.jeditable'); ?>

Also add this script on your layout page.

<script>
$(function() {
    $('.edit').editable("http://www.yoursite.com/item/edit", {
         id        : 'data[Module][id]',
         name   : 'data[Module][value]',
         type      : 'text',
         indicator : '<img src="/img/loading.gif">',
         cancel    : 'Cancel',
         submit    : 'Save',
         tooltip   : 'Click to edit'
    });
});
</script>

On your items controller, details function… (ie. app/controller/items_controller.php nothing is new here.)

function details($id=null) {

    $this->Item->recursive = 1;
    $cond = array('Item.id' => $id);
    $this->set('items', $this->paginate('Item', $cond));

}

On your views folder, details page…(ie. app/views/items/details.ctp ) Add a span with the attributes class and id. Make sure that the class name is exactly the same with what you have in the editable js function above. The id should be the item’s ID (note that field name was prefix on the id, for the reason that, it makes the editable function above reusable for any fields on this page.)

<?php 
foreach ($items as $item):
?>
<table >
<tbody>
<tr>
<td >Item Description</td>
<td ><span class="edit" id="description_<?php echo $item['Item']['id']; ?>"><?php echo $item['Item']['description']; ?> </span></td>
</tr>...

On your Items controller page again, edit function… (ie. app/controller/items_controller.php)


function edit($id=null) {

       if ($this->data) {

       uses('sanitize');
       $sanitize= new Sanitize();
       $value = $sanitize->clean($this->data['Module']['value']);
	
       $temp = explode("_",$this->data['Module']['id']);
			
       //this if conditions makes it sure that the field name and id will be split up correctly.
	
       if(count($temp) == '2'){  // ie. itemdescription_1   
		
		// splits field from id
		list($field, $id) = split('_', $this->data['Module']['id']);
	
        }
	if (count($temp) == '3') { // ie. item_description_1		
			
                 $id = $temp[2];
			
			for ($a=0; count($temp)-1>$a; $a++ ){
				$arrtemp[] = $temp[$a];
			}
			$field = implode("_",$arrtemp);
			
	}
	if (count($temp) == '4') { // ie. item_description_category_1 			
			$id = $temp[3];
			
			for ($a=0; count($temp)-1>$a; $a++ ){
				$arrtemp[] = $temp[$a];
			}
			$field = implode("_",$arrtemp);
	}
		
	$this->Item->id = $id;
	$this->Item->saveField($field, $value);
	$this->set('value', $value);
         }
}

on your views, edit.ctp add this… (ie. app/views/items/edit.ctp)

<?php echo $value; ?>

Hope this helps! :)

disclaimer: i’m not a php guru, just a mid level one. Feel free to post comments and suggestions :)

Follow

Get every new post delivered to your Inbox.