texts: Best way to find a deprecation error with no location hint?

texts:
I'm getting a deprecation error about looping through element queries, but in my markup all my loops are being setup with the .all() method, so I'm struggling to find this.

And it's one that is coming up every time I clear my errors, so the CMS clearly still thinks it's an issue.


texts: Is there a callback for post Craft 3 CMS installation I can use?

texts:
I was hoping to have my module create a few fields, sections, and entries after the Craft 3 CMS has completed it's installation.

Is there a callback I can listen to that triggers after the CMS is installed? Or maybe there's a onAfterInstall equivalent I can run?

I've been poking around the InstallController, but I'm really not sure what I'm looking for.


texts:
Since file inputs are not allowd to be pre-populated, how do i tell craft that a required asset field is already filled in the front end edit form? Can’t seem to figure this one out.

Edit:
Users can create entries from the front end. Those entries have at least one required field which is an asset (image). Creating an entry works fine. However, when editing an entry the user should be able to change the asset as well so we give them the file input too when editing the entry. If they choose to leave that alone the entry couldn’t get saved since the file input stays empty but is still required.


texts: Order entries by a category field alphabetically then paginate

texts:
I've tried so many different things and can't get this to work...

{% set makeCat = craft.categories()
   .group('make')
   .orderBy('title')
   .limit(21) %}

{% paginate makeCat as pageInfo, makeCars %}
{% for make in makeCars %}
{% set entries = craft.entries()
   .section('cars')
   .carStatus('Inventory')
   .relatedTo(make)
   .all() %}

    {% for entry in entries %}
       <p>{{ entry.title }}</p>
    {% endfor %}
 {% endfor %}

I'm trying to list cars with a status of 'Inventory', order them by a single category field alphabetically by car make and paginate...is this not possible in Craft?  This code gets me the closest but doesn't paginate properly.  I want the 60+ entries to paginate 21 per page but in order of the make of the car ie. BMW, Ferrari, Porsche, etc.  Not sure what I'm missing or doing wrong but any help and direction would be super!  Thanks!


texts: Craft rich text field excerpt with slice and raw breaks when cut inside double tags

texts:
I got a rich text field.
I made an excerpt with striptags slice and raw twig functions.
It works fine most of the time (raw close tags when slice cuts inside a
).

{{ textBlock.text | striptags("

") | slice(0, 275) | raw }}...

But sometimes it completely breaks and put plenty of empty tags anywhere :

I noticed that it happened when the original text is cut in the middle of double tags like :

Some text cut by slice function here

Real bug no ?


texts: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data when checking out with PayPal Checkout for Craft Commerce

texts:
Hi I'm a bit lost with getting my new shop to work with the PayPal Checkout for Craft Commerce plugin. I've installed the plugin and set everything up over in Paypal sandbox adding my client ID and Secret into the correct fields in the PayPal gateway. The Paypal payment button is offered correctly when checking out but when clicked I get this error pop up:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I don't really know where to go from here. Tried googling and searching in this forum and although that error message crops up from time to time in the search results it's usually because somebody is doing some customisation with the checking out process. I haven't customised anything apart from styling the Craft Commerce templates. Can anyone tell me what I'm doing wrong? The site is in local development.
Thanks.


texts:
I'm trying to build a restaurant menu using a structure.
The structure looks like that:

> Menu-part 1
  > Menu-item 1
  > Menu-item 2
  > Menu-item 3

> Menu-part 2
  > Menu-item 4
  > Menu-item 5
  > Menu-item 6

How would I now make a page accessible with those entries ? Should I create a single-page and then add those categories ? Or is there a better way ?

EDIT
What I don't understand is: Do structures exist without any page behind it? Because what I want is a page that just takes every entry from my menu-structure and builds me the food-menu on mysite.dev/lunch-menu for example.


texts: Migrating Server - Craft isn't installed yet

texts:
I've set up a new Forge server and connected the repo to my site. I've also uploaded the database and copied over the db credentials to the dotenv file. However when I visit the site control panel continue to see this

Have created new db, imported and changed credentials. Still same
Have ftp'd into the server and can confirm all files are there

Is there something else I am missing?


texts:
This seems like it should be really simple. I set the field for an image asset, linked it to the entry type I want it associated to, and then uploaded the image in the cms to the folder I specified.

So now, when I call {{ entry.featureImage }} it should return the object of that image. I want its URL, because I want to place it in a special image tag. <img class="img-responsive" src="{{ entry.featureImage }}"> Now I know this returns an error that says "Object could not be converted to string". Because I need to modify it to get the string of the URL. How can I do this? I feel like I've tried everything and scoured the docs and internet. I cant just attach a .getURL() or .url like would make a whole ton of sense. I've even set entry.featureImage as a variable and then called image.url on it. Or .getImg('featureImage') maybe? But it needs the class of img-responsive.

This needs to be possible so that the CMS can allow for images to be specified and uploaded for specific spots in the website.


texts: How to structure data: Solo Events (Lectures) and Group of Events (Conferences)

texts:
I am working on my first craft project and am wondering how to create the following data structure:
I have a page with a large archive of solo-events (lectures, discussions etc). I think I will use a channel with categories for this.
In addition, there is a second content type: a conference. A conference is a group of solo-events. For example, several lectures and discussions.
The conference as a container has certain fields (picture, text) and the solo-events have other fields (speakers for example).
I wonder what is the best way in Craft to enable this form of container.
Example:
Solo-Events:

Event 1 with Speaker a
Event 2 with Speaker b

…
Conferences:

Conference A

-- Event A1 with Speaker c
-- Event A2 with Speaker d

Conference B

-- Event B1 with Speaker e
-- Event B2 with Speaker f
…
In the Frontend I would like to have:
Speakers-Archive:
I think this will be the easy one. For the speaker I would like to work with a channel and link them to the events.
Solo-Events and Conference-Archive:
A list with all solo-events and all conferences but without the sub-events.
So, this list should contain: Event 1, Event 2, Conference A, Conference B (A1, A2, B1, B2 should be excluded)
I am wondering how to deal with this idea of grouping the events to conferences:
I was thinking:

Two channels, events and conferences.
All events (solo and conference-related) are in one channel. For a conference (second channel) I can select the events which I want to include. For the archive list I need to exclude all the solo-events that are part of conferences.
This may not be optimal in terms of performance and user experience in the backend

Structure for Confernces and a Channel for Solo-Events
The conferences are the parent elements, the solo events are the child elements.
But how can I create different fields for the parents and children?

Structure with Entry Types:
I wonder if i can work with entry type here as well.
But But how can I bring the Entry Type together with the Hierarchy? So that Parent is always a conference and a children is an Event?

Matrix Field:
The Conferences has a matrix field to store the individual events. But I dont like this approach because I think it would be hard to get all the speaker from a conferences matrix field and combine them with the speaker from the solo-events to get one list with all speaker

Categories.
all events are stored in one channel and I create a Categorie for the Conferences.
It feels kind of wrong-headed because the Conference (in my understanding) is the parent of the event rather than the category.

What do you think?
At the moment I am trying the second approach:
{# get all conferences (parents) (level =1 )  from a structure and merge with all solo-events from a channel#}

{% set entriesConferences = craft.entries.section('conferences').level(1).ids() %}
{% set entriesEvents = craft.entries.section(['events']).ids() %}

{# Combine those IDs #}
{% set entryIdsCombined = entriesConferences | merge(entriesEvents) %}

{# Get all entries (so, no IDs this time), using your IDs, order by date#}
{% set allEntries = craft.entries.id(entryIdsCombined).order('datumUhrzeit desc') %}

Is there a better (in terms of performance, scalability and user experience in the backend) way to archive this?
I asked this question Oli from the craft team and he gave me an answer that he will hopefully add here as well.
Thanks!


texts: Where did the @property delcarations for the inbuilt services go?

texts:
I've noticed in a recent (not sure which exactly) version of Craft that the @property-read declarations for each of the inbuilt services have been dropped from /craft/app/Craft.php.

This means in PHP Storm, I no longer receive valuable code hints following a craft()-> statement:

Is there a new way to access these hints in the recent version? Maybe I've missed something and accessing services via craft() is no longer the preferred method?


texts: Craft 2: Exception: CException: Alias "ext.alpha" is invalid

texts:
Today I updated my craft to latest version Craft V 2.6.3015 by following this url.

I got it updated successfully and now my Craft version is 2.6.3015 which is latest of Craft 2.

After updating the Craft setup, I tested the site, and one of the page is giving an exception as mentioned below:

  Exception thrown in Make a Payment. Exception: CException: Alias "ext.alpha" is >invalid. Make sure it points to an existing PHP file and the file is readable. in C:\path\craft\app\framework\YiiBase.php:324

Please help me to get rid of the error.  I checked that the Craft is not having any extension named alpha.

Stack trace:

#0 C:\path\craft\app\framework\validators\CValidator.php(174): YiiBase::import('ext.alpha', true)
#1 C:\path\craft\app\framework\base\CModel.php(287): CValidator::createValidator('ext.alpha', Object(Craft\BarclaycardEpdq_PaymentModel), Array, Array)
>#2 C:\path\craft\app\framework\base\CModel.php(260): CModel->createValidators()
>#3 C:\path\craft\app\framework\base\CModel.php(158): CModel->getValidators()
>#4 C:\path\craft\app\models\BaseModel.php(501): CModel->validate(NULL, true)
>#5 C:\path\craft\plugins\barclaycardepdq\services\BarclaycardEpdq_ApiService.php(213): Craft\BaseModel->validate()
>#6 C:\path\craft\plugins\barclaycardepdq\services\BarclaycardEpdq_ApiService.php(64): Craft\BarclaycardEpdq_ApiService->callBarclaycard('Craft\\Barclayca...', Array, 'https://site...', 'payByAlias')
>#7 C:\path\craft\plugins\rhp\controllers\Rhp_PaymentsController.php(129): Craft\BarclaycardEpdq_ApiService->makePaymentByAlias(Array)
>#8 C:\path\craft\app\framework\web\actions\CInlineAction.php(49): Craft\Rhp_PaymentsController->actionMakeAPayment()
>#9 C:\path\craft\app\framework\web\CController.php(308): CInlineAction->runWithParams(Array)
>#10 C:\path\craft\app\framework\web\CController.php(286): CController->runAction(Object(CInlineAction))
>#11 C:\path\craft\app\framework\web\CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
>#12 C:\path\craft\app\framework\web\CWebApplication.php(282): CController->run('makeAPayment')
>#13 C:\path\craft\app\etc\web\WebApp.php(836): CWebApplication->runController('rhp/payments/ma...')
>#14 C:\path\craft\app\etc\web\WebApp.php(287): Craft\WebApp->_processActionRequest()
>#15 C:\path\craft\app\framework\base\CApplication.php(185): Craft\WebApp->processRequest()
>#16 C:\path\craft\app\index.php(73): CApplication->run()
>#17 C:\path\index.php(13): require_once('C:\\path\\...')
>#18 {main}


texts:
How can I pass in a quantity value while creating a subscription?

Plugin (version):

Craft CMS (3.1.21)
Craft Commerce (2.1.2)
Stripe for Craft Commerce (1.2.0)

Problem: My website allows users to subscribe to meal plans. For example, a user can subscribe to receive 5 vegetarian meals per week. Another user may also subscribe to recieve 10 meals per week. Currently, I must create two subscritpion plans on Stripe and on Craft (i.e Vegetarian-5 and Vegetarian-10). Stripe's API offers the ability to create a single plan that charges per quantity (i.e I want to create one Vegetarian Plan and charge $10 per meal).

I wrote a plugin that uses createSubscription() from craft\commerce\services. However, ideally I want to send a quantity value but after reviewing Craft's logic for this function, I am unable to figure out a way to pass in a quantity value. However, I could easily bypass Craft and use the Stripe's API to do this (setting subscription quantity through stripe API) but that feels like the wrong solution.


texts:
How does one go about serving asset files stored in cloud locations over SSL?

For S3, serving assets over SSL is simply a matter of changing 'http' to 'https'. However, Rackspace uses completely different domains for their SSL. This creates a situation where http://container1.rscf.com/myfile.jpg mightb be served over https://weird.something.rscf.com/myfile.jpg.

There just seems like there should be a property in the getUrlForFile method in AssetsService.php that helps with this, but I'm not seeing it.


texts: order and limit the occurrences of related categories

texts:
I'm generating a list of all related categories of the entries listed on the page.

{% for entry in entries %}
    {% set categories = craft.categories.group('functieGroep').level(2).relatedTo(entry).all() %}
    {% nav category in categories %}
        <option value="{{ category.title }}">{{ category.title }}</option>
    {% endnav %}
{% endfor %}

This produces the list of categories. However, I want this list sorted by category.title and only show one occurrence of similar listed categories?


texts: Nitro 2 on WSL craft failed permission change in cpresources

texts:
I get the following yii exception after installing and adding a Nitro2 site to WSL.
Failed to change permissions for directory "/app/web/cpresources/1453c57f": chmod(): Operation not permitted
cpresources permissions have been set to 777
imported project is running craft 3.3.15


texts: How do entry elements render a default string but also return an object at the same time?

texts:
So this is more of a PHP question than a Craft question, but the only example I can offer is one I've seen in Craft.
{{ craft.entries.id(4).one() }}
Returns a simple string like: "About Page"
{{ dump(craft.entries.id(4).one()) }}
Returns the entire element object.
From a PHP perspective, how does this work? Or where can I find out more about this practice?
It's a tricky thing to look up online and tracing through Craft's codebase hasn't offered much insight for a novice like me.


texts: Generate PDF preview images automatically?

texts:
Is it possible to auto generate PDF preview images with Craft transforms? This popular Q/A at Stack Overflow shows a PHP solution making use of ImageMagick and GhostScript. Is installing these plugins all I'd need to make Craft do the transforms with pdf.getUrl('thumb')?

Currently I use an assets - asset meta field on the PDF to achieve what I want (see code below), but that means I have to generate and upload the image myself. So I wondered if there's a nice and easy way to automate that process.

{% for pdf in entry.pdfAssets %}

    {# Get the pdf preview thumb or use a generic one as a fallback #}
    {% set previewImage = pdf.previewImage|length ? pdf.previewImage.first.url('thumb') : 'pdf_thumb.jpg' %}

{% endfor %}


texts: Specify a specific entry type in paramaters

texts:
I am currently searching within multiple sections on my site.
I'd like to limit one of the sections (courses) to a specific entry type (cce)?
Any help would be greatly appreciated!
{% set params = {
    section: [ 'pages', 'careerPaths', 'courses', 'events', 'eventsIndex', 'news', 'newsIndex', 'programs', 'allPrograms', 'facultyStaff', 'facultyStaffIndex' ],
    limit: siteVariables.resultsLimitForPagination
} %}

{# if search term exists, search #}
{% set searchTerm = craft.app.request.getParam('q') %}

{% if searchTerm|length %}
    {% set params = params|merge({ groupBy: ['title'] }) %}
    {% set params = params|merge({ search : searchTerm, orderBy: 'score DESC'}) %}
{% endif %}

{# Query #}
{% set query = craft.entries(params)  %}

{% paginate query as pageInfo, entries %}


texts: Moving from local asset folders to Google Cloud, Amazon, etc

texts:
I've setup a few clients with Google's Cloud storage recently and am thinking of offering it to other clients with image-intensive sites, as a kind of retro-fit.

One option will be to just create new asset folders and start using those instead of the current asset folders, but I'm also wondering if anyone has any experience of switching existing assets from local folders to Google Cloud (or Amazon, etc) and how much work was involved?

Thanks,
Clive


texts: Search query: grouping and merging multiple searches

texts:
Is it possible to 'group' search logic in the craft.entries.search query? I need to do the following: [a OR b OR c]  AND  [d OR e]  AND  [x OR y OR z]

Thanks!


texts: Including CSS and JS files on multilanguage sites

texts:
Up till now, all my craft sites were single language. When including CSS and JS files from web folder, i used to use {{siteUrl}} variable, like this:

<script src='{{siteUrl}}/plugins/jquery.js'></script>

Such path was rendered to this:

<script src='http://website.com/plugins/jquery.js'></script>

Unfortunetly, on multilanguage websites, where different languages have different url path (site.com and site.com/en), {{siteUrl}} variable changes and paths to these files are incorrectly rendered, like this:

<script src='http://website.com/en/plugins/jquery.js'></script>

What variable can i use that will give me path to web folder - regardless of currently used language?


texts: Is it possible to disable `requireUserAgentAndIpForSession` for specific instances?

texts:
I'm working on building a post-receive hook and a third party service's attempt to post data to a webhook keeps 302ing to the Craft login page when I attempt to use EmailModel and sendEmail().

The only thing Craft logs during this failed transaction is a series of errors that read...

  Someone tried to restore a session from a cookie without presenting an IP address or userAgent string.

I noticed the requireUserAgentAndIpForSession setting in UserSessionService->_checkVitals(), disabled it, and of course the problem went away.

I'd prefer not to disable this setting in general—is there a way to programmatically unrequire it for a specific plugin receiving posts?


texts: Query for blocks across Block Types using the new field parameter?

texts:
This is a great new feature of Craft 2.3:

  It is now possible to set custom field parameters on Matrix block queries.

I was wondering what would happen, if two or more Matrix Block Types had a field with the same handle (e.g. myLightswitchField), and if it was possible to query for blocks across Block Types using this field as a parameter.

My example code doesn't return any blocks:

{% set blocks = entry.myMatrixField.myLightswitchField('1') %}

Yeah! There's {{ blocks|length }} Matrix blocks enabled.

This is just an example! I know that you can disable blocks from the block's context menu.


texts: Transfer licenses into another Craft ID account

texts: I could only transfer licenses that were not yet assigned to any other Craft ID account. But how can I transfer the licenses, which are assigned with my other Craft ID account?


texts: Is it typical that data is fetched from within templates rather than in controllers?

texts:
I'm assessing Craft's suitability for my next project, coming from using HMVC in CodeIgniter with a custom CMS.

In CI all requests go via a controller action which is responsible for inspecting request parameters, loading and filtering data and passing that data to a view. Pretty typical MVC.

From what I've seen so far of Craft and plugins developed for it, the requests are typically forwarded directly to Twig templates and those templates are responsible for analysing query strings and request data and fetching data from exposed template variables or built in "entries".

I'm thinking of a use case where data would need to be displayed and filtered by query string and session criteria and it strikes me that the template would be handling too much of this logic and become bloated.

Most of the website I will be developing will get its data in JSON format from a REST API and passing filter criteria from user interaction with forms and UI controls will come up a lot.

My question is, is this a typical and recommended approach to using Craft, or should I be using controllers to handle tasks such as filtering and fetching data and passing it to a view?

Are there any plugins that I could look at for reference that could help me to understand the flow and process?

Thanks

Jamie


texts: How do you import hierarchical data that uses the adjacency list model into Craft Structures or Categories?

texts:
Craft makes it nice and easy for us to have hierarchy in Structures or Categories. Many other popular CMS platforms support hierarchical data as well but some support it using a different data model.

Here's an overview of managing hierarchical data in MySQL if anyone's interested:
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql

In particular, I'm trying to understand the best way to migrate data that uses the Adjacency List Model into Craft which uses the Nested Set model.

Are there any tools to help translate how each item in the table of the adjacency list model refers to a parent to how the nested set model uses lft and rgt to identify how the items in the table are nested?

If there aren't any tools for this, is there any step-by-step process that might make this a bit more accessible?  Or could I just be thinking about it the wrong way?


texts: Possible to speed up infinite scrolling?

texts:
In the control panel, on the entries index page, Craft uses infinite scrolling. However, when you scroll to the bottom, there's a slight delay while you wait for more entries to load.

Unfortunately, I'm in a situation where I have to scroll through thousands of entries. I'm cleaning up some imported data, and yesterday I managed to clean up entries from A - M. Today I need to pick up where I left off, and clean up entries from N - Z.

Is there anything I can do to speed up the scrolling process? (besides having a faster server)


texts:
In my _layout.html, I render the SEOmatic stuff via

{% hook 'seomaticRender' %}

This works fine for basically all content singles/channels, etc.

Now I have one template /newsletters/index.twig which works both as an archive page and a typical _entry page, in one.

If there's a 3rd segment or rather slug, it lists the archive sidebar and displays an entries content. So read/newsletter/sunny-beach works fine, and SEOmatic renders everything excellent.

However, when there's not a 3rd segment, so it's just read/newsletter, it works as an archive page, and the seoTitle should become "Newsletter archive".

From what I find is that {% do seomatic.meta.seoTitle("Newsletter archive") %} should enable me to push that through. But it doesn't, something like:

{% extends "_layout" %}

{% block main %}
    {% if craft.app.request.getSegment(3) == "" %}
         {% set entry = craft.entries.section('newsletters').orderby('newsletterIssueNumber desc').one() %}
         {# yes so  if there's no last segment, we're going to load the newest entry, which it does succesfully #}
         {% do seomatic.meta.seoTitle("Newsletter archive") %}
    {% endif %}
    ...
{% endblock %}

But it doesn't, do anything. No title. I also tried it with just putting it outside the if, so it gets executed for sure but, still nothing.

What makes it extra confusing is that in the SEOmatic docs they refer to a "New Template Meta" button, SEO Template Meta, which I can't seem to find, and suppose it's a leftover from its Craft 2 version or something.

In short: how do I bubble up variables to the hook that is in _layout, from within a template? And there are no entries/slug for SEOmatic to base itself on.


texts:
We are in development of our new site in Craft 3 and we are getting some deprecation errors. This is keeping us from using Craft Commerce for our ordering page. Any suggestions on how to fix this?

Message Origin  Last Occurrence Stack Trace
The Purchasable::getPurchasableId() function has been deprecated. Use Purchasable::getId() instead. /srv/captioncall/templates/buy/index.twig:6 Yesterday   Stack Trace
craft.session.getFlash() has been deprecated. Use craft.app.session.getFlash() instead. /srv/captioncall/templates/buy/index.twig:33    Yesterday   Stack Trace
craft.session.getFlash() has been deprecated. Use craft.app.session.getFlash() instead. /srv/captioncall/templates/buy/index.twig:34    Yesterday   Stack Trace


texts: Conditionally Applying CSS to Element on Active Page Without Using URL or ID Logic

texts:
I want to conditionally add some CSS to a subnav element if that page in the subnav is currently active. However, I can't add the CSS based on any slug / URL / getSegment logic, as that will likely be changed down the road. I also can't use the ID of the page.

The pages in this subnav are part of the same structure and it seems to me the best way to set the rule would be based on the order of the page in the structure. Something like if page 2 in craft.entries.section('') is active then apply CSS to target element.

Is this possible in Craft? If so, how would I do that? If not, other ideas for how to approach it?


texts:
This is giving me a surprisingly hard time. Has anyone tried to paginate entries by date, in this case, specifically by day; i.e.: First page loads today's posts, next page loads yesterday's, then the day before yesterday, etc.

I tried grouping items by date, as done in the archive page example, and then paginating the groups but it didn't work.

In this case I am using a combination of pagination + ajax to load more content when needed. However the needs of the project have changed, and paginating by number of items isn't the best approach. It'd be better to show content based on the date.

Anyone?


texts: How get entries by sources in a frontend fieldlayout?

texts:
I have multiple entries fields that I want to use in the front-end. In the field settings I'll set up a sections source for each field. On the frontend I want a dropdown select box with all the entries from section I'll setup for each entries field. If I'll dump the field sources from the field layout I'll get this:

array(1) {
  [0]=>
  string(44) "section:a0977adf3fd-bd50adf-479cadf-90cd-8d5ef46de79c"
}

How to get entries related to the section source above?

{% entries = craft.entries.section(field.sources).all() %} // This is not working

This is the code where I'll need it for some context

{% for tab in entry.fieldLayout.tabs %}
    {{ tab.name }}
    {% for field in tab.getFields() %}
            <label for="{{ field.handle }}">{{ field.name }}</label>
            {% if field.className == 'craft\\fields\\PlainText' %}
                {# field text settings #}
            {% elseif field.className == 'craft\\fields\\Number' %}
                {# field number settings #}
            {% elseif field.className == 'craft\\fields\\Entries' %}
                {% set entries = craft.entries.section(field.sources).all() %}
                {# entries is empty how to fix? #}
                <select name="fields[{{ field.handle }}][]">
                    <option value="">Choose</option>
                    {% for entry in entries %}
                        <option value="{{ entry.id }}">{{ entry.title }}</option>
                    {% endfor %}
                </select>
            {% endif %}
    {% endfor %}
{% endfor %}


texts:
In my plugin I have an init() method:

public function init ()
{
    parent::init();

    require CRAFT_PLUGINS_PATH.'/myplugin/vendor/autoload.php';

    $this->callTemplateHooks();

    craft()->onError = function(Event $event) {
        $this->logError($event);
    };

    craft()->on('userSession.onLogout', function(Event $event) {
        // do something
    });
}

I've got a breakpoint set on the onLogout() method of the UserService class so I can see that firing, however the breakpoint on my // do something line never gets hit.

Am I missing something here?


texts: "Call to undefined method Calendar\Library\Carbon::setWeekStartsAt()" Solspace Calendar

texts:
I've got Solspace Calendar installed to the best of my knowledge. I have repurposed the 'calendar_demo' files to 'calendar'. Both /calendar and /calendar_demo just show:

  "Call to undefined method Calendar\Library\Carbon::setWeekStartsAt()" in DateHelper.php.

/calendar/week does the same. A path like calendar/2016/11 just give a Twig error.

I can't understand why this is happening. I'll give more details if you ask me, I don't know what else to give.


texts:
In the multi-lingual site I'm building, I've created an "SEO" global set where my client can enter keywords and a description to populate meta tags site-wide.

Problem: globals don't seem to be translatable.

So unless I'm missing something, I'll have to add additional dedicated fields to hold the Spanish version of this info.

Am I missing something? How would you approach this, if you'd do it differently?

Thanks!


texts: How to search against a specific field/s, and not every field related to an element?

texts:
I have the below. I want to only show results that contain the query in the the username or fullName attributes.

Because currently if I search for say Tom the search results will return users without a username or full name containing the query Tom, but will show a person if the email contains it. I don't want this as emails are not publicly shown and therefore may cause confusion to the user searching.

How would I exclude email from the search criteria or only allow searching from the username or fullName attribute?

The same happens when searching entries - how do I narrow the search to only use the title field for example otherwise the search results can be too broad which is bad for UX.

{% set users = craft.users()
    .search(query)
    .group('creatives')
    .all() %}

{% if users|length %}

{{users|length }} results:

        {% for user in users %}

{{ user.username }}

        {% endfor %}

{% else %}

Your search for {{ query }} didn&#39t return any users.

{% endif %}


texts: Change asset upload path based on locale

texts:
We have a localized site with separate public directories. I'm looking for a method to handle image uploads for the different asset paths.

For example when uploading an asset within a particular locale, the image will be deposited in that public_*/uploads folder.

I thought perhaps concatenating the {craft.locale} in the asset path might work but it threw an error. I'm thinking that the locale doesn't change when selecting the language from the sidebar or asset dropdown.

I'm pretty stuck on this one and there doesn't seem to be any answers online. Any other ideas or solutions would be appreciated.


texts: Homepage showing up as "index of \" page

texts:
I am uploading a repo that works fine on a staging server to a live server. When doing so however the homepage is showing as "index of \" page with the public and readme.md directories showing. Like so

When i click on the public link it brings me to  the page, however it has no public assets or css. it is just HTML.

The database is linked properly. their are no errors that are showing as it is on dev mode. What can I do to fix this?

Here is the file structure in my home directory which is proper.

Thank you for your time.


texts: Craft 3: White blank page when accessing website and Craft login page

texts:
I'm getting white blank page when trying to access my website and Craft login page. I haven't updated the website for few months. So I assume no files has been changed.

I checked with the hosting provider, and they say everything is okay on their part.

I turned on dev mode, but still get a blank page.

What could possibly cause this? Is there anything I need to check? Thank you in advance. It's on Craft CMS 3.1.28. The url is https://vispaleis-oostende.be/.

Edit: as commented on a below answer: When I change the contents of Craft's index.php file to echo some text, this text does get shown on the website. Also, when I create such an echo php-file and include it from other folders using the variables CRAFT_BASE_PATH or CRAFT_VENDOR_PATH, it also shows that text. So the domain does point to the correct location, the index.php file gets loaded (also on any 'subpage' and the CMS-url, so not only the index page) and the include paths are found.

Edit 2: I just linked the domain name back to the beta-server, since everything was still working there. I also copied the database, to reflect the changes made in the CMS (small text changes). No files were changed since going online, so I didn't need to copy any files. Everything works as expected on the beta-server, so I think it's a problem on the 'live' server, even though the hosting provider claims it isn't. If anyone has an idea what this could be, please let me know so I can get back to the hosting provider...


texts: Multi language site not working on sub domain

texts:
I have an odd situation on a multi-lingual site I am building. I have the site set up on my local dev server and it works fine switching between languages. I have now added the site to an external server to show the client on a subdomain so test-dev.mydomain.com. Everything is exactly the same and the config file has been set up to target this domain. However now switching to another language only brings up the English version of the site when navigating past the home page. Any ideas what is happening here? Could this be because it is sitting on a subdomain?

Config snippet:

'test-dev.mydomain.com' => array(
    'devMode' => 'true',
    'env' => 'dev',
    'environmentVariables' => array(
        'siteStore' => '/assets',
        'sitePath'  => 'http://test-dev.mydomain.com/',
    ),
    'siteUrl' => array(
        'en_gb' => 'http://test-dev.mydomain.com/',
        'de_de' => 'http://test-dev.mydomain.com/de/',
        'pl_pl' => 'http://test-dev.mydomain.com/pl/',
        ),
)


texts: What's a Craft way to achieve extra info on specific relationships?

texts:
For example, say I have two sections:

Services
Locations

I make an entries field called "Services" and add it to the Locations field group, so that on a Location entry you can add n number of services.

What if I want a little bit of extra info that's unique to that particular pairing?

So, I have a location page called "Boston, MA" and a Service called "Window Washing". Using my entries field, I create a relationship on my "Boston, MA" page to the "Window Washing" Service.

However, I want to show a note with this particular relationship that we don't do Skyscraper windows in this location. It's Extra Info for this relationship only and it's variable.

How would you solve this problem in Craft?


texts: Templating not displaying after Craft server migration

texts:
A small team and I have inherited a Craft 2 site. We are brand new to craft with no previous experience with it. In wanting to work on offline copies of the sight the team is attempting to migrate the Craft site to our local LAMP servers.

The migration seems to have been somewhat successful. We are able to access the homepage of the site but there is no styling (please see image).

In addition, the links click through to Not Found errors.

Not sure what additional information can be provided to help troubleshoot the problem. If I can provide the data I will! Thanks for any assistance you can provide.

ps. I wasn't sure if this is the correct place to ask this question. If it isn't please relocate it


texts: Search without leaving or refreshing page

texts:
I'm trying to do a simple search of all posts, and using this: https://craftcms.com/docs/templating/search-form

It works but in that example it assumes you display search results on another page. I am trying to build this as a single-pager (it's a really basic site). I've tried reloading the page (i.e. setting url to the current page) and this works . . . however I also want to show/hide elements on search, and this is getting lost with the page reload.

I have a feeling this is going to be something basic, but am stumped . . . have been playing around with it, trying includes and stuff, and getting nowhere. My apologies if it's a noob question.

Search Results

    {% set query = craft.request.getParam('q') %}
    {% set entries = craft.entries.search(query).order('score') %}

    {% if entries|length %}

{{ entries|length }} results:

          {% for entry in entries %}

{{ entry.title }}

          {% endfor %}

    {% else %}

Your search for "{{ query }}" didn’t return any results.

    {% endif %}

So that is the code. I only want the search results appearing when the user searches (obvs) but want them on the main page (i.e the same page as the search form)

Here is the show/hide code if it helps at all:

var searchForm = document.getElementById("searchForm");
var revealedOnSearch = document.getElementById("revealedOnSearch");

searchForm.addEventListener("submit", function(){
    revealedOnSearch.style = "display:block;";
});


texts: Pulling in Structure entries as radio button options in Sprout Forms

texts:
I have a form created with Sprout Forms with a custom template to override the HTML. This form needs to pull in plan type information from a structure section that already exists.

I added the structure entries to the form in the template, but they currently aren't hooked up to form so when I hit submit. How can I hook this up so that when a user selects a plan type it will register with Sprout Forms?

I could try and create these fields in the form builder, but the way it's set up it's easier for us and the client to pull the information from the existing entries.


texts: Simple way to use craft for databaseless prototypes

texts:
We have found that craft (and twig mostly) combined with bootstrap make a great prototyping tool.  We'd started up a number of projects that use templating and lots of fun twig stuff but no real need to anything in the database

right now we go through the entire craft install and setup a database anyways but curious if it would be possible to run just the templating part of craft without a database at all?


texts: Are there any benefits to using Yii's Aliases vs getenv?

texts:
As part of a refactor on our code base, we have been looking into our use of Yii 2's aliases and PHP's getenv function. Here's a code example:

Alias

<link rel="icon" sizes="96x96" type="image/png" href="{{ alias("@interfaceAssetsBaseUrl/img/icons/favicon-96x96.png") }}" />

getenv

<link rel="icon" sizes="96x96" type="image/png" href="{{ getenv('INTERFACE_ASSETS_BASE_URL') ~ 'img/icons/favicon-96x96.png' }}"/>

For context, Interface Assets Base URL is set according to your environment; if you're on Dev it will point to your local files. If you're in Staging or Production it'll point to Amazon S3.

My question:

Is there any benefits in terms or performance in using either one of these methods? Does Craft cache one of these, for example?


texts: How to Properly Use Controller and Service in Custom Plugin

texts:
I am making some progress with creating a custom plugin, and am curious as to whether I am following proper "Craft standards". Here is my scenario:

A user needs to submit a one field form that contains their email address. Upon button click, I would like to prevent the default action, and send the email address via AJAX to my plugin for processing.

After reading through the Craft Plugin Docs, I am under the impression that my plugin requires the following functionality(and in this order).

Send email address via AJAX to a Controller.
The controller will then extract the email, and send it off to a
Service.
The Service, is where I should write my code that connects to the MailChimp API
Send the result of whether the Mailchimp API request was successful from the Service, back to the Controller.
The Controller will then send back the response to my JavaScript, where I will ultimately display a success or error message to the user.

I have been successful in sending an AJAX request from my JavaScript code to my Controller via the following code, and receiving some dumby test text.

function sendAjax() {
    var xhr = new XMLHttpRequest()
    xhr.open('POST', siteUrl + 'ajax/ajax-mailchimp.html')
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')

    xhr.onload = function() {
      if(xhr.status === 200) {
        console.log(xhr.responseText)
      }
    }
    xhr.send(encodeURI('action=/craftMailchimped/submittal/receiveEmail&email=fakeemailaddress@yahoo.com'))
  }

In my controller, I have the following:

<?php
namespace Craft;

class CraftMailchimped_SubmittalController extends BaseController {

    public function actionReceiveEmail() {
        echo 'Wuzup?';
    }
}

In case you are wondering what 'ajax/ajax-mailchimp.html' is, its an empty template file, with no code in it. I did this, because I didn't really know what to put in as the URL in the xhr.POST method in my JavaScript code.

I am concerned I am not going about this in the right way, as I wouldn't even know how I would extract the email address inside my controller.

Any help on this?

My Form HTML for reference:

<form id="updates" class="mchimp">

      {{ entry.connectNewsletterCta }}

      <input type="email" placeholder="Enter your email" required>
      <button class="btn">
        {{ entry.connectNewsletterButtonText }}
      </button>

  </form>


texts: Smart Map plugin, HAVING SQL and GROUP BY elements.id

texts:
It seems like most Craft queries contain GROUP BY elements.id but this seems to clash with a HAVING clause when using the Smart Map plugin.

Where does this come from and is it possible to override/remove this?


texts:
Not sure what is going on but my website is not getting indexed by google (went live last week). Robots is correct. What am I missing here?

I'm using the plugin seomatic for the SEO, Site robots meta tag has index, follow.

Site is: http://gastro-on-fire.be


texts:
We're trying to use Craft as a CMS for a mobile app and to accomplish this we need to convert entries to JSON. We use the Element API plugin for this and it works like a charm.

The problem is that we don't want certain content to be visible to everyone, so we want to require the users to log in. Is it possible for a user to log in via the mobile app, then get some kind of sessionToken which is stored in the database and then every time the user send a request to the API it sends the token along with it to make sure the user of the mobile app is authenticated (like the token in the craft_sessions table)? If so how can this be accomplished?

Should this require us to write our own plugin with a custom authentication system or is it possible to get this working with the user logic provided by Craft?


texts:
I'm having a problem with my ajax-loading when I'm on the english version of my page (My main language is Norwegian). I have a file named loadmore.html that I'm loading in on index.html when pressing a button. The problem is that this page won't show me the English version when I'm on the english version of the site. I really appreciate all your help. There's my code:

$('.showmemore_inner h2').on("click", function(e){
    $('.third_article_module').load('/loadmore.html');
    $('h2.lasterinn').css('display', 'block');
    return false;
    e.preventDefault();
});

Loadmore.html:

        {% for entry in craft.entries.section('artikkel').order('dateCreated desc') %}

            {% for block in entry.bildekarusell.limit(1) %}
                {% if block.type == "bilde" %}

                        {% for image in block.bilde %}

                            <picture>

                                <source srcset="{{ image.getUrl('hovedsideSekscolBilde') }}" media="(min-width: 990px)">
                                <source srcset="{{ image.getUrl('hovedsideSekscolBilde2') }}" media="(max-width: 990px) and (min-width: 625px)">

                            </picture>

                        {% endfor %}

                {% endif %}
            {% endfor %}

                    {% for category in entry.kategorier %}
                        {{ category.title }}
                    {% endfor %}

{{ entry.title }}

{{ entry.postDate|date("M Y") }}

    {% endfor %}

UPDATE: I tried this code in my _layout.html file but it's not working:


texts: Should project config be used during development when migrating from Craft 2?

texts:
I'm looking for general advice on the best approach to handle a reasonable sized Craft 2 site to Craft 3.1, related to DB changes.

Because the Craft 2 project is live and constantly changing, I regularly refresh my development environment with a snapshot of the Craft 2 database to test the migration process and to work with the latest data from the live project on my development environment.

One of the first problems I encountered was needing to make development changes to the Craft 3 database. These changes could include, adding new fields, updating entry types etc (that is specific to Craft 3), but obviously wiping the dev DB each time would kill these changes. I'm aware project config can store a lot of the changes I'm making, but the issue I found early on was things would get "reset" from each new migration and generate new UID values for certain fields etc. So if I was to replace my project.yaml file to the version that is committed to source, it would usually end with pain and MySQL failures. This made me think that project config isn't necessarily suitable for this specific development workflow.

My next approach was content migrations. This provides a way to write any changes as a migration which would get applied each time the DB was refreshed, this solves the problem of losing changes, as the migration would run as part of ./craft migrate/all and apply them again. As content migrations have full access to pretty much all things Craft, content migrations themselves are quite powerful, so seem like an option.

From a Craft 2 to 3 migration point of view, would it be best to not use project config during development and only enable project config once the Craft 3 migration is complete? It looks like the general advice is to enable project config, copy the project.yaml from the production site and a copy of the DB and apply this to any dev/staging environment to synchronise all environments and then proceed with a more linear workflow going forward.

Any thoughts or opinions on this would be appreciated!

Thanks,


texts: Add a form field into the details bar on the entry edit screen and do something with the value

texts:
I'd like to add a form field into the details bar on the entry edit page, so that when the entry gets submitted, the form field value gets passed into the data payload so that I can pick it up from the EVENT_BEFORE_SAVE event.
However, it does not seem to get passed into the data I can see in that hook. Is there any way to do this? I want to give the user an option to tick a box that on save of the entry, it sends some data off to a third party API.


texts:
How do I duplicate content within craft?

I created one article, and dont want to copy paste content from one to the other, or use one article as template for the others.


texts: Trouble finding the correct path to template in custom module and getting the "Unable to find the template" error

texts:
I've created a custom module trying to implement new field types. I'm using How to create custom field type in Craft 3 and https://github.com/mmikkel/IncognitoField-Craft3
as reference on how to structure the module.

However, with a barebones version, I cannot seem to get the correct path to my templates. My module structure has the templates at:

SalesteamModule/src/templates/_components/fields/_input.twig

And the main function is:

public function getInputHtml($value, ElementInterface $element = null): string
    {
        // Get our id and namespace
        $id = Craft::$app->getView()->formatInputId($this->handle);
        $namespacedId = Craft::$app->getView()->namespaceInputId($id);

        // Render the input template
        return Craft::$app->getView()->renderTemplate(
            'salesteam-module/_components/fields/_input',
            [
                'name' => $this->handle,
                'value' => $value,
                'field' => $this,
                'id' => $id,
                'namespacedId' => $namespacedId,
            ]
        );
    }

App.php

return [

    // All environments
    '*'       => [
        'modules'   => [
            'site-module' => [
                'class' => \modules\sitemodule\SiteModule::class,
            ],
            'salesteam-module' => [
                'class' => \modules\salesteammodule\SalesteamModule::class,
            ],
        ],
        'bootstrap' => ['site-module', 'salesteam-module'],
    ],

    // Live (production) environment
    'live'    => [
    ],

    // Staging (pre-production) environment
    'staging' => [
    ],

    // Local (development) environment
    'local'   => [
    ],
];

The module is registered as "salesteam-module" in the app config, so I don't think it's a module id thing. And the path I copied the structure of the Incognito plugin I posted above. Although that repo is a plugin, not a module if that makes any difference.

Not sure where to go from here since I've tried a whole slew of different path combinations.

Thanks


texts: Best practice way to store countries and cities

texts:
Is there a recommended way for storing countries and cities in craft?
I can see fields and categories as obvious options but its difficult to see the disadvantages/advantages of either at the beginning of a project.


texts: my entries have simple numbers as title (1, 2, 3, ... 10, 11 etc.). I'd like to order them naturally and not 1, 10, 11, 2, 3 etc. Is Craft allowing this?


texts:
Interner Serverfehler

Weder Craft\EntryModel noch zugehörige Behavior haben einen Scope "competitionTitel".

what is wrong… it works fine til i delete one point in the menu


texts:
I'm using the SuperTable plugin to create Matrix fields inside a super Table. It's looking great in the front-end but I can't find any documentation on how to template the fields. This is my code so far:

            {% for block in entry.informasjon %}

                {% if block.type == "innhold" %}

                    {% for row in entry.velg1Av3BildeVideo %}

                            {% for image in entry.bilde1 %}

                            {% endfor %}
                            {% for image in entry.bilde2 %}

                            {% endfor %}

                    {% endfor %}

                {% endif %}

            {% endfor %}


texts: loop.index is not returning correct number inside nested loop with inline if conditional

texts:
I'm getting incorrect loop.index results with the following code. It returns "1" for each entry returned. Is there a different way this needs to be written?

{% for order in orders %}
    {% for refund in order.transactions if refund.type == "refund" %}
        {{ loop.index  }}
    {% endfor %}
{% endfor %}


texts: How do you handle routes in CP with Query Parameters?

texts:
I am currently setting up routes for a one-page application. As soon as a Query Parameter is introduced, the route fails. The route "test" replaces "my-av1" in the following photos.

The documentation in Craft does not describe how Query Parameters are handled. How do I proceed from here?


texts:
I'm confused about how to use an uploaded asset in a template (or rather why it isn't working).

1) I create an asset source and folder (Note: I did not add any fields).

2) I added this as a field in my entry fields called heroImage

3) I uploaded an asset to my single entry for the page.

4) I added this to the template

{% for asset in entry.heroImage %}
             {{ asset.url() }}
             XXXX
{% endfor %}

5) I also tried

    {% set assets = entry.heroImage %}
    {% if assets | length %}

Some great assets

      {% for asset in assets %}
          {{ asset.url }}
      {% endfor %}

    {% endif %}

I can see the image on the entry page but the template wont render it.

What could be


texts: Is it possible to use the field layout designer in settings screen?

texts:
I working on a simple inquiries plugin and i want it to use custom element types to manage the inquiries.

I have the basics working but I'm trying to setup the option to add/edit custom fields on the inquiry and thats where I'm running into some issues.  Most of the other examples I'm finding (including Pixel & Tonic's own events plugin) all seem to have a second model that sets up the field layout and passes it to the elements like Calendars -> Events, or Entry Types -> Entries, Category Groups-> Categories.

But what I'm hoping to do is just have one single field layout for all inquiries (more like how users work currently) and ideally this would be editable through the plugin settings (instead of the tab)  is that currently possible?

I can include this:

{% include "_includes/fieldlayoutdesigner" with {
  fieldLayout: fieldLayout
} only %}

but i need to get a field layout somehow? and then hook into the save?


texts: How to use multiple different instances Element API "Load More" button?

texts:
Following up on a previous question of mine:
How to skip the first few entries in a "load more" scenario with Element API?
I have a website that utilizes the "load More" (button) method shown here:
http://craftsnippets.com/articles/infinite-scrolling-and-lazy-loading-with-craft-cms
On my site, I have a homepage that displays the first 6 post in a featured way, then below I have a "more posts" area. In my previous question, I was shown how to deal with skipping the fist 6 posts in the loop of the "load more" area.
However, I want to use the "load more" button elsewhere on the site. Such as:

Category Page – Same as the Homepage, but only showing more entries in whatever category the page is.
Individual Entry Page – In this instance I need the "Load More" area to not skip the first 6 entries.

I can't seem to figure out how use this method in different ways across the site, because the settings for one instance bleeds into the other instances. So, how can I accomplish this? (sorry if this is basic stuff. dealing with API is still new to me)


texts: VAT not being removed when adding a number to businessTaxID

texts:
Folks, just wondering if anyone has further knowledge on Craft Commerce's Tax Rates? I am setting up my first commerce store and the client requires that if the customer is buying from the EU, and has a valid VAT number, they then do not pay the 20% VAT.

I have my Tax Categories, Zones and Rates set up, and have checked the option to 'Don't apply this tax when the shipping address has a valid VAT ID' - however when it comes to the payment screen after putting in a VAT number in the businessTaxId input on the Shipping Address screen, it does not deduct the 20% added VAT. It does pick up the correct Tax Zone as I can see it is EU Tax that has been added, it is just not deducting when I enter a VAT ID.

Just wondering is there something else that I would need to be covering first before this works? Apologies if this is a little too vague.

I am currently running the latest version of Craft & Craft Commerce, and working from the base files that you get when you download.

Edit
I have just noticed this error in the commerce.log file if it helps matters

[Forced] Communication with VAT API failed: MS_UNAVAILABLE


texts: (Commerce) Multiple line items with the same purchasable ID?

texts:
I'm using onPopulateLineItem in my plugin to dynamically set the price of products added to the cart based on user input on the front-end -

$lineItem = $event->params['lineItem'];

$size = craft()->request->getPost('size');
$colour = craft()->request->getPost('colour');
$finish = craft()->request->getPost('finish');

$options = array(
  'size' => $size,
  'colour' => $colour,
  'finish' => $finish
);

$lineItem->options = $options;
$lineItem->price = $dynamicPrice;

This is working fine, however, if the same product item is added to the cart but with different options (and therefor a different price) the existing line item is overwritten with the new values/price.

Is there a way I can create a new line item each time, rather than overwrite the existing one? Do I need to use a different event or create some kind of custom controller?

Thanks!


texts:
I've been able to customize the locale feature for use in a multi-site project, by creating custom locals in /craft/framework/i18n/data. So now each locale has the site name, instead of a language code like "en_au". For example:

veerlofts' => 'Veer Lofts',

instead of:

'ab' => 'Abkhazian',

The problem is, now I can't delete any of the locales (custom or otherwise) in /admin/settings/locales. It gives me this console error in locales.js:

Uncaught TypeError: Cannot read property 'name' of undefined

These older (whether standard out of the box or custom) locales are still defined in /craft/framework/i18n/data.

Another strange thing, if it helps troubleshoot, is that during the first round of trying to customize the locales, the longer custom names were getting truncated to 12 characters, all lowercase.  Those are the ones I'm trying to delete, so the CMS users won't get confused.See attached screen:


texts: How do I export search results as a csv?

texts:
I have set up a custom search of entries on a page in my Craft site which includes filters to filter the results.  I would like to be able to export these results (filtered or otherwise) as a CSV through a link on the page:
http://www.joycefdn.org/grants

Is there a way to do this?


texts: Searching Number Field To See If It Falls In A Range

texts:
I'm building a property search form and searching by different types of fields in Craft.

Here are my questions:

How can I get a list of the unique cities in the entries section to declare my form options?
I'm stuck on searching by square feet.  (see # sf # section in my code) My plan is to let the user select from a few different ranges of square footage. What I was trying to accomplish below is if my search parameter is "sf=1", the field buildingSQFT is searched for numbers in between 10000 and 20000. I would then set up different ranges based on the parameter.

I'm not sure if this is a good way to do this.  Your input has to how to best accomplish this is appreciated.

{% if not craft.request.isAjax %}
{# set base params #}

{% set params = {
    section: 'propertiesSection',
    limit: null
} %}

{% set relatedParams = ['and'] %}

{# status #}
    {% if craft.request.getParam('status') %}
        {% set status = craft.categories.group('propertyStatus').slug(craft.request.getParam('status')) %}
        {% set relatedParams = relatedParams|merge([{ targetElement:status }]) %}
    {% endif %}

{# city #}
    {% set city = craft.request.getParam('city') %}
    {% if city %}
        {% set params = params|merge({'city':city}) %}
    {% endif %}

{# sf #}
    {% set sf = craft.request.getParam('sf') %}
    {% if sf == "1" %}
        {% set params = params|merge({'buildingSQFT':range(10000,20000)}) %}
    {% endif %}

    {# add relatedParams to params #}
    {% if relatedParams|length > 1 %}
        {% set params = params|merge({'relatedTo':relatedParams}) %}
    {% endif %}

    {% set entries = craft.entries(params).search() %}

    {% if entries|length %}


texts: How do I filter a list of entries by the value of a field? For example, if I have a lightswitch field called "Featured", how do I output just the featured entries?


texts:
I have a 'details' rich text field in my User section. How can i get it in my plugin controller in an array.
I tried getting it by

 $userInfo[] = array(
  'username' => $user->name,
  'details' => $user->details,
)

I get an array like this

        Array
        (
        [0] => Array
            (
                [username] => Username
                [details] => Craft\RichTextData Object
                    (
                        [_pages:Craft\RichTextData:private] =>
                        [_rawContent:Craft\RichTextData:private] => Lorem Ipsum is a dummy text
                        [content:protected] => Lorem Ipsum is a dummy text
                        [charset:protected] => UTF-8
                    )
                )
            )


texts:
Having difficulties creating a new user in a custom controller, here's my implementation:

use craft\records\User;

$user = new User;
$user->firstName = $userData['firstName'];
$user->lastName = $userData['lastName'];
$user->username = $userData['loginName'];
$user->email = $userData['loginName'];
$user->password = $userData['password'];

$response = $user->insert();

Response:

SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value
The SQL being executed was: INSERT INTO `craft_users` (`firstName`, `lastName`, `username`, `email`, `password`, `dateCreated`, `uid`, `dateUpdated`) VALUES ('Tristan', 'Gemus', 'registertest@gmail.com', 'registertest@gmail.com', 'password', '2019-03-28 15:53:10', '85468ad6-63cc-499d-baf4-32aaaf55bfb2', '2019-03-28 15:53:10')

The response returns false. Thoughts?


texts:
When I add the company logo it appears aligned to the left with a lot of space on the right side. How can I make it appear to the center?

I know that adding background-position: top center; to the CSS aligns it to the center, but I don't know where I can set this change permanent.


texts:
I want to build a dynamic html select element that includes the prior five years, given the current year. So, since it is now 2020, the result would be:

<select>
<option value="2015">2015</option>
.
.
<option value="2019">2019</option>

Basically want a "loop while" function, but Twig does not do that. I know I did something like this once before with a macro, but can't for the life of me remember and can't find anything on Stack Exchange.

I know I could do it with Javascript, but would prefer to use Twig. Have the feeling I am missing something obvious, just not obvious to me!


texts: Custom element type defineSearchableAttributes

texts:
I have a custom element type with 2 custom fields, 'name' and 'email'.
I can't seem to get the index search working for this element type.
I defined defineSearchableAttributes and returned an array with these 2 attributes.
Searching on the title field works though.

<?php
namespace Craft;

class Newsletter_SubscriptionElementType extends BaseElementType {

public function getName() {
    return Craft::t('Subscriptions');
}

public function hasContent() {
    return true;
}

public function hasTitles() {
    return true;
}

public function populateElementModel($row) {
    return Newsletter_SubscriptionModel::populateModel($row);
}

public function defineCriteriaAttributes() {
    return array(
        'name'      => AttributeType::String,
        'email'     => AttributeType::Email
    );
}

public function defineSearchableAttributes() {
    return array('name','email');
}

public function defineTableAttributes() {
    $attributes = array(
        'title'         => Craft::t('Title'),
        'name'          => Craft::t('Name'),
        'email'         => Craft::t('Email'),
        'dateCreated'   => Craft::t('Date Created')
    );

    return $attributes;
}

public function getTableAttributeHtml(BaseElementModel $element, $attribute) {
    return parent::getTableAttributeHtml($element, $attribute);
}

public function getSources($context = null) {
    $sources = array(
        '*' => array(
            'label'    => Craft::t('All subscriptions'),
        )
    );

    return $sources;
}

public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) {
    $query
        ->addSelect('newsletter_subscriptions.name, newsletter_subscriptions.email')
        ->join('newsletter_subscriptions newsletter_subscriptions', 'newsletter_subscriptions.id = elements.id');
}
}


texts:
Similar to the question asked here:
How to add a tags-field to an entry form?

I am trying to create an entry form that can create tags. I'm using http://selectize.github.io/selectize.js/ for the select element.

I am currently able to submit the form with existing tags but when trying to create a new tag using

$.post('/tags/createTag', data, function(response) {
    if (response.success) {
        alert('Success')
    } else {
        alert('Unable to create that tag.');
    }
});

I get http://talkbox.es:8888/index.php/tags/createTag 404 (Not Found)

Let me know if you guys need any more information, I'll gladly get it for you! Thanks a ton in advance.


texts: PHP Login & Sessions without Craft Commerce?

texts:
I'm trying to implement this tutorial in my Craft CMS site, I've created all the files and they currently reside in public_html, but twig and the .htaccess of Craft CMS is interfering with it.

Does anyone know what the directory structure should look like to integrate this with craft cms or whether it's possible by other methods?

Appreciate any help.


texts: Email notification on field value change?

texts: Currently, I have the need to get an email notification, only when a particular field(s) have changed value. In my use case, a few light switches. Is there currently any way to get notified of this?


texts:
Hello kind helper folk,

I'm working with Simple Craft XML Import, which has a handful of older code in it. I've managed to get through most of it to the very end.

The last thing it does is saves tags. My tags are saved, but now it has to relate it back to the entry and Craft appears to be saving them but not relating them back correctly, and not throwing an error.

The saveRelations function appears to need:

an instance of Craft\FieldModel provided in arg 1

an instance of Craft\BaseElementModel provided in arg 2

.. the data in arg 3.

I have the following code:

                $tagFieldRecord = FieldRecord::model()->findByPk($tagFieldId);

                $tagFieldModel = FieldModel::populateModel($tagFieldRecord);

                $entryRecord = EntryRecord::model()->findById($entryRecord['elementId']);

                $entryModel = EntryModel::populateModel($entryRecord);

                craft()->relations->saveRelations($tagFieldModel, $entryModel, $tags);

Everything appears to have saved in the db tables - tags and the relations, but when I go to the entries in the back end, there are no tags.

Is there a good db value to look in on and change to get these to work?

Also, is there something in my code I can change to make this happen through the code and not hacking the db?


texts: Why if I change ie. drop down value, all entries needs to be resaved to take changes? How can I prevent it?


texts:
I am experiencing incredibly slow site performance. This extends to loading the control panel (/dashboard, /login).

This only happens when I put the site on to my hosting, locally using MAMP it runs quickly.

I have done the following which are recommended in other posts:

upped the memory_limit to 512M
used (% cache globally using key 'entry-' ~ entry.id %}
used eager loading for image assets
Disabled/enabled plugins

Can someone please help?


texts: How to set up CloudFront for a Craft site

texts: I'm now setting myself to learn about AWS. Has anybody documented their experiences with CloudFront and Craft?


texts: Use of localeEnabled(): bug or misunderstanding?

texts:
localeEnabled(false) does not seem to do anything or I'm misunderstanding its use.

I'm on Craft 2.6 and have this code:

{% for region in Craft.entries.section('handle').level(1).localeEnabled(false) %}

This section is a structure with 3 top level categories which are enabled or disabled for certain languages.
If I'm viewing the site in the Spanish locale for example, I'm only seeing the entries that have Spanish enabled, because they're automatically filtered by Craft to my current Locale as is how Craft works.

So I thought, localeEnabled(false) would get all of the entries in all locales.
But unfortunately, it doesn't work...

Is this a bug or do I misunderstand the function of that command? The explanation in the docs really read as if my understanding of the function is correct.


texts: All categories selected by default for an entry

texts:
Is it possible to create an entry, and have all the categories added by default ?

Let's say I have a category called 'materials', with values like 'gold', 'silver', 'copper'... They should all be added to the entry by default, with the possibility to remove them afterwards

Is this possible in Craft ?


texts: Multiple Entry Types on GraphQL Fragment

texts:
So I am building out a Gatsby Site, which is using Craft in Headless mode as it's content source.
In one Section, I have three entry types. Currently they have identical fields, but may diverge in the future.

I currently have built out my template using one entry type, and have a huge GraphQL query to grab the content.
I am now in the process of moving this query into it's own fragment (and possible sub fragments), to keep a separation of concerns.

The current dilemma I seem to have is that I will end up having to maintain three huge fragments.

I know I can grab the type handle, and pass it through to my template and use it in the query as a variable. But the most logical usage to me doesn't work.

Here was my anticpated usage

In template

query getPage($id: [CraftCMS_QueryParameter], $typeHandle: [String]) {
    craftcms {
        entries(id: $id) {
            ...contentPageShape
        }
    }
}

In fragment file

fragment contentPageShape on CraftCMS_contentPage_$typeHandle_Entry {
    metaDescription
    metaTitle
    id
    title
    slug
    body
    ...loadsMoreFields
}


texts:
I'm trying to get a list of users from two different user groups. One user group (premium) must always show first. Whenever the page is loaded, however, the listing of users should show randomly (while keeping premium users at the top of the list).

Also, the listing needs to filter on a particular service which is determined by the entry slug (in the user profiles, that field is set to an Entries fieldtype).

I've been able to get this like so:

{% set thisService = entry.slug %}

{% set premiumMembers = craft.users().group('premium').search('counselingServices:'~thisService) %}
{% set shuffledPremium = shuffle(premiumMembers) %}
{% set basicMembers = craft.users().group('listed').search('counselingServices:'~thisService) %}
{% set shuffledBasic = shuffle(basicMembers) %}

{% set listedMembers = shuffledPremium|merge(shuffledBasic) %}

That all works great, but that of course is an array. I need to paginate the results which isn't possible with an array.

How can I paginate this? Or is there a better way to get the same results in an Element Criteria Model so that I can use the paginate tag?


texts: What do multiple columns of a record being set to unique mean?

texts:
Does the following mean that both columns or the combination of columns needs to be unique?

public function defineIndexes()
{
    return [
        ['columns' => ['productId', 'productTypeId'], 'unique' => true],
    ];
}


texts: How to log info from an onSaveEntry event?

texts:
Having problems logging to the console using log from within an onSaveEntry or onSaveUser event. Just a simple test below, but will be critical for error logs.

public function init()
{
    parent::init();

    BusinessLogicPlugin::log('init');

    craft()->on('entries.saveEntry', function(Event $event)
    {
        Craft::log('onSaveEntry');
        BusinessLogicPlugin::log('onSaveEntry');
    });

}

'init' gets logged fine, but not 'onSaveEntry'. I seem to be able to log other events fine, like plugins.loadPlugins. I have also confirmed that the event is firing via other tests. Is the log function not available when the onSaveEntry event fires? Scope issue? bug? Or am I missing something else? Thanks.


texts: Contact form on form submission redirects to index.twig

texts: I've run into issues with the contact form plugin - https://github.com/craftcms/contact-form/issues/156 - Any ideas


texts:
Working on fixing a lot of deprecated code, enviroment is setup as dev so getting a lot of warnings. Some are easily idetified, others are pretty generic and come from core files. Doesn't show where the issue is... So I have been going through each block template removing code till the page loads to narrow it down.

Example Warning:
strtolower() expects parameter 1 to be string, array given from /vendor/craftcms/cms/src/helpers/Db.php

 $firstVal = strtolower(reset($value));

I have narrowed an existing issue down to the following code from a block template, however I have tried a few different ways but the page will not load with the following code. Anyone know a way to resolve this, it seems to be an issue with the relatedTo

Source of problem? Setting up section

{% for feed in block.feeds %}
    {% if feed == 'all' %}
        {% set data = ['blog', 'caseStudies', 'dataSheets', 'events', 'news', 'webinars', 'whitePapers', 'artices', 'productDemos'] %}
        {% set break = true %}
    {% else %}
        {% set data = data|merge({ (loop.index0):feed }) %}
    {% endif %}
{% endfor %}

Source of problem? Setting up relatedTo

{% for related in block.relatedTo %}
    {% if related == 'All' %}
        {% set reldata = false %}
        {% set break = true %}
    {% else %}
        {% set reldata = reldata|merge({ (loop.index0):related }) %}
    {% endif %}
{% endfor %}

Then Setting up the query seems to be an issue with the section(data) but not sure what needs changed as I do not see a clear deprecation warning, or stacktrace

{% if reldata %}
    {% set tag = craft.tags.title(reldata) %}
    {% set feat = craft.entries.section(data).relatedTo(tag).limit(8).all() %}
{% else %}
    {% set feat = craft.entries.section(data).limit(8).all() %}
{% endif %}


texts: Searching Multiple Categories in Craft CMS

texts:
I have four category groups (Position, State, Status, Denomination). I am trying to create a search form so all four categories can be utilized together or individually.

Here is what I have for my form:

<form action="{{ url('ministry-jobs/results') }}">

<input type="search" name="query" placeholder="What are you looking for?" style="width: 100%;">

<select name="position[]">
  <option value="" selected>-- Select Position --</option>
  {% set positions = craft.categories.group('position') %}
  {% for position in positions %}
  <option value="{{ position.slug }}">{{ position.title }}</option>
  {% endfor %}
</select>

<select name="state[]">
  <option value="" selected>-- Select State --</option>
  {% set states = craft.categories.group('state') %}
  {% for state in states %}
  <option value="{{ state.slug }}">{{ state.title }}</option>
  {% endfor %}
</select>

<select name="status[]">
  <option value="" selected>-- Select Status --</option>
  {% set statuses = craft.categories.group('status') %}
  {% for status in statuses %}
  <option value="{{ status.slug }}">{{ status.title }}</option>
  {% endfor %}
</select>

<select name="denomination[]">
  <option value="" selected>-- Select Denomination --</option>
  {% set denominations = craft.categories.group('denomination') %}
  {% for denomination in denominations %}
  <option value="{{ denomination.slug }}">{{ denomination.title }}</option>
  {% endfor %}
</select>

  <input type="submit" value="Search">

And here is what I have on Results Page:

{% set query = craft.request.getParam('q') %}
{% set position = craft.request.getParam('position') %}
{% set state = craft.request.getParam('state') %}
{% set status = craft.request.getParam('status') %}

{% set homeGrownParam = craft.request.getParam('homeGrown') %}
{% set preparedProduceParam = craft.request.getParam('preparedProduce') %}
{% set redTractorParam = craft.request.getParam('redTractor') %}

{% set positionCat = position ? craft.categories.group('position').slug(position).find() %}
{% set stateCat = state ? craft.categories.group('state').slug(state).find() %}
{% set statusCat = status ? craft.categories.group('status').slug(status).find() %}

{% set positionParam = positionCat ? {targetElement: ['and']|merge(positionCat)} %}
{% set stateParam = stateCat ? {targetElement: ['and']|merge(stateCat)} %}
{% set statusParam = statusCat ? {targetElement: ['and']|merge(statusCat)} %}

{% set relationParams = [positionParam, stateParam, statusParam]|filter %}

{% set entries = craft.entries({
    section: 'ministryJobs',
    relatedTo: relationParams ? ['and']|merge(relationParams) : null,
    search: query,
    homeGrown: homeGrownParam,
    preparedProduce: preparedProduceParam,
    redTractor: redTractorParam
}) %}

{{ entry.postDate.format("m/d/y") }}

{{ entry.position }}

{{ entry.church }}

{{ entry.city }}

{{ entry.state }}

I am getting no results. I am not sure what I am doing wrong. Any help is greatly appreciated.


texts:
I am having a syntax error on my craftCMS website. Hoping someone could help me.

  Parse error: syntax error, unexpected '[' in /home16/puresoci/public_html/dev/craft/plugins/charge/ChargePlugin.php on line 14

Here's the line that it is referring to

  craft()->templates->hook('charge.prepCpTemplate', [$this, 'prepCpTemplate']);

Here's the whole function

public function init()
{
    craft()->charge_license->ping();

    if (craft()->request->isCpRequest()) {
        $this->includeCpResources();
        craft()->templates->hook('charge.prepCpTemplate', [$this, 'prepCpTemplate']);
        craft()->templates->hook('charge.prepCpSettingsTemplate', [$this, 'prepCpSettingsTemplate']);
    }
}

But I am a beginner on using PHP and I dont know how should I update this. I am using PHP 5.6 right now.


texts: Custom ElementType empty getSource criteria?

texts:
I'm trying to add a source on a custom element type that shows entries with an empty assigned_user_id field. This criteria is not honored and returns the same results as the "All Entries" source. Is there any way to specify a null or empty string criteria value?

public function getSources($context = null)
{
    $sources = [
        '*' => [
            'label' => Craft::t('All Entries'),
            'defaultSort' => [
                'test_plugin.dateCreated',
                'desc'
            ]
        ]
    ];

    $sources[] = ['heading' => 'Assignments'];

    $sources['unassigned'] = [
        'label'    => Craft::t('Unassigned'),
        'criteria' => ['assigned_user_id' => '']
    ];

    return $sources;
}


texts:
Using Craft::Pro Edition, I want to add a specific UserGroup to an existing User in my module. I tried it this way, but the group is not saved.

$userGroup = Craft::$app->userGroups->getGroupByHandle('partner');
$user->setGroups([$userGroup]);
$success = Craft::$app->elements->saveElement($user);

After (successful) saveElement(), $user->getGroups() still returns an empty array.

When I add the group in the Admin CP, it works, but it needs a password confirmation.


texts: Get label from value in radio buttons list fieldtype

texts:
Ok I know how to list radio buttons and use it to display a particular value:

{% set newsType = craft.fields.getFieldbyHandle('newsType') %}
{% for option in newsType.settings.options %}
    {% if option.value == 'newsValue' %}

{{  option.label }}

    {% endif %}
{% endfor %}

(I am not in an existing entry context.)
So I would like to know if there is a shortcut to directly get this label from the value? Like that syntax :

{% set newsTypeLabel = craft.fields.getFieldbyHandle('newsType').option('newsValue').label) %}


texts:
Is it possible to build something like this with a structure and the {% nav %} tag?

         Dropdown

                    ...

This is my code for now:

{% set entries = craft.entries.section('pagina') %}

      {% nav entry in entries %}

            {{ entry.title }}

            {% ifchildren %}

                  {% children %}

            {% endifchildren %}

      {% endnav %}

The problem is, i need custom html inside the children


texts: Craft CMS security scans: upload of over-the-limit file hangs the system; should it throw exception/error?

texts:
We are putting our new Craft CMS 3.2 install (dev environment) through some security scan paces, including uploads of 500Mb files. We'd expect to throw an exception message/error page on an over-the-limit file, but it is not doing that currently (it simply hangs).

When we run these scans against other CMS applications, when the upload is attempted, an error is thrown by the web server and the underlying CMS applications continue to function as they should as do the actual scans. This is not the case when it comes to Craft.

To pass the security scan, we'd like Craft to throw an error, not just 'hang.'

  If Craft is hanging or timing out while you’re uploading a large file,
  or if you get the error message “The uploaded file is empty”, you’re
  probably running into a limitation imposed by your server’s
  configuration.
  https://craftcms.com/guides/troubleshooting-unsuccessful-file-uploads

Our PHP Info:
memory_limit    512M;
upload_max_filesize 256M


texts: Datagrab style plugin for importing CSV data to sections (Channels)

texts: I use Datagrab on an EE site to import data to a Channel/fields and category assignment – is there an equivalent plugin or approach for Craft CMS, typically I want to allow the editor to import wine lists and display as listing pages (category title via EE e.g Burgundy) and click throughs from here to entry pages


texts: 404 Error for assets where "Base URL" and "File system path" are different

texts:
I am new to Craft 3 and I have seen similar questions asked many but never answered.

I want to store my images in a directory that is not public, yet I want them to be served correctly by Craft. The reason why I am doing this is that I work with shared disks for EC2 instances in AWS (Not S3) so I need to be able to mount shared volumes to store images for all the Front Ends to serve.

I am experimenting (without mounting a disk, to simplify) and I have a volume with:

name: images
handle: images
Assets in this volume have public URLs: on
Base URL: @web/somestuff
Volume Type: local folder
File System Path: /var/www/mydomain.com/imagesrepo

Note that the directory /var/www/mydomain.com/imagesrepo has 777 rights, images are uploaded correctly in the CMS, and even "image transform" correctly creates subdirectories and resizes images. I see the images thumbnails but, following the problem explained below, the image shows a broken  when I click on "preview".

Also note that in the directory tree, imagesrepo is outside the website root, at the same level with the "web", "config", etc... directories for Craft. (/var/www/mydomain.com/web is the website root)

I have installed "element api" and I am getting the URL of the image with

$img->getUrl(),

and a "resized" version with

$img->getUrl('largepic').

The result URLs I am getting are

https://mydomain.com/somestuff/2013-12-22-23.46.18.jpg
https://mydomain.com/somestuff/_largepic/2013-12-22-23.46.18.jpg

The URLs look correctly built and I would expect that, once called, Craft would fetch the image file with the actual disk location in /var/www/mydomain.com/imagesrepo and read it out to the front end. Instead I get a 404 page with

HTTP 404 – Not Found – yii\web\NotFoundHttpException

and the whole stack trace, as if Craft was trying to find "somestuff" as a regular template.

Am I doing something wrong or is Craft not able to store assets in a physical location and serve them from a logical one?

P.s. Please do not tell me that there are drivers and plugins for AWS solutions. There are many reasons to store assets in physical locations that differ from the URL


texts: How do I do routing for something like {city}/pricing, {city}/how-it-works, etc. while loading the same template and dataset?

texts:
I'm trying to set up a site for clients that have locations in multiple cities and who want to be able to display something specific to that location on certain pages. I would like to set up routes using the city name as a variable, followed by the page (i.e. mysite.com/chicago/pricing, mysite.com/boston/pricing, etc.), and have it route to the same section and template with all of that section's corresponding entry fields.

I was planning to grab the URL parameter as a variable that enables me to dynamically load content based on a simple string match for that variable. I want to do something like this

{% set location = matches[1] %}

{% if not location %}
  {% set selectedLocation = locations.defaultLocation %}
{% else %}
  {% set selectedLocation = location %}
{% endif %}

....

{% for plan in entry.pricingPlans %}
    {% if plan.location == selectedLocation %}
      ...
    {% endif %}
{% endfor %}

I can route to the template itself just fine, but I don't get the data. Any suggestions on how best to achieve this? I'm not very PHP savvy and have only recently started getting to more advanced tasks in Craft.


texts: What other properties are in the "entry.image" object?

texts:
So this may be a stupid question, but I've sort of never wrapped my head around it. When fetching an image from an entry -- even if there's only one associated with the field -- you can't just do:

{% set image = entry.image %}

You have to say:

{% set image = entry.image.first() %}

Which implies that the returned data are an object or array, and that the actual desired image is the "first" item in it. My questions are:

Why is it structured this way?
Which other properties are in the entry.image apart from the actual resource itself? What would you use those for?

I realize this may be obvious to pro Craft developers, but I remember the first Craft site I ever built, I had a devil of a time trying to remember that!


texts: PHPUnit - Warning: "Header already sent"

texts:
I'm trying to cover the plugin controller with unit tests, but when I try to run phpunit this error shows up:

  Warning: Cannot modify header information - headers already sent by (output started at /craft/app/vendor/phpunit/phpunit/src/Util/Printer.php:172 ) in /craft/craft/app/helpers/JsonHelper.php on line 25

The same error indicates also line 26 and 27 of JsonHelper.php

Did someone already had this issue? Can somebody help me on this?

Thank you very much.


texts: Trying to display post based on two variables

texts:
I am setting three variables like so ...

{% set featureEntryIds = craft.entries({ section: 'blog', featurePost: 1, limit: 1 }).ids() %}

{% set articleClass = entry.id in featureEntryIds ? 'featured' %}`

{% set featuredPostLayout = entry.featuredPostLayout == 'subtleBar' or 'largeFeature' %}

Then I am trying to use a conditional to display posts where the featurePost lightswitch field is true

AND

featuredPostLayout radio field is either subtleBar or largeFeature

{% if articleClass and featuredPostLayout %}

{% endif %}


texts:
I've got a Matrix field with an image. If I use a pre-defined transform that's defined in Assets everything works fine. However, I need to set a transform manually in the template but it keeps returning an error "The transform “wideCrop” cannot be found!". I have used transforms in templates all over the site that work fine so I'm puzzled why this particular one isn't working.

This is from an embedded template inside the entry:

{% for block in entry.contents %}
    {% for image in block.image %}

        {% switch block.position %}
            {% case 'full' %}
                {% set wideCrop = { width: 940, height: 360, mode: 'fit' } %}
                <img class="full" src="{{ image.getUrl('wideCrop') }}">
        {% endswitch %}

    {% endfor %}
{% endfor %}

Thanks in advance!


texts:
in a multilingual site, how can i place multilingual links to content.

i.e. in the footer i would place a Imprint but in anohter language the slug might be /de/germanImprint...is there an easy helper to always get the right url from the english slug?


texts:
I have a dev server and a production server, they are on two different databases. The editors will only be logging into the production space to add content. I'm looking for an easy (but still manual) way to export content. I rather not do an entire database dump every time.

Any thoughts?


texts: Looping through images in a Asset field type

texts:
Sorry, this is kind of a newbie question, but I can't figure out how to loop trough all images in one image asset field supporting multiple images.

The only way I have been able to output anything without an error, is this:

{% set asset = entry.wireframeImages.first() %}

{% if asset %}
    {{ asset.url }}
{% endif %}

But as you can see, only the first image is printed out.

How can I loop trough all images from this field?

I have been reading trough this page, but can't figure out how to do this simple task.

Thanks


texts: We recently moved the site from one domain to another domain (development to staging). I am able to login to control panel and see the fields and sections but when I go to entries, i dont see any entry in there. Any help is appreciated.


texts:
Hi got past the username etc screen for install but stuck on the 'oops' screen?
I've tried again and again but same deal, checked db settings just not getting past this, assuming the oops means it can't connect to the db but if the details are correct (I have a pw with its own un and pw with privs for that) and tested with root root, any ideas – seems most people are having no probs with this, then tried logging in and ok, why would it hang do you think on oops when seems to have installed?


texts: How to use sprite sheets effectively and responsively in Craft

texts:
I'm planning for a site which will use a number of small image elements, which leads naturally to looking for first-load speedups by using sprites.

Since the site will be responsive, it will need the sprites to resize.

One way would be to let Craft do the resizing; might work well enough.
the offsets would also be very nice to find re-aligned with the resized sprite locations. I think I am probably talking about a feature request here. Maybe it could be as simple as a conversion function, cached results or not.
another possibility would be to allow Assets to specify their own non-generated images for given Transform labels. Maybe by a middle-extension that named the tranform, if not a tranform folder solution?

Ok, I think this is all dreamland for now, but might spark some thinking. I'm considering it because I think I'm realizing that the delay times for later than first images which show even on a Pingdom are probably due to limited sockets for browsers, or a modeled equivalent in the monitoring service if they are not just using Webkit contents for this.

Something to think about, or if someone has an answer I don't know about.


texts: how to includeJsFile in head instead of body

texts:
I am using this code to include a js file, but it adds to the <body>:

{% includeJsFile '/path/script.min.js' %}

I need to add it to the <head> instead, how can I do?


texts: Resolving the $entry variable for custom routes somewhere but a Twig template

texts:
I have several custom routes defined on the routes.php and, as usual, I am resolving the value of the template's entry in the Twig template when it is not defined (which is when it doesn't match a Craft Route) but I'd like to do it somewhere else before it reaches the template because I want to remove the logic in Twig.

Can I add a method to be executed before last Craft's renderTemplate($template, $variables) in which I would resolve and add $entry to $variables when it's not defined? What's the way to go?

Thank you :)


texts: Calling a plugin function after an entry is deleted?

texts:
Is there a way to call a custom function after an entry is deleted successfully?

If there isn't, is there a record of the deleted record stored anywhere?

Currently, I am thinking of editing the actionPerformAction in elementIndexController, but I don't want to edit the application files, so if there is another method I would prefer that.


texts: Image and italics issues in Rich Text editor since 2.5 update

texts:
In addition to the lack of image resizing and the odd extra spacing, the latest Redactor implementation also lacks support for aligning images left or right.

I've also discovered any text that was previously italicized by the previous text editor disappears when rendered in the new one. If the entry is saved with the new text editor in place, all previously italicized copy disappears.

Until this implementation is remedied, I've plugged the earlier version of Redactor into this instance to stem client complaints. Doing so completely disables image placement and Live Preview, but it beats the alternative.

Is this the correct route of action in order to restore this functionality, or is there a better way? Please advise.


texts:
Hello Craft community,

My team and I have built a site for a client and it looks great.  The site runs just fine in my developers local environment and we're all very happy.  I have the site now set up on my preproduction Red Hat environment and when I access it there is about 30 seconds of latency, every single time.  I cannot figure out where this latency happens, perhaps there is a configuration somewhere I am missing?

I can access images, js files, etc. without any issue - but once I hit a php file in the Craft environment, things are super slow.

I tried turning the devMode flag to false in the general configurations and that didn't seem to help.

This has nothing to do with my browser - I've tried a straight CURL to the URL and I see the same amount of lag.  Perhaps there's some server-side caching I need to enable?  Like I said - this is not just with my site, it was slow during the install as well as when I just access the admin tool to look at/change configurations.  Please help!


texts: What do the values in /admin/utils/phpinfo mean?

texts:
When two values are displayed for PHP Info, what does that mean? For example,

Why the two values?


texts: How can I configure multi-site base URLs where the subdomains are static but the domain name is dynamic?

texts:
For example, let's say I have two sites: abc.example.com and xyz.example.com but I want to also host test versions of those sites at example-test.com.
It'd be nice if I could set the baseURLs to http://abc.$DOMAIN and http://xyz.$DOMAIN and then set the env var DOMAIN on the server (or something similar), but Craft currently only supports setting base URL to an env var if that is the entirety of what it is set to.
I'm not interested in creating an env var per subdomain.
Any ideas?


texts:
Every time I try to run an update, I get these errors. Installing plugins won't work either. I'm using Media Temple / Grid server hosting. I've increased the file size limits in php.ini as well. But I'm at a loss.
Status: Internal Server Error

Response: PHP Fatal Error 'yii\base\ErrorException' with message 'Out of memory (allocated 226500608) (tried to allocate 4096 bytes)'
in /nfs/c07/h01/mnt/179491/domains/bluepearl.villas/vendor/composer/composer/src/Composer/DependencyResolver/RuleWatchGraph.php:52
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleFatalError()
#1 {main}


texts: How to route to a controller action in Craft3?

texts:
Before I get tagged as a duplicate I have already tried everything in the 'duplicate' issues on here to no avail so I'm posting my exact config to see what I'm doing wrong.

Here is my plugin code and my controller code

// My plugin and init funciton
use belniakmedia\sitedominjector\controllers\DefaultController;
class SiteDomInjector extends Plugin
{
    /**
     * @var SiteDomInjector
     */
    public static $plugin;

    /** @var array */
    public $controllerMap = [
        'default' => DefaultController::class,
    ];
    public function init()
    {
        parent::init();
        self::$plugin = $this;

        // Register our site routes
        Event::on(
            UrlManager::class,
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
            function (RegisterUrlRulesEvent $event) {
                $event->rules['echo'] = 'site-dom-injector/default/index';
            }
        );
    }
}

// My Controller
class DefaultController extends Controller
{
    protected $allowAnonymous = true;

    public function actionIndex()
    {
        $result = 'Welcome to the DefaultController actionIndex() method';
        return $result;
    }
}

I really don't know if that controller map is necessary or not but one of the posts on here said they got it to work setting that up, so thats what I did.

Here is a photo of my plugin's file structure for continuity:

I really have no idea why this isnt working but no matter what I do, when I try to browse to http://site.local/echo I get a 404 not found and the trace seems like its not even attempting to load the controller and is just looking for a matching template file... :(

Any ideas?


texts: Craft 3 add Simple Map in entry through plugin

texts:
I am trying to fill in lat/lng data in the Simple Map field of an entry through a plugin. All information from entry is saved except for Simple Map. Apparently I am doing something wrong there.

Here is my code:

$entry = new Entry(); // use craft\elements\Entry;
$entry->.... // set fields
...
$entry->setFieldValues([
    'otherFields' => $value,
     ...
    'mySimpleMapFieldName' => [
       'lat' => 52.27, //$location['lat'],
       'lng' => 0.51 //$location['lng'],
]);
Craft::$app->elements->saveElement($entry);