SitePoint Sponsor

User Tag List

Results 1 to 15 of 15
  1. #1
    SitePoint Wizard
    Join Date
    Dec 2005
    Posts
    1,711
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Drupal view field keeps repeating

    Hi all

    I have some php code which I've been trying to change to display separate fields.
    The problem I've added extra fields manually to try and do this, everything is repeating.

    The original

    PHP Code:
    <?php foreach ($fields as $id => $field): ?>
      <?php if (!empty($field->separator)): ?>
        <?php print $field->separator?>
      <?php endif; ?>

      <?php print $field->wrapper_prefix?>

        <div>
          <?php print $field->content?>
        </div>

      <?php print $field->wrapper_suffix?>
    <?php 
    endforeach; ?>
    Which outputs (from $field->content):

    Location
    Date
    Title

    Amended

    PHP Code:
    <?php foreach ($fields as $id => $field): ?>
      <?php if (!empty($field->separator)): ?>
        <?php print $field->separator?>
      <?php endif; ?>

      <?php print $field->wrapper_prefix?>
        <div>
          <?php print $fields['field_event_location']->content?>
        </div>
        <div>
          <?php print $fields['field_event_date_and_time']->content?>
        </div>
        <div>
          <?php print $fields['title']->content?>
        </div>

      <?php print $field->wrapper_suffix?>
    <?php 
    endforeach; ?>
    Which now outputs (from $fields['field_event_location']->content; etc.):

    Location
    Date
    Title
    Location
    Date
    Title
    Location
    Date
    Title

    Can you see what I'm doing wrong?
    Why is is repeating and showing numerous times?

    Thanks, cb
    The more you learn.... the more you learn there is more to learn.

  2. #2
    SitePoint Wizard
    Join Date
    Dec 2005
    Posts
    1,711
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Anybody?

    Thank you
    The more you learn.... the more you learn there is more to learn.

  3. #3
    SitePoint Wizard
    Join Date
    Dec 2005
    Posts
    1,711
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Managed to fix it

    If anybodys interested, remove the foreach loop, it's only needed with <?php print $field->content; ?>
    You can then spit out and style whatever fields you desire, as long as you have the fields ID to output it.

    Remove everything besides the fields you're working with, in my case the below:
    Code PHP:
    <?php print $fields['field_event_location']->content; ?>
    <?php print $fields['field_event_date_and_time']->content; ?>
    <?php print $fields['title']->content; ?>

    Then simply add whatever markup you need.
    <ul> maybe <div>'s whatever you need

    Barry
    The more you learn.... the more you learn there is more to learn.

  4. #4
    SitePoint Wizard bronze trophy
    Join Date
    Oct 2001
    Location
    Vancouver BC Canada
    Posts
    2,029
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    Barry, are you using a views template so that you can wrap the elements inside containers of your choosing or is there another reason?

    I'm afraid that by hard coding the fields right in your template, you're doing away with the flexibility that views was intended to add. I use views templates sparingly and only when I need to do something like filter a special character using a PHP replace function or maybe to do some sort of string translation.

    Moving forward, your template will ignore any changes someone might make to add or modify the view through the views ui. For instance, if I go into views and add another field or change the order of the fields, it won't respond to it. If I replace or rename one of the fields, when that template runs, it will give me a php error.

    If you want to change the html elements or add/change the classes that views wraps around each field, you can make granular changes to the individual field in the Field Properties window and more overall changes in Format -> Settings of the view.
    Andrew Wasson | www.lunadesign.org
    Principal / Internet Development

  5. #5
    SitePoint Wizard
    Join Date
    Dec 2005
    Posts
    1,711
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Barry, are you using a views template so that you can wrap the elements inside containers of your choosing or is there another reason?
    Exactly that awasson.

    I've added the above to views-view--article-list--block.tpl with article-list being my view.

    I'm afraid that by hard coding the fields right in your template, you're doing away with the flexibility that views was intended to add.
    Yes I understand this, but how are you supposed to get the individual fields to output from inside $field->content ?
    By doing it this way you have complete control of the output, no?

    Moving forward, your template will ignore any changes someone might make to add or modify the view through the views ui. For instance, if I go into views and add another field or change the order of the fields, it won't respond to it.
    As long as I keep track of the changes this shouldn't be a problem.
    Isn't this why the overrides are used so you can override this and do what you want with the code?
    I understand if maybe we have 10 developers working on the same site or clients updating the view(s) themselves though I think in this instance this is the best way.

    If you want to change the html elements or add/change the classes that views wraps around each field, you can make granular changes to the individual field in the Field Properties window and more overall changes in Format -> Settings of the view.
    Are you saying I can remove all the markup from each individual field and wrap whatever code I like around it without the need for views-view--article-list--block.tpl?

    If so, please explain thanks.
    And correct me if I'm wrong but doesn't each view reference roughly 3.tpl files for different stages of the output.
    I'm currently overriding 3 files to get the full customization of the higher wrappers, not just the fields.

    Barry
    The more you learn.... the more you learn there is more to learn.

  6. #6
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,147
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    Is your query rather complex? The reason I ask is views can be a quite a bit to untangle. In many cases it is better to use an Entity Field Query and avoid views altogether in D7. Than you don't have to muddle with all the magic of views, ctools, etc. Not to mention avoiding views will provide a much more stable architecture.
    The only code I hate more than my own is everyone else's.

  7. #7
    SitePoint Wizard bronze trophy
    Join Date
    Oct 2001
    Location
    Vancouver BC Canada
    Posts
    2,029
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by computerbarry View Post
    Are you saying I can remove all the markup from each individual field and wrap whatever code I like around it without the need for views-view--article-list--block.tpl?

    If so, please explain thanks.
    And correct me if I'm wrong but doesn't each view reference roughly 3.tpl files for different stages of the output.
    I'm currently overriding 3 files to get the full customization of the higher wrappers, not just the fields.

    Barry
    I usually leave the default wrappers and write css to make them do what I want and override any default behaviors. Typically I use the default unformatted list (which isn't an html list, just a series of divs). That gives you an outer view div and a bunch of divs with the class views-rows that will contain divs with each of my fields also contained in a div.

    If I want to remove or modify the formatting, I can do it in several layers. It really depends on what you want to do.

    1) The first thing to look at is the "Style Settings". That's where you can override, add to how the individual field is formatted. Does it output in a div, span, h1, a, etc... Do you want the default styles or do you want custom classes or IDs. Lots of options here to look at. You may find everything you need right here.

    2) The next setting I would suggest learning inside and out is the rewriting control. I rarely if ever use the default checkbox, output as link option on the field and rather will opt to rewrite the field using the replacement patterns. I almost always rewrite fields. There are so many options you can use here to add classes, remove default classes, completely override the output. It is one of the most powerful features in views and negates the need to hard code fields in a template.

    3) In a similar vein, I'll often check the "Exclude from display" on a number of fields and then add a global text field which I'll use to consolidate them in with various html tags. This is really handy for things like fully formatted address or contact blocks and that sort of thing. In the following example, I used the location module which gives me a nicely formatted vCard for the address but the contact name, email and website info needed to be set up to match. I excluded them from display and then added a global text field to set up the way I wanted them to be done. This could also do away with your custom template: http://www.sitelines.org/category/categories/features

    Edit, the above idea is better shown at this page: http://www.bcsla.org/consulting/bcsla-roster
    If you look at the code that produces the content for each person, you'll see that there are a bunch of fields named field-nothing. These are global text fields I've used to insert and format my exclude from display fields with.
    HTML Code:
    <div class="views-row views-row-1 views-row-odd views-row-first">
          
      <div class="views-field views-field-nothing">        <span class="field-content"><strong>Joe Blow</strong></span>  </div>  
      <div class="views-field views-field-current-employer">        <span class="field-content">ACME Design Inc.</span>  </div>  
      <div class="views-field views-field-nothing-1">        <span class="field-content">123 Alphabet Street<br>
    West Vancouver, BC V7P 1N3</span>  </div>  
      <div class="views-field views-field-country">        <span class="field-content">Canada</span>  </div>  
      <div class="views-field views-field-phone">    <span class="views-label views-label-phone">Tel: </span>    <span class="field-content">778 222-2222</span>  </div>  
      <div class="views-field views-field-email">        <span class="field-content"><a href="mailto:me@example.com">me@example.com</a></span>  </div>  
      <div class="views-field views-field-url">        <span class="field-content"><a target="_blank" title="Website" href="http://www.example.com">http://www.example.com</a></span>  </div>  
      <div class="views-field views-field-text-link">        <span class="field-content">Edit Contact</span>  </div>  </div>
    Here's another with more global "nothing" text fields from this site: http://www.csla-aapc.ca/people/reper...bres-de-l-aapc
    HTML Code:
    <div class="views-row views-row-1 views-row-odd views-row-first">  
      <div class="views-field-display-name">
        <span class="field-content">Joe Blow</span>
      </div>
    
      <div class="views-field-nothing-1">
        <span class="field-content"><span class="description">ACME Designs (ACME)</span> </span>
      </div>
      
      <div class="views-field-nothing">
        <span class="field-content">street-address-field<br>
          city-field province-field postal-code-field<br>
          country-field</span>
      </div>
      
      <div class="views-field-phone">
        <label class="views-label-phone">
          Tel:
          </label>
            <span class="field-content">778-222-2222</span>
        </div>
      </div>
    4) Finally there is the Format -> format and Format -> show settings you can modify to change the overall way your view is rendered. Table, grid, list etc...

    There are lots of things you can do to mess with views straight out of the box and if you can do it within the UI, it will be easier to maintain in the long run
    Last edited by awasson; Feb 16, 2014 at 12:16. Reason: better example
    Andrew Wasson | www.lunadesign.org
    Principal / Internet Development

  8. #8
    SitePoint Wizard
    Join Date
    Dec 2005
    Posts
    1,711
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Cheers oddz

    Is your query rather complex?
    I'm basically pulling in a few nodes which I've made from an imported feed, then sorting by date and limiting to 3 with linked title and date.
    So suppose its not that complex.
    Are you saying Entity Field Query is a better way?

    In many cases it is better to use an Entity Field Query and avoid views altogether in D7.
    Haven't used Entity Field Query yet, still fairly new to Drupal though after you mentioned it I seem to be seeing it more
    What I can gather from a quick search... I'd need to write all the logic for everything I query. Views has a simple UI which does the work for you, no?
    And wouldn't that mean I'd need to be very good at coding with PHP?

    Than you don't have to muddle with all the magic of views, ctools, etc.
    I wouldn't say I'm muddling it I'm just making the markup/output better. More semantic.

    Not to mention avoiding views will provide a much more stable architecture.
    Can you explain? How does it make it better?

    I did think that using views was the backbone of most drupal sites, no?
    I've also been looking at Drupal 8 which now has views built into the core and even uses a view for the default homepage.
    And speaking of backbone, this is the new javascript framework their using with Drupal 8.

    Thanks, Barry
    The more you learn.... the more you learn there is more to learn.

  9. #9
    SitePoint Wizard bronze trophy
    Join Date
    Oct 2001
    Location
    Vancouver BC Canada
    Posts
    2,029
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    Yes, Views is the backbone for many Drupal sites but you can write a module to run your own queries and wrap it up in a page or a block as well. I tend to use Views to standardize the way I do things and so that if need be, someone else can take over and not have to deal with my custom code.

    What is the preferred (semantic) markup you're looking for? If you can show what you're looking for I may be able to give you a step-by step approach to achieve it. We may still need a views-template but key to my philosophy is not painting yourself into a corner where you have to modify code just to add or modify a field.
    Andrew Wasson | www.lunadesign.org
    Principal / Internet Development

  10. #10
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,147
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by computerbarry
    Can you explain? How does it make it better?
    The nature of the beast is as you store more and more stuff in configuration instead of concrete code the less stable the site. This is especially true when it comes to continuous integration work which can be a real painful thing to do on large scale Drupal sites where nearly everything is stored as; ctools entity, database serialization, etc.

    Quote Originally Posted by computerbarry
    I did think that using views was the backbone of most drupal sites, no?
    I've also been looking at Drupal 8 which now has views built into the core and even uses a view for the default homepage.
    And speaking of backbone, this is the new javascript framework their using with Drupal 8.
    Drupal 8 has a very sophisticated configuration management system that nearly eliminates all the problems concerning continuous integration and moving configuration between different environments. Though I would still say that writing queries instead of views is going to be faster and more stable. The more and more magic you pile on the less maintainable the site will become. Achieving a good balance is important.

    Quote Originally Posted by computerbarry
    I wouldn't say I'm muddling it I'm just making the markup/output better. More semantic.
    One things views is not is semantic. If you are going to use views I would recommend going in accepting the fact that will loose in semantics you gain in themeing flexibility. I don't think a client would ever want me to spend time reverse engineering and making views even more complex than it already is for semantics. If you truly want the most semantic site available using drupal than use queries and standard menu callbacks. I'm sure there is a certain group of people that would disagree but I work on very large Drupal sites and the time it would take to make some of the views and what not semantic while loosing a designers flexibility to style isn't really worth it. The wrappers are there for a reason. I mean they can be removed but really, why from a practical standpoint.

    Quote Originally Posted by computerbarry
    Haven't used Entity Field Query yet, still fairly new to Drupal though after you mentioned it I seem to be seeing it more
    Entity Field Query is a wrapper about the database abstraction layer for entities. Specifically adding integration with fieldable entities providing a relatively simple API to filter and sort by fields. Thing of it like a ORM for entities within Drupal.

    Quote Originally Posted by computerbarry
    Are you saying Entity Field Query is a better way?
    It is going to depend who you ask but I would say yes.
    The only code I hate more than my own is everyone else's.

  11. #11
    SitePoint Wizard
    Join Date
    Dec 2005
    Posts
    1,711
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    write a module to run your own queries and wrap it up in a page or a block
    I know blocks can have there own code, its more or less the way I'm working at the moment each block has a different view assigned to it.
    Are you saying the module will also work as a db connection? And wouldn't I need to write a mixture of SQL/PHP do get what I need if I don't use a view?

    Just trying to get an understanding here thanks.
    I just don't see the benefit of writing code if I can create a view and everything is done for me?

    Hope this makes sense.

    -------------------------------------------

    I was getting around to your post awasson.
    Have you heard the term "divitis" this is what your output looks like above.

    What I need is a <ul class="someclass"><li>... and some rich snippets added to certain fields.
    This is the main reason I need to get full control of the output.
    And generally follow best practices and have well formed well structured semantic markup, that makes more sense than wrapped up in unnecessary div elements.

    I'm still learning Drupal and appreciate and very interested in your views on this.

    Thanks, Barry

    update. thanks oddz get back shortly.
    The more you learn.... the more you learn there is more to learn.

  12. #12
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,147
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    Well this is psuedo code for want you want to do and I wrote it in about a minute. Where as trying to find your way through views to alter the HTML is much more complex and is going to require template overrides and all that junk.

    PHP Code:
    function foo() {

      
    $query = new EntityFieldQuery();
      
    $query
      
    ->entityCondition('entity_type','node')
      ->
    entityCondition('bundle','bundle_name');
      ->
    propertyOrderBy('created');
      ->
    range(0,3);

      
    $result $query->execute();

      
    $nodes = array();

      if(isset(
    $result['node'])) {
        
    $ids array_keys($result['node']);
        
    $nodes entity_load('node',$ids);
      }

      
    $build = array(
        
    '#prefix'=> '<ul>',
        
    '#suffix'=> '</ul>',
      );

      foreach(
    $node as $node) {
      
        
    $build['node_'.$node->nid] = array(
          
    '#prefix'=> '<li>',
          
    '#suffix'=> '</li>',
        );
      
        
    $build['node_'.$node->nid]['title'] = array(
          
    '#type'=> 'markup',
          
    '#markup'=> l($node->title,drupal_get_path_alias('node/'.$node->nid)),
          
    '#prefix'=> '<h3>',
          
    '#suffix'=> '</h3>',
          
    '#weight'=> 0,
        );
        
      }

      return 
    $build;


    If you want to expose it as a block you could than use the block hooks to create your own block. Much simpler than fussing with views imo.
    The only code I hate more than my own is everyone else's.

  13. #13
    SitePoint Wizard
    Join Date
    Dec 2005
    Posts
    1,711
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well this is psuedo code for want you want to do and I wrote it in about a minute
    If it was just that simple... you make it look so easy.
    If I can write PHP like this I doubt I'd be here oddz.
    You're giving me a good angle starting point here and giving me something to work from.
    I can definitely see where youre coming from and kind of agree, well, I do agree its just my knowledge isn't at that level yet

    I've worked with big teams in the past and for the more complex Drupal sites with consistent updates and queries amongst other things... budgets, timescales there is no time to create clean semantic html. Though saying that, its down to personal preference if its a small personal site then I think its a good idea to do things right. And a good learning curve. As most things, there is always a number of different ways to do it.

    If you want to expose it as a block you could than use the block hooks to create your own block. Much simpler than fussing with views imo.
    Still learning about hooks and stuff but again, I can see what you mean and does make more sense than adding everything to the configuration.


    I'll need to digest the information here and continue learning a few things.
    Really appreciate the information and advice. I'll get back once I get my head around things.

    Thank you
    Barry
    The more you learn.... the more you learn there is more to learn.

  14. #14
    SitePoint Wizard
    Join Date
    Dec 2005
    Posts
    1,711
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Couple of questions:

    Though I would still say that writing queries instead of views is going to be faster and more stable
    What about a mixture. Do you use one over the other or sometimes mix them up?

    Entity Field Query is a wrapper about the database abstraction layer for entities
    What do you mean? It talks to the DB?
    If turned on views shows you all the SQL code. How does this work if you write your own?
    I don't see any SQL in your code above. Where is the DB query?

    Thanks, cb
    The more you learn.... the more you learn there is more to learn.

  15. #15
    SitePoint Wizard bronze trophy
    Join Date
    Oct 2001
    Location
    Vancouver BC Canada
    Posts
    2,029
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by computerbarry View Post
    I know blocks can have there own code, its more or less the way I'm working at the moment each block has a different view assigned to it.
    Are you saying the module will also work as a db connection? And wouldn't I need to write a mixture of SQL/PHP do get what I need if I don't use a view?

    Just trying to get an understanding here thanks.
    I just don't see the benefit of writing code if I can create a view and everything is done for me?

    Hope this makes sense.
    Ok, I'm getting off topic of your intention to clean up a View but here goes...

    Yes, sort of... Drupal has an API/Abstraction Layer that simplifies a fair bit of custom coding and you can write your custom logic in a module that will plug into Drupal and do whatever heavy lifting you need done. Using the API which is reasonably documented (https://api.drupal.org/api/drupal) you can get drupal to do a lot of work for you but you need to be familiar with the system (read the API docs). For what you want to do, you'll still need to write some SQL but armed with a tool like MySQL Workbench, you can do a lot of the legwork before you write anything to code.

    You can also write custom PHP in your theme or a block but it is wildly less efficient that writing in a module because module code runs earlier in the process when any given page loads. I don't know if you're ready for it yet but I'd recommend a book called Pro Drupal Development. It does a decent job of walking you through the API and discusses module development, when different code is run and some ideas of how best to do things.



    Quote Originally Posted by computerbarry View Post
    I was getting around to your post awasson.
    Have you heard the term "divitis" this is what your output looks like above.
    Well, you might want to have a look at that again and you'll find that it is not divitus. It uses a div to wrap the views-row, then it uses div containers for each section of the entry (which is not a case of Divitus) as they are not nested divs. Then you'll see that phrases or words, titles, etc... are wrapped in spans which is the way the semantic web is supposed to be approached. I can use any wrapper I want around the fields, spans, h1 - h6, p, etc.... but for my purposes spans work fine because they allow me to use CSS as necessary to style each part as needed.

    HTML Code:
    <div class="views-row views-row-1 views-row-odd views-row-first">  
    
      <div class="views-field-display-name"><!-- This is the name of a contact for the firm  -->
        <span class="field-content">Joe Blow</span>
      </div>
    
      <div class="views-field-nothing-1"><!-- This is 2 fields concatenated in a global text field -->
        <span class="field-content">
           <span class="description">name-of-firm (region-of-firm)</span> 
        </span>
      </div>
      
      <div class="views-field-nothing"><!-- These are 5 fields concatenated in a global text field -->
        <span class="field-content">
          street-address-field<br>
          city-field + province-field + postal-code-field<br> 
          country-field</span>
      </div>
      
      <div class="views-field-phone">
        <label class="views-label-phone">Tel:</label> <span class="field-content">778-222-2222</span>
      </div>
    
      </div>


    Quote Originally Posted by computerbarry View Post
    What I need is a <ul class="someclass"><li>... and some rich snippets added to certain fields.
    This is the main reason I need to get full control of the output.
    And generally follow best practices and have well formed well structured semantic markup, that makes more sense than wrapped up in unnecessary div elements.

    I'm still learning Drupal and appreciate and very interested in your views on this.

    Thanks, Barry
    Ok, this is dead easy to do. In your view all you need to do is change the way the view is outputed. In the Editing UI, on the left side above the fields is the Formatting controls. You are probably using Unformatted list. Change that to HTML List and in the settings, change that to Unordered list.
    Andrew Wasson | www.lunadesign.org
    Principal / Internet Development


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •