Chaining jQuery.each() - method-chaining

I'm trying to add results from an object to newly created HTML elements:
*long chain of newly created elements*.append(
$("<div />").append(
$.each(myObj.results, function( intIndex, objValue ){
return objValue.description;
})
)
);
If I use a function() call with a for-loop instead of each() it works, but is there no way to achieve this with each()?

.each just iterates through a collection, you need an anonymous function to return something, so try this:
$("<div />").append(function(){
var string = "":
$.each(myObj.results, function( intIndex, objValue ){
string += objValue.description;
})
return string;
});

.each is meant for iterating over the list and perform operation, You can achieve what you want with $.map Which build an array from returned elements in each iteration.
*long chain of newly created elements*.append(
$("<div />").append(function(){
var des = $.map(myObj.results, function( objValue ){
return objValue.description;
});
return des.join(' ');
});
);

Related

Custom End points API to get all themes from word-press returning False value

Here is the custom end points What i have created here for getting all themes. But in json it’s not returning result as expected.
add_action( ‘rest_api_init’, function () {
//Path to rest endpoint
register_rest_route( ‘theme/v1’, ‘/get_theme_list/’, array(
‘methods’ => ‘GET’,
‘callback’ => ‘theme_list_function’
) );
});
// Our function to get the themes
function theme_list_function(){
// Get a list of themes
$list = wp_get_themes();
// Return the value
return $list;
}
?>
If I can see simply the wp_get_themes() function it will return all the themes and its description in arrays. and It’s return fine in arrays but when i am encoding this into json to pass data its returning only array keys.
Producing only key name like in this way
All: {"basepress":{"update":false},"codilight-lite":{"update":false},"twentyfifteen":{"update":false},"twentyseventeen":{"update":false},"twentysixteen-child":{"update":false},"twentysixteen":{"update":false}}
I need all the information about the themes.
How can i do that with custom REST end points.
Please help.
Try this code
add_action( 'rest_api_init', function () {
//Path to rest endpoint
register_rest_route( 'theme/v1', '/get_theme_list/', array('methods' => 'GET','callback' => 'theme_list_function') );
});
// Our function to get the themes
function theme_list_function(){
// Get a list of themes
$list = wp_get_themes();
$varTheme = array();
foreach($list as $theme=>$value){
$varTheme[$theme] = (array)$value;
}
return $varTheme;
}

How can I get the format the results of a CheckboxsetField as a comma separated string in SilverStripe?

I'm trying to create some filters for a datalist. I'd like the user to be able to select one or multiple filters from a list of tags and then spit out a list of objects based on those filters. All is good using this code to grab data based on the URL params being sent...
public function index(SS_HTTPRequest $request)
{
// ...
if($tagsParam = $request->getVar('tags')) {
$articles = new ArrayList();
$tagids = explode(",", $tagsParam);
foreach($tagids AS $tagid) {
$tag = Category::get()->byID($tagid);
$articleitems = $tag->getManyManyComponents('Articles')->sort('Date DESC');
foreach($articleitems AS $articleitem) {
$articles->push($articleitem);
}
}
}
$data = array (
'Articles' => $articles
);
if($request->isAjax()) {
return $this->customise($data)->renderWith('ListItems');
}
return $data;
}
That code works fine with a URL like mysite.com/?tags=1,2,3
My issue comes with trying to generate that URL based on the filters built with a CheckboxSetField. Here is my code for that...
public function ArticlesSearchForm()
{
$tagsmap = $this->getTags()->map('ID', 'Title')->toArray();
$form = Form::create(
$this,
'ArticlesSearchForm',
FieldList::create(
CheckboxSetField::create('tags')
->setSource($tagsmap)
),
FieldList::create(
FormAction::create('doArticlesSearch','Search')
)
);
$form->setFormMethod('GET')
->setFormAction($this->Link())
->disableSecurityToken()
->loadDataFrom($this->request->getVars());
return $form;
}
When the user submits that form, the URL generated is something along the lines of mysite.com?tags%5B1%5D=1&tags%5B2%5D=2&action_doArticlesSearch=Search Obviously, it's passing the values as an array. How can I pass a simple comma separated list?
Rather than trying to change the return of CheckboxSetField, I'd recommend changing your code. Given you are converting the comma-separated list list into an array already here:
$tagids = explode(",", $tagsParam);
Something like this, will skip this step:
public function index(SS_HTTPRequest $request)
{
// ...
if($tagsParam = $request->getVar('tags')) {
$articles = new ArrayList();
//This has a minor risk of going bad if $tagsParam is neither an
//array of a comma-separated list
$tagids = is_array($tags) ? $tagsParam : explode(",", $tagsParam);

Assert that given arguments are passed to a method regardless of call order

In testing method A, method B is called multiple times. I want to assert that at least one of those calls uses specific arguments, but I don't care when that call is made.
How can I construct a PHPUnit test to assert this?
I've searched Google and StackOverflow for the solution with no luck, and the docs aren't proving to be much help, either.
I've tried using this helper function:
protected function expectAtLeastOnce( $Mock, $method, $args = array() ) {
$ExpectantMock = $Mock->expects( $this->atLeastOnce() )->method( $method );
$this->addWithArgsExpectation( $args, $ExpectantMock );
}
This, however, doesn't work because it expects every call to use the specified arguments, even though it would accept any number of calls above none.
Similar questions:
Test that method is called with same parameters, among others - recommends using ->at() which requires knowledge of invocation order, so not a solution
PHPUnit stubs - make expected calls independent of the order of invocation - unanswered; comments recommend using a testing framework, which I'm not interested in doing
EDIT: Here's my implementation of the accepted answer:
protected function assertMethodCallsMethodWithArgsAtAnyTime(
$InquisitiveMock,
$inquisitiveMethod,
$InitiatingObject,
$initiatingMethod,
$expectedArgs = array()
) {
$success = false;
$argsChecker = function () use ( &$success, $expectedArgs ) {
$actualArgs = func_get_args();
if (
count( $expectedArgs ) === count( $actualArgs )
&& $expectedArgs === $actualArgs
) {
$success = true;
}
};
$InquisitiveMock->expects( $this->any() )
->method( $inquisitiveMethod )
->will( $this->returnCallback( $argsChecker ) );
$InitiatingObject->$initiatingMethod();
$this->assertTrue( $success );
}
Maybe not very elegant, but you can check the method arguments manually by using a callback and set a flag when the right arguments were found:
$mock = $this->getMock('Class', array('theMethod'));
$call_done = false;
$params_checker = function() use (&$call_done) {
$args = func_get_args();
if (1 == count($args) && "A" == $args[0]) {
$call_done = true;
}
};
$mock->expects($this->any())
->method('theMethod')
->will($this->returnCallback($params_checker));
$mock->theMethod("A");
$this->assertTrue($call_done);

wordpress: change wp_title with variable from another function

i would change the page title from a wordpress plugin site. the name comes from a function:
function subPage() {
$content = 'blabla';
$subPageTitle = 'Plugin Sub Page Dynamic';
return $content;
}
and the simple function for replace wp_title:
function wp_plugin_page_title($subPageTitle) {
$siteTitle = $subPageTitle;
return $siteTitle;
}
add_filter('wp_title', wp_plugin_page_title);
my problem is now: how i get the variable $subPageTitle in the function wp_plugin_page_title()?
Thanks a lot for ANY help!
EDIT: the code was not correct.
function subPage() {
$subPage = new stdClass();
$subPage->content = 'blabla';
$subPage->subPageTitle = 'Plugin Sub Page Dynamic';
return $subPage;
}
function wp_plugin_page_title($subPageTitle) {
$siteTitle = $subPageTitle . " " . subPage()->subPageTitle;
return $siteTitle;
}
add_filter('wp_title', wp_plugin_page_title);
Then you get the value by calling subPage()
echo subPage()->subPageTitle;
If you print_r the subpage you will see:
stdClass Object ( [content] => blabla [subPageTitle] => Plugin Sub Page Dynamic )
Any values that are inside a function, they are encapsulated values if you need to reach them outside that function or you return them in an array or in an object.

Getting print_r from a Drupal variable

I have a Drupal variable, $view. I need to print out all of its values. I have tried:
dsm($view);
var_dump($view);
function hook_form_alter() {
$form['print'] = array('#value' => '<pre>'.print_r($view, 1).'</pre>');
}
All of these functions produce an output of Null, however. How can I get the value of the variable?
This is probably happening because the $view variable isn't within scope in the function hook_form_alter().
Use:
$view = views_get_current_view();
Then you can access, for example, the arguments of the view:
$arg0 = $view->args[0];
function MYMODULE_form_alter(&$form, &$form_state, &$form_id){
switch($form_id){
case 'MY_FORM':
$display_id = 'block_1';
$view = views_get_view('my_view_machine_name');
$view->set_display($display_id)
$view->set_items_per_page(0); // or other
$view->execute();
$result = $view->preview();
// Also you can use $view->result to get result as array
$form['print'] = $result;
break;
}
}

Resources