How to use node_load()? - html

Hi m a bit confused that how to retrieve node title by using this code
node_load($nid);
$title=$nid->title;
i have done this coding in block and i wants to retrieve from node id for displaying image.that images are normally uploaded at the site by using filezilla and it has same name as the node title.i have tried many forms of node_load(),but i m failure.so please tell me right option for this.
Thanks all.-Pranoti

Here is the reference for node_load
http://api.drupal.org/api/function/node_load
It returns an object which is the node.
$node = node_load($nid); // $nid contains the node id
$title = $node->title;
Please get a good book on Drupal Module development to learn the fundamentals.

Your question is a little confusing. Could you clean it up and explain better what you are trying to accomplish? In all events:
Node load takes either an numeric argument or an array of parameters to query, and returns a single node object. (As already mentioned, here's the API documentation: http://api.drupal.org/api/function/node_load).
Load with a numeric node id:
$nid = 55;
$node = node_load($nid);
$title = $node->title;
Load by querying on title:
$title = 'How to serve man';
$node = node_load(array('title' => $title));
$body = $node->body;

you can also load multiple node load efficiently by using the following code
<?php
$type = "product_type";
$nodes = node_load_multiple(array(), array('type' => $type));
foreach($nodes as $products):
?>
<?php print $products->nid; ?>
<?php print $products->title; ?>
<?php endforeach; ?>
also you can query any thing in the node load for example we have used type in query but we can also use title as mentioned in the above post by
"David Eads"
NODE LOAD BEST PRACTICES

If you are loading a lot of nodes with node_load(), make sure to use the $reset parameter so that every node isn't kept in the function's static cache (and increasing memory usage):
$nid = 55;
$node = node_load($nid, NULL, TRUE);

Related

Cannot load default values in input fields using FormHelper in cakephp 3.x

I'm facing a very wierd situation concerning a quite simple task.
I'm trying to create a very simple edit form in my application using
cakephp 3.x version.
In my ContentsController::edit($contentID) method I'm loading the content entity to be edited like this
$content = $this->Contents->findById($contentID)->first()
and then I'm simply creating the respective view variable using set() method like that:
$this->set('content', $content);
In the view file - named edit.ctp - all I'm doing is to simply create
a new form using FormHelper using the following piece of code:
<h2><?= __('Edit content: ') . $content->title; ?></h2>
<?php
echo $this->Form->create($content);
echo $this->Form->input('title', ['type' => 'text']);
echo $this->Form->input('alias', ['type' => 'text']);
echo $this->Form->input('body', ['type' => 'textarea']);
echo $this->Form->submit();
?>
The following code creates the form correctly but it does not load the default values in each input element from the $content entity. After doing some digging into the source code of the FormHelper I found out that when the FormHelper::create() method is called, it correctly loads the EntityContext interface using the $content entity. But for some reason, which I cannot explain, in each of the FormHelper::input() calls, internally the context interface is switching to NullContext so no data is loaded into the field.
Does anyone have an idea what am I doing wrong with that piece of code?
After some more digging I found the real cause of the issue.
FormHelper works correctly and so does my query.
The issue has to do with the view file and how it is rendered.
The whole picture is this.
My view (edit.ctp) was an extension of a common skeleton I created, namely edit_frm.ctp. So in my view file I was extending by calling $this->extend('/Common/edit_frm');
The structure of the edit_frm.ctp consists of three blocks, as shown below (I removed the html markup)
<?php
// Common/edit_frm.ctp
$this->fetch('formStart');
$this->fetch('formPrimaryOptions');
$this->fetch('formSecondaryOptions');
$this->fetch('formEnd');
?>
Now in my view file (edit.ctp) I was creating the blocks like that:
<?php
// Contents/edit.ctp
$this->extend('Common/edit_frm');
// The "formStart" block contains the opening of the form
$this->start('formStart');
echo $this->Form->create($content);
$this->end('formStart');
// The "formEnd" block contains the submit button and the form closing tag
$this->start('formEnd');
echo $this->Form->submit();
echo $this->Form->end();
$this->end('formEnd');
// "formPrimaryOptions" contains the main input fields
$this->start('formPrimaryOptions');
echo $this->Form->input('title', ['type' => 'text']);
echo $this->Form->input('alias', ['type' => 'text']);
echo $this->Form->input('body', ['type' => 'textarea']);
$this->end('formPrimaryOptions');
?>
As you see in my view file, I was building the formEnd block before the construction of the formPrimaryOptions block. Though in my skeleton the blocks are fetched in a different order.
Apparently in CakePHP when you extend a view combined with blocks of content in the actual view file you must create your blocks in the same order as they are fetched, otherwise you end up in weird situations like the one I was facing.
In any case, I had a very good lesson today!!
Maybe you can do this instead of findById:
$content = $this->Contents->find('all')->where(['id' => $contentID])->first();

Laravel Select Query within helper file

I'm coming from codeigniter background. Unlike codeigniter helper directory, i just created helper directory within app directory of Laravel. Just want to know how to execute query within this common function. Here is my codeigniter function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$output = "";
$ci =& get_instance();
$ci->db->select("*");
$ci->db->where('is_active', "Y");
$ci->db->where('is_delete', "N");
$ci->db->where('parent_id', $parent_id);
($sort_order!="")?$ci->db->order_by($sort_order, "ASC"):"";
$query = $ci->db->get('tbl_cms_menus');
foreach ($query->result() as $row){
$output .= '<option value="'.$row->$primary_key_col.'">'.$indent.$row->menu_name.'</option>';
}
return $output;
}
I tried something like this in laravel file. but this code did't give me any result. Please tell me where i'm doing wrong in this code. thanks
function databaseTable()
{
$table = DB::table('tbl_cms_menus');
$get_rows = $table->get();
$count_rows = $table->count();
if($count_rows > 0){
foreach ($get_rows as $tbl)
{
echo $tbl->menu_name;
}
}
}
This code will rot so hard that it shipped pre-rotten.
But, if you want to just.. ram it into the app all dry like that.. then add something like this to your base controller class...
$whatever = crazyChainingStuff;
foreach ($whatever ...) { $topMenu .= ... }
View::share('topMenu', $topMenu);
If you want to learn how to write code that will do less damage to your company and your clients then I recommend starting by watching Uncle Bob's "Fundamentals" videos. At least the first 5-6. http://cleancoders.com
It looks like you are trying to generate a drop-down/select with some data from your database, in this case, you should pass the data required for the drop-down/select from your controller to the view where you have written your HTML, for example, in your view, you may have a select like this:
echo Form::select('cms_menu', $cms_menu, Input::old('cms_menu'));
Or this (If you are using Blade):
{{ Form::select('cms_menu', $cms_menu, Input::old('cms_menu')) }}
From your controller you should pass the $cms_menu which should contain the menu-items as an arrtay and to populate that array you may try something like this:
$menuItems = DB::table('tbl_cms_menus')->lists('menu_name','id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
Also, you may use something like this:
// Assumed you have a Page model
$menuItems = Page::lists('menu_name', 'id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
You may also read this article which is about building a menu from database using view composer (More Laravelish way). Read more about Form::select on documentation.
It was too late to give an answer. I was also from CodeIgniter background and when I learnt Laravel then first I try to find how can I write a query in Helper. My Team leader helped me.
I have converted your code in a helper function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$query = DB::table('tbl_cms_menus')
->select('*')
->where('is_active', '=', 'Y')
->where('is_delete', '=', 'N')
->where('parent_id', '=', $parent_id);
($sort_order != "")? $query->orderBy($sort_order, "ASC") : "";
$resultData = $query->get()->toArray();
}
Here $resultData will be array format. Now, you can create a foreach loop according to your requirement.

How to retrive Custom Post Type Meta Fields in Custom WP_Query

Can some one let me know How I can render the Custom Post Type Meta Fields (Meta-boxes).
I have a Custom Post Type Called "News" and I successfully added a metabox to my Custom Post Type called "News Info" which is suppose to store : A TextField = News Resource A Select option = News Type A check box
I can retrieve the Custom post Type "News"content using a custom Loop as:
<?php
$args = array( 'post_type' => 'news');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo '<div class="content">';
the_content();
echo '</div>';
endwhile;
?>
But I have no idea how to get the associated meta fields to "news" posts? trust me I Google this a lot but couldn't find any solution all of them just tried to render the Metabox on the admin page but no sample for presenting on the page!
Can you please let me know how I can get access and render the data on the page using the wp-query loop?
Thanks
To build upon SidGBF's answer, you can use get_post_meta(get_the_ID(),'YOUR_FIELD_NAME',true);
That is a little verbose if you're going to use it again and again, so it might be helpful to add this to your functions.php file:
function get_custom_field($field_name){
return get_post_meta(get_the_ID(),$field_name,true);
}
Then you can just use get_custom_field('YOUR_FIELD_NAME').
If you'd like to print the value of the field, use echo get_custom_field('YOUR_FIELD_NAME')
Your solution may be found in http://codex.wordpress.org/Function_Reference/get_post_meta . To get the post's ID you may use get_the_ID().

Soundcloud API doesn't explicitly support pagination with json

Specific example I was working with:
http://api.soundcloud.com/users/dubstep/tracks.json?client_id=YOUR_CLIENT_ID
You'll get their first 50 tracks, but there is not next-href object like what you see in the xml version.
However, you can use offset and limit and it works as expected- but then I would need to "blindly" crawl through tracks until there are no more tracks, unlike with the XML version which gives you the "next page" of results. I wouldn't have even noticed it was paginated except by chance when I was searching the json object and noticed there was exactly 50 tracks (which is suspiciously even).
Is there a plan to support the next-href tag in json? Am I missing something? is it a bug that it's missing?
There is an undocumented parameter you can use linked_partitioning=1, that will add next_href to the response.
http://api.soundcloud.com/users/dubstep/tracks.json?client_id=YOUR_CLIENT_ID&linked_partitioning=1
for ex :
// build our API URL
$clientid = "Your API Client ID"; // Your API Client ID
$userid = "/ IDuser"; // ID of the user you are fetching the information for
// Grab the contents of the URL
//more php get
$number="1483";
$offset=1300;
$limit=200;
$soundcloud_url = "http://api.soundcloud.com/users/{$userid}/tracks.json?client_id={$clientid}&offset={$offset}&limit={$limit}";
$tracks_json = file_get_contents($soundcloud_url);
$tracks = json_decode($tracks_json);
foreach ($tracks as $track) {
echo "<pre>";
echo $track->title . ":";
echo $track->permalink_url . "";
echo "</pre>";
}
sI've seen this code is supposed to help (this is in Ruby):
# start paging through results, 100 at a time
tracks = client.get('/tracks', :order => 'created_at', :limit => page_size,
:linked_partitioning => 1)
tracks.each { |t| puts t.title }
However, the first set of results will show and i'll even see the "next_href" at the end of the response, but what are you supposed to do, to make the next set of results show?

how to get an empty Json object with Zend_json?

From http://json.org/:
an empty Json object is:
{}
I've tried to get it with json_encode (which is officially part of PHP):
json_encode((object)(array()))
that's what I need. But somehow I have to use Zend_json to get it:
Zend_Json::encode((object)(array()))
but the result is:
{"__className": "stdClass"}
Any ideas?
My PHP version 5.1.6; ZF version 1.7.2
For me this works perfectly:
echo '<pre>'; print_r(Zend_Json::encode((object)array())); echo '</pre>'; exit;
// Output: {}
Tested with ZF-Version 1.11.3
Also possible:
Zend_Json::encode(new stdClass());
Try
Zend_Json::encode(array());
Just in case anybody is still wondering, the internal encoder of the ZF adds the __className property to each object.
The internal encoder is used if the PECL extension json is not installed and thus the function json_encode not available (see http://php.net/manual/en/function.json-encode.php ).
Just use
preg_replace('/"__className":"[^"]+",/', '', $jsonString);
to get rid of all className elements
I find the solution as below:
$m = Zend_Json::encode($obj);
$res = str_replace('"__className":"stdClass"', '', $m);
$res = str_replace("'__className':'stdClass'", '', $res);
$res = str_replace("'__className': 'stdClass'", '', $res);
$res = str_replace('"__className": "stdClass"', '', $res);
return $res;
To get around this in Zf2 I have added a disableClassNameDecoding option to Zend\Json\Encoder.
If you want to disable the __className output, you can use it like this:
return Zend\Json\Json::encode($object, false, array('disableClassNameDecoding' => true));
The patched file can be found on github. At some point I will add unit tests and create a pull request.