yii ajaxLink is not passing variable to controller - php

I am trying to pass a variable from an ajaxLink into my controller but my controller is not getting the variable.
//view
$ids = Yii::app()->storedData->getIds();
foreach($ids as $id) {
echo 'ID '.$id .'<br />';
echo CHtml::ajaxLink(
'remove',
array('/storedInfo/remove'),
array(
'data' => array('removeItem' => $id),
));
}
//controller
public function actionRemove() {
var_dump($_GET['removeItem']); // RETURNS string(0) ""
die();
}

The ajax array you're passing to CHtml::ajaxLink ends up taking the whole array and passing it to CJavaScript::encode().
As you mentioned in your comments, the $id you were using to build your data array was a PHP object. When this got to CJavaScript::encode, things got wonky, and the results weren't what you were expecting. Extracting a string or numeric value from $id, rather that passing the whole object should take care of this, e.g.:
'data' => array('removeItem' => $id->value) // obviously you'll need to use the proper key to get the value
Or maybe something like this depending on the data structure:
'data' => array('removeItem' => settype($id, 'string'),

I edited out my answer because i admit it was not what the original asker wanted but for the sake of the comments, i leave my code here
$ids = Yii::app()->storedData->getIds();
foreach($ids as $id) {
echo 'ID '.$id .'<br />';
echo CHtml::ajaxLink(
'remove',
array('/storedInfo/remove', array('removeItem' => $id)),
);
}

Looks like CHtml::ajaxLink takes more parameters than you're sending.
public static string ajaxLink(string $text, mixed $url, array $ajaxOptions=array ( ), array $htmlOptions=array ( ))
Do you need to send along some $text before the $url?

Related

Remove array element with YiiMongoDbSuite

I have some code that should be deleting a record from an embedded MongoDB document.
Here is the code:
public function actionDeleteSaved()
{
$savedLink = $_POST['savedLink'];
$userId = Yii::app()->user->getId();
$current = SaveLink::model()->findByPk($userId);
if(in_array($savedLink, $current->links))
{
array_slice($current->links, $savedLink);
$current->save();
}
}
This is what is passing the data to the controllers action method:
echo CHtml::ajaxButton(
'delete',
Yii::app()->createUrl("dashboard/index/deletesaved"),
array( // ajax options
'type' => 'POST',
'context' => "js:this",
'data' => array(
'savedLink' => $savedLink
)
),
array( //html options
'class'=>'deleteSaved'
)
);
This is what renderPartial looks like:
$this->renderPartial('_deleteSaved', array('savedLink'=>$s));
What I want being posted is being posted correctly but I'm not sure if it's communicating with the Controller and passing the data through or if my code for removing the data from the database is correct.
Any help would be greatly appreciated, thanks.
The problem is with array_slice part. As specified in php docs array slice does not modify array parameter.
Use array_splice instead (it modifies passed array param) and array_search to get key:
if(in_array($savedLink, $current->links))
{
$key = array_search($savedLink, $current->links);
array_splice($current->links, $key, 0);
$current->save();
}
NOTE: If $current->links is embedded documents (objects) array, you might have to find $key and check if is in array some other way.

Extracting array as list of arguments passed to function

Is it possible to make something like that:
$array = array('id' => '5', 'something_else' => 'hi');
function some_function($id, $something_else)
{
echo $something_else;
}
some_function(extract($array));
This code is giving me true/false and not $id,$something_else, etc..
It is important for me to do something like that, because I have different list of variables for each function ( I'm working on my ( let's call it ) "framework" and I want to pass list of variables instead of array with variables. This code is actually going in my router so it's not quite that simple, but in the end it comes to that ).
I assume you know how your array is built. So, why do not you just pass an array as a parameter and then use it in your function ?
If you do something like this you can access to your array's values :
echo $array['something_else'];
And build your function like this :
$array = array('id' => '5', 'something_else' => 'hi');
function some_function($an_array)
{
echo $an_array['something_else']; // value for something_else
}
some_function($array);
Or if you don't want to change function's parameters, call it like this :
some_function($array['id'], $array['something_else']);

How to return this Multidimensional PHP Array as a JSON object?

I have this code in my model when the controller requests to get all the messages for a certain user:
public function get_messages($user_id) {
$sql = "SELECT *
FROM messages
WHERE `to` = '$user_id'
ORDER BY id DESC";
$query = $this->db->query($sql);
foreach($query->result() as $row) {
$messages[] = array(
'id' => $row->id,
'to' => $row->to,
'from' => $row->from,
'message' => $row->message,
'star' => $row->star,
'timestamp' => $row->timestamp
);
}
return $messages;
}
Here's the code in my controller:
$result = $this->inbox_m->get_messages($user['id']);
How can I return the result as a JSON object using PHP's json_encode() function?
Normally I do something like this for simple returns:
json_encode(array('result' => true))
but all these arrays in arrays got me confused.
EDIT
Never mind guys, should have actually tried it before posting. This works just fine:
echo json_encode(array('result' => $result));
I will close the question in a day when my account allows me.
json_encode($messages); should be fine here. Call it and examine the output to see if it's what you want. But json_encode should handle nested arrays without breaking a sweat.
Closing the question by answering it myself. Like explained in the edit this works just fine:
echo json_encode(array('result' => $result));

CakePHP question: What's the difference between these two routing?

This is one =>
echo $this->Html->link('Edit',
array('controller'=>'comments','action'=>'edit',$comment['Comment']['id']));
This is another one in form =>
echo $this->Form->create('Comment',
array('url'=>array('controller' => 'comments', 'action' =>'add', $listposts['Post']['id']) )
);
echo $this->Form->input('post_id',array('type'=>'hidden','style'=>'width:30%','value'=>$listposts['Post']['id']));
echo $this->Form->input('name',array('style'=>'width:30%'));
echo $this->Form->input('email',array('style'=>'width:30%'));
echo $this->Form->input('body',array('rows'=>'5'));
echo $this->Form->end('Submit');
Is it possible to do echo $this->Form->create like the previous one ? Why do i need 'url'=>array(..) why not like this =>
echo $this->Form->create('Comment',array('controller' => 'comments', 'action' =>'add', $listposts['Post']['id']));
The reason for that is tthat the url-array is an argument in the link()-function of the HTML-helper. If you take a look at the declaration:
link(string $title, mixed $url = null, array $options = array(),
string $confirmMessage = false)
So you pass the url as second argument without the $url name as you would do with other methods.
Howerver, the declaration of the create()-method in the Form-helper is:
create(string $model = null, array $options = array())
Notice that there is just one $options-array. So your url here is a member of an array rather then a member of an argument list. In associative arrays you can't simply leave the keys so using the url-array without explicitly naming the key should not work.
For more information see the Docs for this methods:
HTML->link()
Form->create()

Passing additional parameters to the Zend partialLoop View Helper

In a Zend view I can apply a partial template to an iterable element as follows:
$this->partialLoop('template.phtml', $iterable);
However inside the template, only the elements of the $iterable are available, is there another way of passing extra data to the partial?
I use
$this->partialLoop('template.phtml', array(
'data' => $iterable,
'otherVariable' => $otherVariable
);
Warning & Edit:
To be completly honest, I made a mistake. I guess that the code I proposed won't work. I mistaken it for the partial() helper. It won't work because of this part of the helper's class:
foreach ($model as $item) {
// increment the counter variable
$this->partialCounter++;
$content .= $this->partial($name, $module, $item);
}
It will iterate over the whole array instead of the "data" key. I don't get how the answer could be accepted :D Thanks to Nikolaus Dulgeridis for pointing that out.
You can't even post any extra data through $this->view because the point of partial is that it creates "clean" view instance - so that the assigned variables won't collide with your existing variables.
Possible options
- Extend the view helper with methods to set custom variables
- Iterate the array and reformat it to
array(
array('data' => $item1, 'id' => 1, 'totalCount' => 10) ,
array('data' => $item2, 'id' => 2, 'totalCount' => 10) ,
array('data' => $item3, 'id' => 3, 'totalCount' => 10) ,
)
- Use Registry to store the values.
Zend_Registry::set('partialLoopCount', $count);
$this->partialLoop($viewScript, $data);
- Dump partialLoop and use partial() instead
I prefer this solution.
$count = count($data);
foreach ($data as $key => $value) {
echo $this->partial($viewScript, array('item' => $value, 'position' => $key, 'count' => $count));
}
Inside the partial, you can access all of your view variables with:
$this->partialLoop()->view->myVariable
where myVariable is a normal view variable ($this->view->myVariable in the controller or
$this->myVariable in the view, which it's actually the same thing).
Basically, you retrieve the PartialLoop() object, then the view which called it, and then the variable itself.
This, though, will probably impact performance (and I don't think it's really MVC friendly...)
But, hey: it works. :)
An example here:
Hardcode.nl == Joris Osterhaus
Later I found (insert in partial):
$this->getHelper('PartialLoop')->view->otherVariable;
You can access parent view variables by this way :
$this->ViewModel()->getCurrent()->getVariable('parentVariable');
Found at http://blog.dossantos.com.au/how-to-access-parent-view-variables-from-a-partial-loop-in-zf2
In controller
$this->view->otherVariable = 'otherVariable';
In "partial file" - template.phtml
$this->otherVariable
(ZendFramework-1.11.4-minimal)

Categories