Hot answers tagged

9

You can use either an activeRecord for it $customer = Customer::find() ->where(['id' => 123]) ->one(); Or a query $rows = (new \craft\db\Query()) ->select(['id', 'email']) ->from('user') ->where(['last_name' => 'Smith']) ->limit(10) ->all();


7

Your where clause is actually a query based where so you have to select the database fields instead of the field handles. When you want to do it with where you have to make it like that $country = Entry::find()->section('countries')->where([ 'content.field_code' => ['like', 'CA'] ])->all(); This is the correct documentation right now. ...


6

You can use {{ craft.entries.section('whatever').total() }} for that.


5

Edited to provide a cleaner solution: This code will display different contents for available times and unavailable times in 30 min increments, and makes no assumption on how long your events are. {% set targetDate = "today" %} {% set events = craft.calendar.events({ dateRangeStart: targetDate, dateRangeEnd: targetDate }) %} {% for hour in craft....


4

Not a definitive answer at all, but you could at least add a .ids() on that so it only retrieves the entry ids and not all the entry data... {% if craft.entries.section('whatever').ids() | length > 0 %} <a href="www.com">Go here</a> {% endif %}


4

I got the answer to this thanks to @BrandonKelly from a comment in this question: How can you return elements between two values? Turning it into a subarray does the trick: expirationDate: [ 'and', '>=' ~ now, '<=' ~ now|date_modify('+2 weeks') ] Thanks, @BrandonKelly!


4

Both approaches are valid. In your first example, you could have moved .all() into the for-loop; and in the second example, you could have moved .all() out of the for-loop, and into the {% set entries = ... %} statement. Until you call .all(), you are working with an entry query, and after you call .all(), you’re working with an array of the actual entries (...


4

In Craft 3, you can't really have locales. If in Craft 2 you had multiple locales, that should have been automatically migrated to multiple sites (as now the site is always single locale) Having said that, you now need to use site or siteId parameter https://docs.craftcms.com/v3/dev/element-queries/entry-queries.html#site


4

The light switch value should be taken out of the search query and put into the entry query: {% set query = 'title:"' ~ "myValue" ~ '"' %} {% set results = craft.entries({ section: querySections, search: query, excludeFromSearch: 'not 1', orderBy: 'score', }).limit(50) %} Or slightly cleaner / Craft 3: {% set query = 'title:"' ~ "...


3

You can probably use the relatedTo parameter with multiple relation criteria: {% set entries = craft.entries.section(['news', 'press']).relatedTo('or', { targetElement: newsTypeCategory, field: 'newsTypeCategoryField' }, { targetElement: pressTypeCategory, field: 'pressTypeCategoryField' }).order('postDate desc') %} Note that newsTypeCategory and ...


3

Not sure how you implemented the cache tags, but I would recommend to cache each "eDrops" entry individually. I also took out {% if entry.slides|length %}. Testing if entry.slides.first() returns anything is all you need. In order to make the length filter work, Craft internally applys find() to the criteria model behind entry.slides. This means you (...


3

One way to do it is to split the search query on spaces, and then join it with 'OR': {% set query = craft.request.getParam('q')|split(' ')|join(' OR ') %} {% set entries = craft.entries.search(query).order('score') %} The above will convert the search term "salty dog" to "salty OR dog". It'll work regardless of the number of keywords in the original search ...


3

Got it all sorted: {% if craft.users.group('myusergroup').total() > 0 %}


3

You'd have to set up an ElementCriteriaModel with parameters adapted to your entry type and the values you're getting from the query string. I'd recommend to read the official docs on that topic https://craftcms.com/docs/templating/elementcriteriamodel https://craftcms.com/docs/templating/craft.entries After that you shouldn't miss Combined searches and ...


3

I might be missing some important SQL-ism, here, but I think the question has a much simpler answer. The ElementQuery docs bury it a bit, and I wonder if many new Craft developers have trouble understanding the power of it, as a result. From the documentation: Tip Most custom fields support element query parameters as well, named after the field ...


3

general The first way creates an object of type EntryQuery, you then call the 2 functions section and limit In PHP you would do the following: $query = Entry::find()->section('news')->limit(10); The second creates an array section => 'news', 'limit' => 10 you then call Yii2::configure($query, $array) with your EntryQuery which does: public ...


3

You need to join the matrixblocks and the specific content table $query->join('{{%matrixblocks}}, 'matrixblocks.ownerId = elements.id); $query->join('{{%matrixcontent_your_table_name}}, 'matrixcontent_your_table_name.elementId = matrixblocks.id); $query->andWhere([ '>=', 'matrixcontent_your_table_name.name-of-the-column', new ...


3

When joining the tables you get more results like you mentioned in Edit2. First pick distinct ids, to use later on in the main query. I came up with this: $timeSlotIds = Entry::find() ->section('activities') ->innerJoin('matrixblocks', 'matrixblocks.ownerId = elements.id AND (SELECT enabled FROM elements WHERE matrixblocks.id = elements.id) = ...


3

My Craft 3 version is: {% set result = craft.entries() .section('events') .eventDate( ['and', '<' ~ now|atom, '>' ~ now|date_modify('-6 days')|atom ] ) .results(':notempty:') .orderBy('eventDate desc') .limit(3) .with(['imageGallery']) .all() %} Note the extra |atom after the date_modify('-6 days')


3

You can just query for the field value directly How to use Element Queries {% set featuredEntry = craft.entries({ section: ['resources'], orderBy: {postDate: SORT_DESC}, limit: 1, featured: 1, }).all() %}


3

Try rewriting your element query like so... craft.entries .section(['etiquette','style','culture']) .requiredReading(true) .orderBy('id desc') .limit(12) .all() In Craft you can do queries against fields in this way. The where() isn't necessary for what you're trying to achieve.


3

There is a related to parameter you can use Entry::find() ->section($section) ->relatedTo(['targetElement' => $image->id, 'field' => 'galleryImages') ->all();


3

Answer for Craft 2 Your final result should not look like relatedTo('and', '1,2') but relatedTo('and, 1, 2') Or relatedTo(['and', 1, 2]) So you just need to do relatedTo('and,' ~ param) Keep in mind to code defensively, so you might want to check if your query param is not null or something Answer for Craft 3 relatedTo(['and', ['element' => 1], ['...


3

This should do it: {% set eventCats = craft.request.getParam('cat')|split(',') %} {% set events = craft.entries.relatedTo(['and']|merge(eventCats)).find() %}


3

I think your problem is you're converting the date to a year string then converting that to an atom value. Just convert the date straight to an atom value: {% set yearStart = "#{year}-01-01"|atom %} {% set yearEnd = "#{year}-12-31"|atom %} {% set entries = craft.entries({ section: "programme", isOngoing: 0, startDate: ["and", ">= #{yearStart}...


3

So I'm wondering the same thing, I'm using CraftQL as I need to support mutations, and I am close with this - but I get an error if I try to use $id instead of a hard-wired Int (e.g. 99): query getEntryData($id: [Int]) { prevEntry: entry(prevSiblingOf: 99) { id title slug uri } nextEntry: entry(nextSiblingOf: 99) { id title ...


3

When you're setting section.links.limit(4), Craft will persist that limit in subsequent calls. This was a change introduced in Craft 3, which you can read about Changes in Craft 3 | Cloning Element Queries You have two options to resolve your issue: Use clone() to create a new version of the ElementCriteriaModel for each time you use section.links {% for ...


3

Joshua M's answer explains why it's happening, but in terms of best practice, you'd be better off avoiding multiple roundtrips to the database by using Twig filters on a single result set. There are probably a few different ways, but here's one using slice: {% set allLinks = section.links.all() %} {% for link in allLinks|slice(0, 3) %} {# iterate ...


2

I believe that Craft searches and indexes the contents from ALL custom fields. If that's true, then you only need a single search field. e.g. https://craftcms.com/search?q=field Display's results from multiple Sections i.e. Plugin Dev, Documentation and Templating Would you consider separating your search results, based on whichever entries/sections are ...


2

Using the pagination helper might be a cleaner way to achieve your desired results. It would go something like this: {% paginate craft.entries.section('news').order('postDate').relatedTo({targetElement:categoryId}).limit(5) as entries %} {% for item in entries %} {# your item code goes here #} {% endfor %} {% if paginate.prevUrl %} ...


Only top voted, non community-wiki answers of a minimum length are eligible