anderson

php basics? about Repeater print out

Recommended Posts

Hi,

For the purpose of learning, as shown in this photo, I created a repeater field "we", then a template, then a page.

But in /templates/testrepeater.php, I has some problem, the "foreach" part does not work as expected.

<html>
<body>
	<?php echo "<h1>$page->title</h1><br>"; ?>

	<? foreach($page->we as $member); ?>
		<img  src="<?php echo $member->images->url; ?>" alt="">	
		<?php echo $member->wemember; ?><br>
	<? endforeach;?>
</body>
</html>

Could anybody please help point out my error?

Thanks in advance.

repeatertest.jpg

Share this post


Link to post
Share on other sites

From a quick look, I see a typo here:

<? foreach($page->we as $member); ?>

It should be:

<? foreach($page->we as $member): ?>

Notice ":" instead of ";"

  • Like 1

Share this post


Link to post
Share on other sites

You may also need to grab the ->first() image from the images field, or add another nested foreach to loop through all images, eg:

    <?php echo "<h1>$page->title</h1><br>"; ?>

    <? foreach($page->we as $member): ?>
        <? foreach($member->images as $image):
            <img src="<?php echo $images->url; ?>" alt="">    
        <? endforeach;?>    
        <?php echo $member->wemember; ?><br>
    <? endforeach;?>

 

Share this post


Link to post
Share on other sites

I'd recommend using adrians great tracy debugger module. Then you can easily (and instantly) see the content of your variables. It has lots of helpful information so you'll learn a lot quicker and it has the console, where you can try out things quickly and easily. See what you get by a simple dump - using the short syntax d()

Zfv1HnA.png 

  • Like 2

Share this post


Link to post
Share on other sites
<html>
<body>
	<?php echo "<h1>$page->title</h1><br>"; ?>

	<? foreach($page->we as $member): ?>
		<img  src="<?php echo $member->Images->url; ?>" alt="">	
		<?php echo $member->wemember; ?><br>
	<? endforeach;?>
</body>
</html>

 

Share this post


Link to post
Share on other sites

Hi,

1. PHP notice is not error. Your code still valid.

2. Try change the line if displaying image to the following:

<?php echo $member->images->first()->url; ?>

Gideon

Share this post


Link to post
Share on other sites
9 hours ago, Gideon So said:

Hi,

1. PHP notice is not error. Your code still valid.

2. Try change the line if displaying image to the following:

<?php echo $member->images->first()->url; ?>

Gideon

Thanks for your help. 

first() is recognized as unknow function?

To make it clear, with @adrian's code, I removed everything else that's working, only kept:

    <? foreach($page->we as $member): ?>
        <? foreach($member->images as $image):
            <img src="<?php echo $images->url; ?>" alt="">    
        <? endforeach;?>    
    <? endforeach;?>

 and the result output is:

we as $member): ?> images as $image):  

that's always the same problem.

Really don't know what is going on.  

Share this post


Link to post
Share on other sites

another format:

    <? foreach($page->we as $member): ?>
        <? foreach($member->images as $image):
            echo '<img src="' . $images->url . '"  alt="">'    
        <? endforeach;?>    
    <? endforeach;?>

still similar result.

Share this post


Link to post
Share on other sites

Can you show the code from the entire page? 

Is it maybe a PHP short tags issue, or a character encoding issue?

Do you have PW debug mode on?

Does that code work in the Tracy Debugger console panel? Just trying to isolate it.

 

Share this post


Link to post
Share on other sites

Thanks for fast response.

17 minutes ago, adrian said:

code from the entire page? 

my last post IS the entire page of \site\templates\testrepeater.php

I'm new to all this, I didn't create any shortcut of PHP, Wordpress or anything.

 

21 minutes ago, adrian said:

character encoding issue?

Just tried ANSI, Unicode, UTF-8. All the same.

And yes, PW debug is ON. 

Not in the Tracy Debugger console panel.

Share this post


Link to post
Share on other sites

This does not help because tracy and the file editor panel do not work on this host. Also, you should never make any admin login data public, please remove it from your post, even if it is a temporary host.

Did you do (and I mean DO, not READ) the hello world tutorial? https://processwire.com/docs/tutorials/hello-worlds/

PS: I got several 502 bad gateway errors on your install, so you might have server issues that cause several problems...

Share this post


Link to post
Share on other sites

i think it's a problem with php 😉 

 

Check it with this code:

<html>
<body>
	<?php echo "<h1>$page->title</h1><br>"; ?>

	<?php foreach($page->we as $member): ?>
		<img  src="<?php echo $member->Images->url; ?>" alt="">	
		<?php echo $member->wemember; ?><br>
	<?php endforeach;?>
</body>
</html>

 

you are using <? ... but with newer PHP Versions, this isn't working with the standard configuration, so you should always use <?php instead of <?

Share this post


Link to post
Share on other sites
20 minutes ago, zoeck said:

i think it's a problem with php 😉 

Check it with this code:

......

you are using <? ... but with newer PHP Versions, this isn't working with the standard configuration, so you should always use <?php instead of <?

You saved my life !!!!!!

This works:

<html>
<body>
	<?php echo "<h1>$page->title</h1><br>"; ?>

	<?php foreach($page->we as $member): ?>
			<?php foreach($member->images as $image): ?>
	            	<img  src="<?php echo $image->url; ?>" alt="">   
	        <?php endforeach;?> 		
		<?php echo $member->wemember; ?><br>
	<?php endforeach;?>
</body>
</html>

New PHP version is more tight?

And I appreciate help of everybody here, so nice! 

Share this post


Link to post
Share on other sites
37 minutes ago, bernhard said:

This does not help because tracy and the file editor panel do not work on this host. Also, you should never make any admin login data public, please remove it from your post, even if it is a temporary host.

OK, I'll remember that, and any Admin here please delete that info for me, guess I cann't do that on my own. And I find it hard to amend my post, only get a short window of one minute or so.

And, yes, I DID the hello world tuts.  Also I'm watching some youtube tuts by Ryan. Hope I could learn fast. 

Thanks.

  • Like 1

Share this post


Link to post
Share on other sites

You can also just change your login credentials or take the site offline 😉

Share this post


Link to post
Share on other sites
Just now, bernhard said:

You can also just change your login credentials or take the site offline 😉

Oh, good to know. 👍

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By David Karich
      Thanks to the great Pro module "RepeaterMatrix" I have the possibility to create complex repeater items. With it I have created a quite powerful page builder. Many different content modules, with many more possible design options. The RepeaterMatrix module supports the cloning of items, but only within the same page. Now I often have the case that very design-intensive pages and items are created. If you want to use this module on a different page (e.g. in the same design), you have to rebuild each item manually every time.
      With this proof of concept I have created a module which adds the feature to copy a repeater item to the clipboard so that you can paste this item to another page with the same repeater field. The module has been developed very rudimentarily so far. It is currently not possible to copy nested items. There is also no check of Min/Max. You can also only copy items that have the same field on different pages. And surely you can solve all this more elegantly with AJAX. But personally I lack the deeper understanding of the repeaters. Also missing on the Javascript side are event triggers for the repeaters, which would make it easier. Like e.g. RepeaterItemInitReady or similar.
      it would be great if @ryan would implement this functionality in the core of RepeaterMatrix. I think he has better ways to implement this. Or what do you think, Ryan?
      Everybody is welcome to work on this module and improve it, if it should not be integrated into the matrix core. Therefore I put it for testing and as download on GitHub: https://github.com/FlipZoomMedia/InputfieldRepeaterMatrixDublicate
      You can best see the functionality in the screencast: 
       
    • By Harmen
      Hi All,
      I've made a previous regarding an issue which I solved but I stumbled across a new issue :). Below again the explanation needed.
      You need a short introduction for this. The company I am working for has approx. 80 products on their website and they all have their own features. The features are imported from an older system which isn't used anymore. Back then, when they changed from the old system to PW, we imported the features into the product pages as a JSON-array so the pages could load a bit faster as exploding a JSON array is a bit faster than loading in a lot of items from a table or a repeater field.
      How the JSON array looks like: 
      {     "2": {  // The ID of the group that contains the actual features         "name": "Model and function", // The name of the group         "features": {             "43": { // Attribute ID                 "name": "Resolution (DPI)", // Attribute name                 "values": {                     "896": "500-1500-2000-3500" // Value ID and value name                 }             }         }     } } Now we are adding a few more products to the catalog with new features and some that are already in use by other products but I am really struggling to assign the right ID's with the correct values in 7 different languages without messing up filters etc. So I decided to develop a module that lets you easily add feature groups, attributes and values as pages and connect these to the product using a repeater. This started by exporting all the current groups, attributes and values and import them as pages in the following structure:
      - Features - Feature Groups - Group 1 - Group 2 - ... - Feature Attributes - Attribute 1 - Attribute 2 - ... - Feature Values - Value 1 - Value 2 - ... Secondly, I created a repeater field that I assigned to the 'Features'-page that can handle the JSON structure explained above by seeing each item of the repeater field as a group. Inside each item you can select the group page and you will find another repeater which contains 2 page selectors to select an attribute and a value. A single repeater field looks like this:

      Next step was to create a module that gets this field as an Inputfield from the Features page. Once the user has finished adding groups, attributes and values he can click on save and I export all the values in the same JSON array structure as earlier but now the ID's of the groups, attributes and values are just the page ID's. This works great to add new features to new products. 
      BUT, sometimes the features of a product change or need to be changed and you don't want to change the JSON array manually.
      So my idea was to do the same thing as adding the features, but now you grab the values from the product first and populate the items of the repeater field.
      $featuresPage = wire("pages")->get("template=features"); $featureGroups = json_decode($product->features, true); foreach ($featureGroups as $featureGroupID => $featureGroup){ $row = $featuresPage->features_repeater->getNewItem(); $groupPage = wire("pages")->get($featureGroupID); $row->feature_group_selector = $groupPage; $row->save(); foreach ($featureGroup["features"] as $featureID => $feature){ $featuresRow = $row->feature_repeater->getNewItem(); $attributePage = wire("pages")->get($featureID); $valuePage = wire("pages")->get(key($feature['values'])); $featuresRow->feature_attribute_selector = $attributePage; $featuresRow->feature_value_selector = $valuePage; $featuresRow->save(); } $row->save(); } $featuresPage->save(); $f = wire('fields')->get('features_repeater'); $inputfield = $f->getInputfield($featuresPage); $form->add($inputfield); $f = $this->modules->get("InputfieldSubmit"); $f->name = 'updateFeatures'; $f->label = 'Update Features'; $f->icon = 'plus'; $f->value = 'Update Features'; $form->add($f); Then the user can change / add features, click save and done!
      It is possible to update the feature attributes and values, but when I change the feature group value, it seems like PW creates a new field behind the scenes and keeps the old value as well. So let's say I have the following feature structure:
      - Feature Group 1 - Feature attribute 1 - Feature value 1 Now I want to update Feature Group 1 to Feature Group 2, below is the desired result and the actual result:
      // === Desired result - Feature Group 2 - Feature attribute 1 - Feature value 1 // === Actual result - Feature Group 2 - Feature attribute 1 - Feature value 1 - Feature Group 1 - Feature attribute 1 - Feature value 1  
      I am using the following function to update the features:
      private function processForm5_UpdateFeatures(InputfieldForm $form){ $form->processInput($this->input->post); if (count($form->getErrors())) return false; $pageID = $this->session->selectedProduct; $product = wire('pages')->get($pageID); $product->of(false); $repeater = $form->get("features_repeater")->value; $languages = wire("languages"); foreach ($languages as $language) { $return_array = []; $i = 0; foreach ($repeater as $repeaterItem) { //$this->message($repeaterItem); $group = $repeaterItem->feature_group_selector; if ($group["id"] == 0) { continue; } else { $group = wire("pages")->get($group["id"]); $feature_group_name = &$return_array[$group->id]['name']; if (!isset($feature_group_name)) $feature_group_name = $group->title->getLanguageValue($language); $features = $repeaterItem->feature_repeater; foreach ($features as $feature) { $this->message($feature); $attribute = $feature->feature_attribute_selector; $value = $feature->feature_value_selector; if ($attribute["id"] == 0 || $value["id"] == 0) { continue; } else { $attribute = wire("pages")->get($attribute["id"]); $value = wire("pages")->get($value["id"]); $return_array[$group->id]['features'][$attribute->id]['name'] = $attribute->title->getLanguageValue($language); $return_array[$group->id]['features'][$attribute->id]['values'][$value->id] = $value->title->getLanguageValue($language); } } } } $product->features->setLanguageValue($language->name, json_encode($return_array, JSON_UNESCAPED_UNICODE)); } $product->save(); $featuresPage = wire("pages")->get("template=features"); $featuresPage->features_repeater->removeAll(); $featuresPage->save(); /* $this->messages("clear all"); $this->errors("clear all");*/ $this->message("Updated all features for {$product->title}"); $this->session->redirect("../"); } Is there a way to avoid the current result and get the desired result? Why is there even a new repeater page created for the new value? Anything that can help me is greatly appreciated!
       
      ~Harmen
    • By gregory
      Hi guys, I need help.
      how do I translate Next Page?
      <?php if($page->next->id) {echo "<div class='float-right'><a class='button' href='{$page->next->url}'> Next Page </a></div>";} ?> I usually use this:
      <?php $lang = $user->language->name; if($lang == 'default') {echo "Next Page";} else {echo "Pagina successiva";} ?> or
      <?php echo __("Next Page"); ?> Thanks
    • By nuel
      Hi there
      Basically I want to call code within a ProcessWire page that isn't used as a template. Example: www.mypwpage.com/myphpfile.php
      I have a working PW Website with a couple of pages like /artists, /releases, /videos etc. Now I need a page /download without any editable fields in the backend, just calling some PHP code (that was coded by another guy) containing a form that checks unique download-codes in a second database and starts the download of the desired file. The script is working fine right now as part of a static website, but since I built PW behind the site, this independent «Download Section» of the page doesn't work anymore.
      Right now I have the main file download.php as a page template on a newly created empty page called /download, so until now the form is working (wow). After sending the form containing the download-code, the file check_code.php in a subfolder /site/templates/download is called and that's where I get an error.
      Any help?
    • By Sanyaissues
      Hi, I have a page with a repeater called teams with two fields: team (a pageReference with a list of teams) and people (a pageReference with a list of people who likes this team).
      I'm trying to populate the people field in the repeater according to the value of the team field in the same repeater. So far. I'm able to get the pageArray that I want to assign to the people field, but i don't know how to "save" the value for each instance of the repeater.
      I hope somebody can give me a light. Thanks in advance.
       
      $wire->addHookAfter('InputfieldPage::getSelectablePages', function($event) { if($event->object->hasField == 'people') { $repeaterField = $event->arguments('page')->teams; foreach ($repeaterField as $t) { // Is this the way to loop the instances of the repeater? $team = $t->team->id; $t->people = $event->pages->find("template=user, team={$team}"); var_dump($t->people); // This returns the values that i want to assign for each repeate instance $event->return = $t->people; // I hope this assign a custom pageArray for each repeater, but it assigns the same for all the instances of the repeater } } });