Drupal - get the field of view - drupal-7

Hello!
I am trying to get the fields of views
There is a code:
$variables = module_invoke('views', 'block_view', 'news-block');
print render($variables['content']);
to display unit software.
Whether it is possible to obtain the field at such a conclusion. Rather get views across the fields from variable $variables
Advance all grateful
Sorry for my English.

You can use views_get_view_result function:
$view = views_get_view_result($name, $display_id); // returns an array conatining the result of the view
print_r($view);
If you prefer to get whole node objects, you can use node_load function with nids of each row:
$view = views_get_view_result($name, $display_id); // returns an array conatining the result of the view
$nodes = array(); // create an empty array to push each node objects
foreach ($view as $row) {
$node = node_load($row->nid); // get the node object by nid
$nodes[] = $node; // push node to $nodes array
}
print_r($nodes);
Also see: https://drupal.stackexchange.com/questions/32825/get-a-views-result-using-php-code-and-iterate-the-proper-way

Related

Indirect modification of overloaded element of Illuminate\Support\Collection has no effect

im quite new in laravel framework, and im from codeigniter.
I would like to add new key and value from database
static function m_get_promotion_banner(){
$query = DB::table("promotion_banner")
->select('promotion_banner_id','promotion_link','about_promotion')
->where('promotion_active','1')
->get();
if($query != null){
foreach ($query as $key => $row){
$query[$key]['promotion_image'] = URL::to('home/image/banner/'.$row['promotion_banner_id']);
}
}
return $query;
}
that code was just changed from codeigniter to laravel, since in codeigniter there are no problem in passing a new key and value in foreach statement
but when i tried it in laravel i got this following error :
Indirect modification of overloaded element of Illuminate\Support\Collection has no effect
at HandleExceptions->handleError(8, 'Indirect modification of overloaded element of Illuminate\Support\Collection has no effect', 'C:\xampp\htdocs\laravel-site\application\app\models\main\Main_home_m.php', 653, array('query' => object(Collection), 'row' => array('promotion_banner_id' => 1, 'promotion_link' => 'http://localhost/deal/home/voucher', 'about_promotion' => ''), 'key' => 0))
please guide me how to fix this
thank you (:
The result of a Laravel query will always be a Collection. To add a property to all the objects in this collection, you can use the map function.
$query = $query->map(function ($object) {
// Add the new property
$object->promotion_image = URL::to('home/image/banner/' . $object->promotion_banner_id);
// Return the new object
return $object;
});
Also, you can get and set the properties using actual object properties and not array keys. This makes the code much more readable in my opinion.
For others who needs a solution you can use jsonserialize method to modify the collection.
Such as:
$data = $data->jsonserialize();
//do your changes here now.
The problem is the get is returning a collection of stdObject
Instead of adding the new field to the result of your query, modify the model of what you are returning.
So, assuming you have a PromotionBanner.php model file in your app directory, edit it and then add these 2 blocks of code:
protected $appends = array('promotionImage');
here you just added the custom field. Now you tell the model how to fill it:
public function getPromotionImageAttribute() {
return (url('home/image/banner/'.$this->promotion_banner_id));
}
Now, you get your banners through your model:
static function m_get_promotion_banner(){
return \App\PromotionBanner::where('promotion_active','1')->get();
}
Now you can access your promotionImage propierty in your result
P.D:
In the case you are NOT using a model... Well, just create the file app\PromotionImage.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PromotionImage extends Model
{
protected $appends = array('imageAttribute');
protected $table = 'promotion_banner';
public function getPromotionImageAttribute() {
return (url('home/image/banner/'.$this->promotion_banner_id));
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'promotion_banner_id','promotion_link','about_promotion','promotion_active'
];
just improving, in case you need to pass data inside the query
$url = 'home/image/banner/';
$query = $query->map(function ($object) use ($url) {
// Add the new property
$object->promotion_image = URL::to( $url . $object->promotion_banner_id);
// Return the new object
return $object;
});
I've been struggling with this all evening, and I'm still not sure what my problem is.
I've used ->get() to actually execute the query, and I've tried by ->toArray() and ->jsonserialize() on the data and it didn't fix the problem.
In the end, the work-around I found was this:
$task = Tasks::where("user_id", $userId)->first()->toArray();
$task = json_decode(json_encode($task), true);
$task["foo"] = "bar";
Using json_encode and then json_decode on it again freed it up from whatever was keeping me from editing it.
That's a hacky work-around at best, but if anyone else just needs to push past this problem and get on with their work, this might solve the problem for you.

Accessing array values of a field collection in a node with Drupal?

Please bare with a very recent user of Drupal.
I want to create an array out of all examples of the string "url" on a Drupal site.
I've used the method "field_get_items" previously to do something very similar, but I am now trying to access a field collection that is many levels deep into the node's array and I'm not sure that method would work.
$website_urls = array();
$faculty_members = field_get_items('node', $node, 'field_faculty_member');
for ($i = 0; $i < count($faculty_members); $i++) {
$value = field_view_value('node', $node, 'field_faculty_member', $faculty_members[$i]);
$field_collection = $value['entity']['field_collection_item'][key($value['entity']['field_collection_item'])];
$website_urls[] = render($field_collection['field_link']['#items'][0]['url']);
}
An example of one url's location is...
['field_faculty_program'][0]['entity']['field_collection_item'][1842]['field_faculty_member'][0]['entity']['field_collection_item'][1843]['field_link']['#items'][0]['url']
..and another...
['field_faculty_program'][4]['entity']['field_collection_item'][1854]['field_faculty_member'][0]['entity']['field_collection_item'][1855]['field_link']['#items'][0]['url']
What is the method I should be using to collect al of the 'url' strings for placement in an array?
You can actually still use the field_get_items() function but eventually pass it 'field_collection_item' instead for the node type.
Something like this should work:
if ($items = field_get_items('node', $node, 'field_faculty_member')) {
//loop through to get the ids so we can take
//advantage of field_collection_item_load_multiple for
//greater efficiency
$field_collection_item_ids = array();
foreach ($items as $item) {
$field_collection_item_ids[] = $item['value'];
}
if ($field_collection_items = field_collection_item_load_multiple($field_collection_item_ids)) {
foreach ($field_collection_items as $subitem) {
//now we load the items within the field collection
if ($items = field_get_items('field_collection_item', $subitem, 'field_faculty_member')) {
//And you can then repeat to go deeper and deeper
//e.g. a field collection item within a field collection
//for instance to get the urls within your faculty members
//item. Best to break this into functions or a class
//to keep your code readable and not have so many nested
//if statements and for loops
}
}
}
}
Hope that helps!
Scott

Drupal 7: Get all content items attached to all terms in a vocabulary sorted by date

Just like the title says. I have a vocabulary with several terms. I'd like to be able to get all items tagged by each of the terms in the vocabulary sorted by date created in one giant list. Is this possible with the built-in taxonomy API or am I going to have to build something custom?
As far as I know, there is no function/method in Drupal API will get that for you. I believe you will have to make your own.
When you say 'items' if you mean nodes then the function you are looking for is taxonomy_select_nodes().
https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy_select_nodes/7
This function returns an array of node ids that match have the term selected.
/**
* Get an array of node id's that match terms in a given vocab.
*
* #param string $vocab_machine_name
* The vocabulary machine name.
*
* #return array
* An array of node ids.
*/
function _example_get_vocab_nids($vocab_machine_name) {
$vocabulary = taxonomy_vocabulary_machine_name_load($vocab_machine_name);
if (!$vocabulary) {
return array();
}
$terms = taxonomy_get_tree($vocabulary->vid);
if (!$terms) {
return array();
}
$nids = array();
foreach ($terms as $term) {
$term_nids = taxonomy_select_nodes($term->tid, FALSE);
$nids = array_merge($nids, $term_nids);
}
return $nids;
}

access zf2 database result object in controller

How can I loop trough my db results in the controller by using a foreach loop?
$select = new Select();
$select->from('table_name');
$select->where(array('salt' => $salt));
$select->where(array('ip' => $this->_getUserIp()));
$rowset = $this->tableGateway->selectWith($select);
return $rowset;
I guess I need to convert the db result object to an array?
Thanks in advance
http://framework.zend.com/manual/2.1/en/modules/zend.db.result-set.html
Zend\Db\ResultSet\ResultSet extends traversable and therefore you can use foreach on it.
foreach($this->getSomeTable()->fetchAll() as $row) {
//here you can access the row as an array or use getters if you have set a prototype object
//eg
$userId = $row['user_id'];
$userId = $row->user_id;
$userId = $row->getId();
}
Also, I suggest reading through the getting started guide. All this basic stuff is explained there.
http://framework.zend.com/manual/2.1/en/user-guide/overview.html

drupal_write_record doesn't take object

In drupal 6 i used to do something like this:
<?php
/*
* CLASS Example
*/
class example {
var $id = NULL;
var $title;
var $body;
.....
// Save
function save() {
$primary_key = ($this->id == NULL ? NULL : 'id');
if (drupal_write_record('mytabble', $this, $primary_key)) {
return TRUE;
} else {
return FALSE;
}
}
}
?>
This worked quite well. But in Drupal 7, the drupal_write_record only takes an array and no longer the object $this. The new db_merge also only takes an array.
Since i want to save the properties of my object to the database, the above code was very handy and generic for all kinds of classes.
Is there an alternative way to write an object to database, or a method to place objectproperties into a an array?
Any help will be appreciated!
Robert
drupal_write_record does take an object or an array. Guess your problem is caused somewhere else.
drupal_write_record($table, &$record, $primary_keys = array())
$record: An object or array representing the record to write, passed in by reference. If inserting a new record, values not provided in $record will be populated in $record and in the database with the default values from the schema, as well as a single serial (auto-increment) field (if present). If updating an existing record, only provided values are updated in the database, and $record is not modified.
More info on drupal_write_record for D7.

Resources