CakePHP 2.0: How can i work with own functions - sorting

I work with CakePHP 2.0. I made a new function sort and had no problem, if I take the table fields. But if I want to calculate something and give the result (method: 'Participant.year'=>'calculateyear' ) in my sort method, I have no result on my view.
function sort() {
$participants = $this->Participant->find('all', array(
'conditions'=>array('Participant.sex'=>'m','Participant.year'=>'calculateyear'),
'order'=>array('Participant.communitieRank'=>'ASC','Communitie.name'=>'ASC')
));
$this->set('participants', $participants);
}
function calculateyear ($jahr) {
$jahr = '2000';
return $jahr;
}

assuming you are in your PartecipantsController I guess what you want to do is:
function sort() {
$participants = $this->Participant->find('all', array(
'conditions'=>array(
'Participant.sex'=>'m',
'Participant.year'=> $this->calculateyear(2000)
),
'order'=>array('Participant.communitieRank'=>'ASC','Communitie.name'=>'ASC')
));
$this->set('participants', $participants);
}
but your question is not clear at all

thats my solution, it works :)
function calculateyear ($year) {
$today = date("Y");
$year = $today - $year;
return $year;
}
function kat1w() {
$participants = $this->Participant->find('all', array(
'conditions'=>array('Participant.sex'=>'f',
'Participant.year >='=>$this->calculateyear(9)),
'order'=>array('Participant.communitieRank'=>'ASC','Communitie.name'=>'ASC')
));
$this->set('participants', $participants,$this->Paginator->paginate());
}

Related

how to insert the data using codeiginter?

I am new to codeiginter,how to insert the data into table using codeiginter
my controller code;
$data = array(
'subgrpname' => $this->input->post('subgrpname'),
'grpname'=> $this->input->post('grpname'),
'pltype'=> $this->input->post('pltype')
);
It is simple form use internet to search it
$data = array(
'subgrpname' => $this->input->post('subgrpname'),
'grpname'=> $this->input->post('grpname'),
'pltype'=> $this->input->post('pltype')
);
$this->db->insert('tablename',$data);
I would like to share reusable code approach by following the MVC coding style
My Controller
$table = 'table_name';
$data = array(
'subgrpname' => $this->input->post('subgrpname'),
'grpname'=> $this->input->post('grpname'),
'pltype'=> $this->input->post('pltype')
);
$record_id = $this->Common_Model->insert_into_table($table, $data);
My Common_Model
function insert_into_table($table, $data) {
// echo "<pre>";print_r($data);exit;
$insert = $this->db->insert($table, $data);
$insert_id = $this->db->insert_id();
if ($insert) {
return $insert_id;
} else {
return false;
}
}
You can use this model function as much time as you want.

How to properly update a array that has only one identifying id

I'm trying to update an array with objects inside something like this, with the current code I have it only saves the first one, I know that's the problem but I don't know how to fix it
array (
0 =>
array (
'option' => 'new',
),
1 =>
array (
'option' => 'ewrwer',
),
),
This is my current code, the line in question is
$option = SurveyQuestionOption::where('survey_question_id', $preg->id)->first();
How do I fix this so it cycles through all in the array questionOptions instead of just the first one? I tried ->get() but then the ->save() doesn't work.
public function update(Request $request, $id)
{
DB::beginTransaction();
$preg = SurveyQuestion::findOrFail($id);
$preg->question = $request->question;
$preg->survey_section_id = $request->survey_section_id;
$preg->response_type_id = $request->response_type_id;
$preg->optional = $request->optional;
$preg->save();
$ids = [];
if ($request->get('questionOptions')) {
foreach ($request->get('questionOptions') as $item) {
$option = SurveyQuestionOption::where('survey_question_id', $preg->id)->first();
if (empty($option)) {
$option = new SurveyQuestionOption();
$option->survey_question_id = $preg->id;
}
$option->option = $item['option'];
$option->save();
}
}
if (count($ids) > 0) {
SurveyQuestionOption::whereNotIn('id', $ids)->where('survey_question_id', $preg->id)->delete();
}
DB::commit();
return back();
}
Basically, when you use get, you get a collection, so you can't really use save on it. you need to do a foreach loop, and save in that. i.e; like this;
$options = SurveyQuestionOption::where('survey_question_id', $preg->id)->get();
foreach($options as $option){
if (empty($option)) {
$option = new SurveyQuestionOption();
$option->survey_question_id = $preg->id;
}
$option->option = $item['option'];
$option->save();
}
Note that you can't save $options if you don't use a foreach loop, as you're not specifying which instance of the collection to save it in.

Codeigniter multiple parameter on update

I am copying this code in Codeigniter official docs, but I don't know why this will throw an error
public function acceptChangeRequest($id,$data1,$accept) {
$data = array(
'status' => $accept,
'approve_by' => $data1,
);
$this->db->where('id', $id);
$this->db->update('change_request',$data);
//return true;
}
Error Number: 1054
Unknown column 'Array' in 'field list'
UPDATE change_request SET status = 'Y', approve_by = Array WHERE id = '22'
It sounds wierd since this code works in my other function. Any idea?
Read The Documentation Clearly
Read About Update Records In Codeigniter
Here IS Demo Function For You
public function updateBasic($data,$user_id){
$userData=array(
'marital_status'=>$data['marital_status'],
'country'=>$data['stateofresidence'],
'city'=>$data['city'],
'caste'=>$data['caste'],
'residential_status'=>$data['residencystatus']
);
$this->db->WHERE('user_id',$user_id)->update('basic_profile',$userData);
return true;
}
You Must Check Through Print_r();what Is coming To your Function In Your Case $data1 Is Coming In the From OF array You Must Extract The Array To Update The Record
Use this function in your model to update the record.
public function acceptChangeRequest($where, $table, $data){
$this->db->where($where);
$this->db->update($table, $data);
return $this->db->affected_rows() > 0;
}
use this code in your controller.
$where = array('id'=>$id);
$data = array(
'status' => $accept,
'approve_by' => $data1,
);
$this->User_model->update($where,'table_name',$data);
What is in your $data1 variable? I can see that it's an array, and that is the problem.
If your $data1 stores indexes like in your table's row, than this is the possible solution for you:
public function acceptChangeRequest($id,$data1,$accept) {
$data1["status"] = $accept;
$this->db->where('id', $id);
$this->db->update('change_request', $data1);
return true;
}
But if your $data1 variable stores only the approve_by information, than your possible solution is:
public function acceptChangeRequest($id,$data1,$accept) {
$data = array(
'status' => $accept,
'approve_by' => $data1["approve_by"]
);
$this->db->where('id', $id);
$this->db->update('change_request', $data);
return true;
}
First of all, you need to know what you expect from $data1, than you can move forward to the solution.
You can see your $data1 variable in your Controller's function:
print "<pre>";
print_r($data1);
print "<pre>";
die();

how to sort before printing in yii

so I found this:
How to print directly from printer with Yii?
and the 2nd answer (the one with the jquery) was the one I felt was most suitable for me
but I just want to know, is there a way I can sort these out before printing? like for example In the model
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id,true);
$criteria->compare('name',$this->name,true);
$criteria->compare('date',$this->date,true);
$criteria->compare('department_id',$this->department_id);
$criteria->compare('section_id',$this->section_id);
$criteria->compare('team_id',$this->team_id);
$criteria->compare('created_date',$this->created_date,true);
$criteria->compare('updated_date',$this->updated_date,true);
$data = new CActiveDataProvider(get_class($this), array(
'criteria'=>$criteria,
'pagination'=>false,
));
$_SESSION['all'] = $data;
$data = new CActiveDataProvider(get_class($this), array(
'pagination'=>array('pageSize'=> Yii::app()->user->getState('pageSize',
Yii::app()->params['defaultPageSize']),),
'criteria'=>$criteria,
));
$_SESSION['limited'] = $data;
return $data;
}
is it possible to display this ordered by the name maybe or the date instead of just the id?
$data = new CActiveDataProvider(get_class($this), array(
'sort'=>array(
'defaultOrder'=>'name ASC',
)
));

Incorrect Signature in facebook stream_publish call

I am having a facebook error on stream_publish call. I actually used an extension for Magento for Fconnect. Fconnect & Flogin is working fine. But it is requirement that when user place an order it should be posted on user's wall. For that I have implemented like this
document.observe('click', function(e){
if (e.element().match('a[rel^=facebook-connect]') || e.element().match('button[rel^=facebook-connect]')) {
e.stop();
FB.login(function(response){
if(response.status=='connected') setLocation('http://staging.mystore.com/facebook/customer_account/connect/');
}, {perms:"email,publish_stream"});
}
});
in Facebook Client file generateSignature method is like this
private function _generateSig($params_array)
{
Mage::log($params_array);
$str = '';
ksort($params_array);
foreach ($params_array as $k=>$v) {
$str .= "$k=$v";
}
$str .= $this->_secret;
Mage::log($str);
Mage::log('md5 sigs:: ' . md5($str));
return md5($str);
}
& My code that is calling the API is like this
$message = 'just placed an order on mystore.com';
$attachment = array(
'name' => "mystore",
'href' => 'http://www.mystore.com/',
'description' => 'New order on mystore.com',
'media' => array(array('type' => 'image',
'src' => 'http://www.mystore.com/skin/frontend/default/mystore/images/logo.png',
'href' => 'http://www.mystore.com/')));
$action_links = array( array('text' => 'Buy#mystore', 'href' => 'http://www.mystore.com/'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
try{
// if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id))
if($this->_getClient()->call( 'facebook.stream.publish',
array($message, $attachment, $action_links,
$this->_getClient()->users->getLoggedInUser(),
Mage::getSingleton('facebook/config')->getApiKey() )
) )
{
Mage::log( "Added on FB Wall" );
}
} catch(Exception $e)
{
Mage::log( "Exception in wall write" );
Mage::log($e);
}
After logging the Signature I found in log is
api_key=XXXXXXXXmethod=facebook.stream.publishsession_key=2.AQCm5fABfobInAS5.3600.1309352400.1-1000025660978090=just placed an order on mystore.comcall_id=1309345883.3068format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
I have never done any development on Facebook SO I have no Idea what to do? Please help me with solution. & let me know if u guys need any other info to understand this.
Oh yeah One more thing the Client File code that is calling Api (call method) its like this
private function _prepareParams($method, $params)
{
$defaultParams = array(
'api_key' => $this->_apiKey,
'call_id' => microtime(true),
'format' => 'JSON',
'v' => '1.0'
);
if($this->_sessionKey){
$defaultParams['session_key'] = $this->_sessionKey;
}
$params = array_merge($defaultParams, $params);
foreach ($params as $key => &$val) {
if (!is_array($val)) continue;
$val = Zend_Json::encode($val);
}
$params['method'] = $method;
if(isset($params['sig'])) {
unset($params['sig']);
}
$params['sig'] = $this->_generateSig($params);
return $params;
}
public function call($method, $args=array())
{
Mage::log($args);
$params = $this->_prepareParams($method, $args);
$client = self::_getHttpClient()
->setUri(self::FACEBOOK_REST_URI)
->setMethod(Zend_Http_Client::POST)
->resetParameters()
->setParameterPost($params);
try {
$response = $client->request();
} catch(Exception $e) {
throw new Mage_Core_Exception('Service unavaliable');
}
if(!$response->isSuccessful()) {
throw new Mage_Core_Exception('Service unavaliable');
}
$result = Zend_Json::decode($response->getBody());
//json decode returns float on long uid number? is_json check? old php?
if(is_float($result)){
$result = $response->getBody();
}
if(is_array($result) && isset($result['error_code'])) {
throw new Mage_Core_Exception($result['error_msg'], $result['error_code']);
}
return $result;
}
For calling API I used two ways $this->_getClient()->call( 'facebook.stream.publish',
& $this->_getClient()->call( 'stream_publish',
None of them are working
ok GUys I figure out the mistake
look at my code
format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
where u can see format=JSONv=1.01={....}2=[{.....}] the problem was I used numeric arrays for parameters. they should be associated arrays
like message={new order}attachment={....}
Once I fixed the associative array problem my code start working correctly
here is a link that'll give u detail about parameters to pass to stream.publish
http://schoolout.net/en/developers/view/39
Hope this will help somebody else too.

Resources