I got this error in my error log
PHP Warning: Invalid argument supplied for foreach()
foreach ( $fields as $field ) {
if ( $field['name'] == $fieldname ) {
$characteristics = $field;
}
}
Does anyone know how to fix this?
Thanks
one problem is if your variable is empty and inside a foreach loop the warning appears
Try this
if (is_array($fields) || is_object($fields)) {
foreach ($fields as $field) {
if ($field['name'] == $fieldname) {
$characteristics = $field;
}
}
}
Related
I am using goutte sracper to scrape the data , i m getting error like InvalidArgumentException - The current node list is empty. Below is the code which i m using
$string = $crawler->filter('div#links.results')->html();
if ( empty( $string ) )
return false;
$dom = new \DOMDocument;
$state = libxml_use_internal_errors(true);
$dom->loadHTML($string);
libxml_use_internal_errors($state);
$xp = new \DOMXPath($dom);
$divNodeList = $xp->query('//div[contains(#class, "results_links_deep")]
[contains(#class, "web-result")]
/div[contains(#class, "links_main")]
[contains(#class, "links_deep")]
[contains(#class, "result__body")]');
$results = [];
if(count($divNodeList) > 0){
foreach ($divNodeList as $divNode) {
$results[] = [
trim($xp->evaluate('string(./h2/a[#class="result__a"])', $divNode)),
trim($xp->evaluate('string(.//a[#class="result__snippet"])', $divNode)),
trim($xp->evaluate('string(.//a[#class="result__url"])', $divNode))
];
}
}
I tried using the solution as below
if ($crawler->filter('div#links.results')->count() > 0 ) {
$string = $crawler->filter('div#links.results')->html()
}
then it started giving another error like DOMDocument::loadHTML(): Empty string supplied as input
Any suggestions please ?
Your filterdid not return any results. That is why it crashed. That's how I solved this issue, by adding a try catch.
try {
$string = $crawler->filter('div#links.results')->html()
} catch (\InvalidArgumentException $e) {
// Handle the current node list is empty..
}
I have a situation where I am trying to clone a node field after importing content via feeds. I am doing this because of a challenge I have with feeds_tamper_string_2Id module. I have tried the following code but it didn't work
function members_entity_presave($entity, $type)
{
if($entity->type == 'members') {
foreach ($entity->field_tags2['und'] as $tags) {
array_push($entity->field_tags_people['und'], $tags);
}
}
}
I want to copy the values of field_tags2['und'] into field_tag_people['und'].
If your field is a taxonomy reference you can try this :
function MYMODULENAME_entity_presave($entity, $type)
{
if($entity->type == 'members') {
$items = field_get_items($type, $entity, 'field_tags2');
if(is_array($items)) {
foreach ($items as $tags) {
$entity->field_tags_people[LANGUAGE_NONE][]['tid'] = $tags['tid'];
}
}
}
}
EDIT
You can use entity_metadata_wrapper : https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers
I have:
if (count($data['paymentTypes'])<5) {
$arr = array();
foreach (array_values($data['paymentTypes']) as $value) { $arr[]=$value->getId(); }
$query = $query->leftJoin('p.payments','g')->where('g.id IN(:num)')->setParameter('num', $arr);
}
if (count($data['expertise']->toArray())>0) {
$arr = array();
foreach (array_values($data['expertise']->toArray()) as $value) { $arr[]=$value->getId(); }
$query = $query->leftJoin('p.expertise','g')->where('g.id IN(:num)')->setParameter('num', $arr);
}
How may I stop the query from breaking in case both statements are true? I would expect leftjoins and wheres to congregate but they throw an exception instead. What is the cleanest way of accomplishing this?
Use different alias and parameter name in the second part than in the first.
I have the following class:
class Foo
{
public function importBars(array $array)
{
foreach ($array as $key => $value) {
$this->importBar($key, $value);
}
}
public function importBar($key, $value)
{
// do stuff
}
}
I need to test that importBar is called count($array) times, and that it's called with the right parameters. Using $this->at() is not an option, as the order of the $array elements might change. I have:
public function testImportBars(array $array)
{
// Mock invocation ...
$logicalOrs = array();
foreach ($array as $sku => $value) {
$logicalOrs[] = $this->logicalOr($this->equalTo($key), $this->equalTo($value));
}
$mock->expects($this->exactly(count($array)))
->method('importBar')
->with(call_user_func_array(array($this, 'logicalOr'), $logicalOrs));
}
Which passes the tests. However, when I deliberately make it fail:
foreach ($array as $sku => $value) {
$logicalOrs[] = $this->logicalOr($this->equalTo($key), $this->equalTo(null));
}
... it still passes. It only fails if the $key is incorrect:
foreach ($array as $sku => $value) {
$logicalOrs[] = $this->logicalOr($this->equalTo(null), $this->equalTo(null));
}
... which suggests PHPUnit is only checking if the first parameter passed to Foo::importBar() is correct.
Is there a way to tell PHPUnit to verify arguments to methods when there is more than one?
After some trial and error, here is the closest solution I've come up with:
$rows = array();
foreach ($array as $key => $value) {
$rows[] = array($key, $value);
}
$method = $mock->expects($this->exactly(count($array)))
->method('importBar');
call_user_func_array(array($method, 'withConsecutive'), $rows);
See: http://phpunit.de/manual/4.1/en/test-doubles.html#test-doubles.mock-objects
So in my base template, I have: {% render "EcsCrmBundle:Module:checkClock" %}
Then I created the ModuleController.php...
<?php
namespace Ecs\CrmBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Ecs\CrmBundle\Entity\TimeClock;
class ModuleController extends Controller
{
public function checkClockAction() {
$em = $this->getDoctrine()->getEntityManager();
$user = $this->get('security.context')->getToken()->getUser();
$today = time();
$start = date('Y-m-d 00:00:00');
$entities = $em->getRepository('EcsCrmBundle:TimeClock');
$query = $entities->createQueryBuilder('tc')
->select('tc.in1, tc.out1, tc.in2, tc.out2, tc.in3, tc.out3')
->where('tc.noteBy = :user')
->andWhere('tc.daydate >= :start')
->setParameter('user', $user->getid())
->setParameter('start', $start)
->setMaxResults('1')
->getQuery();
$entities = $query->getSingleResult();
if (empty($entities)) {
$ents = "clocked_out";
$this->get('session')->set('clockedin', 'clocked_out');
} else {
for ($i=1; $i <= 3; $i++) {
if ($entities["in$i"] != NULL) {
$ents = "clocked_in";
if ($i == 1) {
$this->get('session')->set('nextclock', "out$i");
} else {
$x = $i+1;
$this->get('session')->set('nextClock', "out$x");
}
if ($entities["out$i"] != NULL) {
$ents = "clocked_out";
$x = $i+1;
$this->get('session')->set('nextclock', "in$x");
}
if ($entities["out3"] != NULL) {
$ents = "day_done";
}
}
}
}
return $this->render('EcsCrmBundle:Module:topclock.html.twig', array(
'cstat' => $ents,
));
}
}
The problem is, if there is nothing in the database for the specific day for the specific user yet.. i keep getting:
An exception has been thrown during the rendering of a template ("No result was found for query although at least one row was expected.") in ::base.html.twig at line 161.
500 Internal Server Error - Twig_Error_Runtime
1 linked Exception: NoResultException ยป
I know it has something to do with the fact that is no 'result' from the database... but isn't that what i've accomplished by having the if (empty($entities)) { ?? I have no clue to fix it... any help appreciated...
Replace:
$entities = $query->getSingleResult();
With
$entity = $query->getOneOrNullResult();
If you look in Doctrine\ORM\AbstractQuery you will see that getSingleResult expects one and only one results. 0 will through an exception.
I looked at your code a bit more closely and it looks like you actually expect an array of entities. in which case use:
$entities = $query->getResult();