node_load_multiple() can it go through the array? - arrays

I'm trying to do this to get the "floor" value of my node :
$type = "desk";
$floor = '2';
$nodes = node_load_multiple(array(), array('field_floor["und"][0]["value"]' => $floor, 'type' => $type));
I can get all my desk if I'm just doing $nodes = node_load_multiple(array(), array('type' => $type)); and I can find a deck with for exemple the title, but is it possible to go through the arrays to get the 'value' and check it in the query ?
Thank you for your answers.

To get value of a field you have multiple methods :
Field get item:
$nid = 2;
$node = node_load($nid);
$floor = field_get_items($node , 'node', 'field_floor');
$floor = reset($floor); // or loop on it, here take first value if multiple
echo $floor['value'];
https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field_get_items/7.x
Entity metadata wrapper:
$nid = 2;
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$floor = $wrapper->field_floor->value();
echo $floor;
https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers
Direct way :
global $language; // take current language
$nid = 2;
$node = node_load($nid);
echo $node->field_floor[$language->language][0]['value'];

Related

create node wuth Term reference tag

I'am trying to add node programmatically with term reference Auto complete term widget (tagging) and add new tag my code not work
when I remove tag reference from code ,my node add successfully
I need add new tag each node
<?php
$bodytext = "body?";
$node = new stdClass(); // Create a new node object
$node->type = "programstvradio"; // Or page, or whatever content type you like
node_object_prepare($node); // Set some default values
// If you update an existing node instead of creating a new one,
// comment out the three lines above and uncomment the following:
// $node = node_load($nid); // ...where $nid is the node id
$node->title = "title";
$node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
$node->uid = 1; // UID of the author of the node; or use $node->name
$node->body[$node->language][0]['value'] = $bodytext;
$node->body[$node->language][0]['format'] = 'filtered_html';
// I prefer using pathauto, which would override the below path
$path = 'node_created_on' . date('YmdHis');
$node->path = array('alias' => $path);
$node->field_tag_[$node->language][]['value'] ='tagggggggg';
$node->field_catprogram[$node->language][]['tid'] =12;
$file_path = drupal_realpath('C:\Users\Admin\Desktop\drupal.png'); // Create a File object'); // Create a File object
$file = (object) array(
'uid' => 1,
'uri' => $file_path,
'filemime' => file_get_mimetype($file_path),
'status' => 1,
);
$file = file_copy($file, 'public://images'); // Save the file to the root of the files directory. You can specify a subdirectory, for example, 'public://images'
$node->field_image[LANGUAGE_NONE][0] = (array)$file; //associate the file object with the image field:
if($node = node_submit($node)) { // Prepare node for saving
node_save($node);
echo "Node with nid " . $node->nid . " saved!\n";
}
?>``
i find solution
$my_term_name = 'gggg';
$term_array = taxonomy_get_term_by_name($my_term_name);
if($term_array == array()){
//empty term ..
$term->name = $my_term_name;
$term->vid = 1;
taxonomy_term_save($term);
$term_array = taxonomy_get_term_by_name($my_term_name);
}
//get the first index of the array .
foreach ($term_array as $tid => $term_object)break;
$node->field_progna['und'][$tid] = (array)$term_object;

How do you filter Joomla 3 articles by article id

I'm trying to create a Joomla module that displays articles based on categories and tags.
I've taken code for selecting tagged articles from https://github.com/lasinducharith/joomla-tags-selected) and introduced it into a copy of mod_articles_news:
public static function getList(&$params)
{
$app = JFactory::getApplication();
$db = JFactory::getDbo();
// Code base on https://github.com/lasinducharith/joomla-tags-selected to fetch ids of tagged articles
$tagsHelper = new JHelperTags;
$tagIds = $params->get('tagid', array());
$tagIds = implode(',', $tagIds);
echo '<pre>search for tags[' . $tagIds . ']';
$query=$tagsHelper->getTagItemsQuery($tagIds, $typesr = null, $includeChildren = false, $orderByOption = 'c.core_title', $orderDir = 'ASC',$anyOrAll = true, $languageFilter = 'all', $stateFilter = '0,1');
$db->setQuery($query, 0, $maximum);
$results = $db->loadObjectList();
$article_ids=array();
foreach ($results as $result){
$article_ids[]=$result->content_item_id;
}
echo ' yields articles[' . implode(',', $article_ids ) . ']</pre>';
// Get an instance of the generic articles model
$model = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$appParams = JFactory::getApplication()->getParams();
$model->setState('params', $appParams);
// Set the filters based on the module params
$model->setState('list.start', 0);
$model->setState('list.limit', (int) $params->get('count', 15));
$model->setState('filter.published', 1);
$model->setState('list.select', 'a.fulltext, a.id, a.title, a.alias, a.introtext, a.state, a.catid, a.created, a.created_by, a.created_by_alias,' .
' a.modified, a.modified_by, a.publish_up, a.publish_down, a.images, a.urls, a.attribs, a.metadata, a.metakey, a.metadesc, a.access,' .
' a.hits, a.featured' );
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$model->setState('filter.access', $access);
// Category filter
$model->setState('filter.category_id', $params->get('catid', array()));
// Article filter
$model->setState('filter.id', $article_ids);
// Filter by language
$model->setState('filter.language', $app->getLanguageFilter());
// Set ordering
$ordering = $params->get('ordering', 'a.publish_up');
$model->setState('list.ordering', $ordering);
if (trim($ordering) == 'rand()')
{
$model->setState('list.direction', '');
}
else
{
$direction = $params->get('direction', 1) ? 'DESC' : 'ASC';
$model->setState('list.direction', $direction);
}
// Retrieve Content
$items = $model->getItems();
$newitems=array();
foreach ($items as &$item)
{
echo '<pre>fetched article[' . $item->id .'] which is ';
if ( !in_array($item->id, $article_ids )){
echo 'not tagged';
} else{
echo 'tagged';
}
echo '</pre>';
...
}
return $newitems;
}
The debug statements give me:
search for tags[2] yields articles[40,44,45]
fetched article[45] which is tagged
fetched article[44] which is tagged
fetched article[43] which is not tagged
fetched article[42] which is not tagged
fetched article[41] which is not tagged
fetched article[40] which is tagged
fetched article[39] which is not tagged
fetched article[38] which is not tagged
So the articles have not been filtered by id. I'd be very grateful for any advice.
Thanks
Found the problem, the filter should be article_id:
// Article filter
$model->setState('filter.article_id', $article_ids);
Now it selects articles based on tags and categories

Symfony2: Querying for object with 2 other objects as parameters

What is the best way to do the following: I have a gameobject entity which has properties game and user. Now my method gets the game id and the user id and i want to look for the gameobject with game = object of game id and user = object of user id.
I have tried the following:
$game = $this->getDoctrine()->getRepository("xxx:Game")->find($game_id);
$user = $this->getDoctrine()->getRepository("xxx:User")->find($user_id);
$gameobject_query = $em->getRepository('xxx:Gameobject')->createQueryBuilder('g')
->where('g.game = :game AND g.user = :user')
->setParameters(array(
'game' => $game,
'user' => $user
))
->getQuery();
$gameobject = $gameobject_query->getResult();
Your advices would be appriciated :)
I think that something like the following should work:
$repository = this->getDoctrine()->getRepository('xxx:GameObject');
$queryBuilder = $repository->createQueryBuilder('go')
->innerJoin('go.game', 'g')
->innerJoin('go.user', 'u')
->where('g.id = :gameId')
->andWhere('u.id = :userId')
->setParameter('gameId', $gameId)
->setParameter('userId', $userId);
$gameObjects = $queryBuilder->getQuery()
->execute();
Alternatively, the following may also work and be more efficient: It should do the same but without needing to join to the other entities:
$repository = this->getDoctrine()->getRepository('xxx:GameObject');
$queryBuilder = $repository->createQueryBuilder('go')
->where('IDENTIY(go.game) = :gameId')
->andWhere('IDENTITY(go.user) = :userId')
->setParameter('gameId', $gameId)
->setParameter('userId', $userId);
$gameObjects = $queryBuilder->getQuery()
->execute();
Why didn't you use the findOneBy method of your Gameobject repo ?
$game = $this->getDoctrine()->getRepository("xxx:Game")->find($game_id);
$user = $this->getDoctrine()->getRepository("xxx:User")->find($user_id);
$gameobject = $em->getRepository('xxx:Gameobject')->findOneBy(array(
'game' => $game,
'user' => $user
));

Drupal 7 db_query

The perfect little module for what I am looking to do was made for drupal 6 but to my dismay it doesn't work on drupal 7. I've have learned that drupal 7 has a new api for the database. I have tried to get it to work but I am admittedly out of my league here. I am hoping some one could give me a little guidance. Specifically with the db_query.
function webform_image_validation_webform_validation_validate($validator_name, $items,
$components, $rule) {
$errors = array();
if ($items) {
switch ($validator_name) {
case 'max_image_size':
$dimensions = explode('x', $rule['data']);
foreach ($items as $key => $val) {
if (is_numeric($val['_fid'])) {
$result = db_query("select * from {files} where fid = %d", $val['_fid']);
while ($data = db_fetch_object($result)) {
$thefile = $data;
}
$image_info = image_get_info($thefile->filepath);
if (webform_image_validation_validate_image($image_info, $dimensions[0], $dimensions[1], FALSE) === FALSE) {
$errors[$key] = t('Your image did not match the required width and/or height. (') . $dimensions[0] . t(' x ') . $dimensions[1] . t(')');
}
}
}
This is the error I receive.
Argument 2 passed to db_query() must be an array, string given, called in
/home/designco/public_html/dev/sites/all/modules/webform_image_validation/
webform_image_validation.module on line 69 and defined in
/home/designco/public_html/dev/includes/database/database.inc on line 2310
It appears I need to add an array but I get lost there. Any help would be appreciated. I'm just trying to find out if I'm the right track.
db_query works differently in Drupal7.
$result = db_query("select * from {files} where fid = %d", $val['_fid']);
while ($data = db_fetch_object($result)) {
$thefile = $data;
}
becomes
$results = db_query("select * from {files} where fid = :fid", array(':fid' => $val['_fid']));
foreach($results as $result) {
// Do your thing for each result.
}
Try changing
$result = db_query("select * from {files} where fid = %d", $val['_fid']);
while ($data = db_fetch_object($result)) {
$thefile = $data;
}
to
$query = db_select('files', 'f')
->fields('f')
->condition('fid', $val['_fid']);
$thefile = $query->execute()->fetchObject();
The Drupal 7 database API docs http://drupal.org/node/310069
thanks JurgenR for the answer.
Just to add one more thing: In drupal 6, we use '%s' for strings. In drupal 7, it is same for all.
For example:
$results = db_query("select * from {files}
where filename = :fname", array(':fname' => $filename));
If you want to search for records starting with a pattern then query will be:
$results = db_query("select * from {files}
where filename = :fname", array(':fname' => $filename.'%'));
Hope this is useful.

Using read() in cakephp to retrieve row with array of data

I want to know if it is possible to retrieve a row from the database using something similar to the following:
if (!empty($this->params['form'])) {
$place = array();
$place['city'] = $this->params['form']['city'];
$place['area'] = $this->params['form']['state'];
$place['country'] = $this->params['form']['country'];
$place['iso'] = $this->params['form']['iso'];
$this->Place->set($place);
$place_found = $this->Place->read();
}
Is there some way I can preset the data in the Place model using the array and then use Place read. I'm looking for something simple like the usual:
$this->Place->id = 7;
$place_found = $this->Place->Read();
I have also tried doing this:
$this->Place->city = blah;
$this->Place->area = foo; etc....
$place_found = $this->Place->read();
However, that also does not work.
Haven't you ever used find()?! read() only fetches a row with the ID passed.
$place_found = $this->Place->find('first', array(
'conditions' => array(
'Place.city' => $city,
'Place.area' => $area
// etc
)
));
If you need to build the conditions manually you can create a conditions array to pass like so:
$placeConditions = array();
$placeConditions['city'] = $city;
if($area) {
$placeConditions['area'] = $area;
}
$places = $this->Place->find('first', array('conditions' => $placeConditions));
I suggest you read the page I linked, you will soon find out there is never a reason to use the read() method.
In model you could do:
$this->id = 3; //place id
$this->Place->read();
Hope it helps
I think this approach is what you're looking for(with your code):
if (!empty($this->params['form'])) {
$place = array();
$place['city'] = $this->params['form']['city'];
$place['area'] = $this->params['form']['state'];
$place['country'] = $this->params['form']['country'];
$place['iso'] = $this->params['form']['iso'];
//$this->Place->set($place); //don't need it here I think
$place_found = $this->Place->find('all',array('conditions'=>$place));
}
You'll have to use "find()", not "read()", but - it's almost as simple as your example code and should work. (also, there's a shortcut for the array_push() I believe, but - I like to use this for readability - personal preference):
if (!empty($this->params['form'])) {
$conditions = array();
array_push($conditions, array('Place.city' => $this->params['form']['city']);
array_push($conditions, array('Place.state' => $this->params['form']['state']);
array_push($conditions, array('Place.country' => $this->params['form']['country']);
array_push($conditions, array('Place.iso' => $this->params['form']['iso']);
$this->Place->set($place);
$place_found = $this->Place->find('all', array('conditions'=>$conditions));
}

Resources