texts: Errors after Upgrading from 3.0.35 > 3.041

texts:
I ran the updater from the Admin (local install.)
After a few minutes, the update failed.

Now when I try to load the site:

Warning: require(C:\Users\rickn\Documents\Craft\Projects\Untye/vendor/craftcms/cms/bootstrap/web.php): failed to open stream: No such file or directory in C:\Users\rickn\Documents\Craft\Projects\Untye\wwwroot\index.php on line 20

Fatal error: require(): Failed opening required 'C:\Users\rickn\Documents\Craft\Projects\Untye/vendor/craftcms/cms/bootstrap/web.php' (include_path='.;C:\php\pear') in C:\Users\rickn\Documents\Craft\Projects\Untye\wwwroot\index.php on line 20

There is no "vendor/craftcms/cms" folder

Is there a way to manually update an existing install? I don't see that option in v3 update instructions.


texts:
Is there a way to add the validator strings into the translations?

$message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');

/* craft/app/validators/CRequiredValidator.php - line 70 */

I'd like to translate that text without changing any of the code (which might be overwritten and lost with an update)


texts:
When looping through a matrix, is there aquick way to check whether or not the block has a particular field (not if the field is empty, but if the field exists at all).

I have a matrix with ~20 block types, 12 or so have a field called blockTitle. For in-page nav, I'd like to loop through all the blocks and just output blockTitle for those that do have it. I could do this with a conditional for block.type, but am wondering if there's a simpler check (in case we add more block types in the future, don't want to have to update the conditional every time).

Using {% if block.blockTitle %} will kick back "Craft\MatrixBlockModel and its behaviors do not have a method or closure named "blockTitle"." for block types without that field, so that's a no go.

Tks.


texts: Craft console app within windows batch script

texts:
I try to create a simple deployment batch script that would work on windows.

To do that, I need to interact with Craft console app. How do I pass multiple commands to it to perform installation?

I tried this:

(echo mysql && echo localhost)|craft setup

This in theory should answer two first questions that craft console asks during installation. Unfortunetly it just caused console program to be stuck in some kind of loop when first question about the database is repeated infinitely.


texts:
I am trying to change all rgb colours in a bit of text/content. I have the RegEx working here in php using preg_replace:

preg_replace("/#[a-zA-Z0-9]{6}|rgb\((?:\s*\d+\s*,){2}\s*[\d]+\)|rgba\((\s*\d+\s*,){3}[\d\.]+\)|hsl\(\s*\d+\s*(\s*\,\s*\d+\%){2}\)|hsla\(\s*\d+(\s*,\s*\d+\s*\%){2}\s*\,\s*[\d\.]+\)/", "*****", $input_lines);

https://www.phpliveregex.com/p/oc2

But cannot seem to get it working in craft template code am trying is like this:

{% set svg_image = '
#ffffff
#ffffffasdf
asdf#ffffff
rgba(170,221,255,0.59)
rgba(170,221,255,0.59)asdf
rgb(0, 0, 0)
rgb(33, 44,66)
rgb(0,0,0)asdf
rgba(170,221,255,0.59dsaf)
' %}

{% set svg_image_output = svg_image|replace({ '/#[a-zA-Z0-9]{6}|rgb\\((?:\\s*\\d+\\s*,){2}\\s*[\\d]+\\)|rgba\\((\\s*\\d+\\s*,){3}[\\d\\.]+\\)|hsl\\(\\s*\\d+\\s*(\\s*\\,\\s*\\d+\\%){2}\\)|hsla\\(\\s*\\d+(\\s*,\\s*\\d+\\s*\\%){2}\\s*\\,\\s*[\\d\\.]+\\)/': '****' }) %}
{{ svg_image_output | raw }}

I have:
 - added double-escaped '\' as the docs suggest in v2
 - started with / and ended with /

Seems in the docs that if this is done it works like preg_replace.

Any ideas?


texts: Showing products from many categories becomes very slow

texts:
We have 8000 products imported in the database, with a few 100 categories, sometimes up to 4 levels deep.

What we try to do is that when a user clicks a main category, we show 4 random products of each subcategory (but only for it's direct children).

This is about 10 subcategories, that are directly under each main category. Though I imagine the relatedTo digs as many levels deep as it can.

The code works, but it takes 15 seconds before the page is loaded, so this is not workable.

I'm quite sure it might be the relatedTo tag that slows it down.
Plus it also seems that when using relatedTo and a limit parameter together, that limit just gets ignored, and it seems he's grabbing all records?

Here's the code:

{% set categories = craft.categories.group('pharmacyCategories').descendantOf(category.id).level(2).order('catDisplayName') %}

{% for subcat in categories %}

    {% set productsSubCategory = craft.commerce.products.relatedTo(subcat)  %}

{{ subcat.catDisplayName }} ({{ productsSubCategory.total }})

    {% for product in productsSubCategory.limit(4).order('RAND()') %}
        {% if product.variants|length %}
              {{ product.title }}
        {% endif %}
    {% endfor %}

{% endfor %}


texts: Editing error messages and allowing a phone number input in a P&T Contact Form

texts:
Firstly, thanks very much for the help I've already had from members here. It's been straightforward and easy, even for a newbie like me, to understand.

At the moment, I'm working on editing one of the last pages on a client's site, the Contact Us page and am hoping to be able to use the Pixel & Tonic, Contact Form plugin. But, after some inspection of the Readme and the files that run the plugin, I have been unable to find the following:

1) How do I create/edit the error messages that the form generates?

2) Can I use the form to allow a user to enter their phone number? If so, what should the code look like in the template?

I would like the final form to look like the screenshot below.

Any help that anyone can provide would be most appreciated.

With kind regards,

Mark

EDIT

Thanks to this post, I've realised how easy it is to add a new field for the phone number (and assume I add the code wherever I want the new field to appear(??)), but am still clueless about the error messages.


texts: How do I setup a password administration workflow using setPasswordPath and a forgot password page?

texts:
I have a couple of issues regarding administering users passwords from the front-end of my site.

Firstly, I'm trying to implement the Set Password form as listed at https://craftcms.com/docs/templating/set-password-form.

I have created a single pointing to the path specified in the setPasswordPath config entry, using a template containing the above form. However, when I navigate to the setPasswordPath page it is erroring saying that 'Variable "code" does not exist'. When I remove the hidden code field, the id variable errors in the same way.

Secondly, the forgot password form listed at https://craftcms.com/docs/templating/forgot-password-form works great, except for when the user navigates to the link in the e-mail, and then enters their new password, they are redirected the Craft dashboard login, which a lot of the end users should never really see. Is it possible to redirect people  to my home page login form on the front-end?


texts: How to send email to user when we change his group?

texts:
I have some user groups with different permission and I need to notify them by email when i switch them to another group.

Is there a way to make it automatic by a plugin or via the code directly?


texts: Setting valueless boolean attributes with the tag function

texts:
When using the tag function, how does one handle valueless attributes which could also be null?
For example, it's great we can do…
{% set idVar   = 'idstring' %}
{% set nameVar = 'namestring' %}
{% set typeVar = 'typestring' %}

{{ tag('input', {
    id: idVar,
    name: nameVar,
    type: typeVar
}) }}

…to generate:
<input id="idstring" name="namestring" type="typestring">

But what about if the required attribute is also a variable? We can’t do:
{% set reqVar  = '' %}

{% if field is required %}
    {% set reqVar = 'required' %}
{% endif %}

{{ tag('input', {
    id: idVar,
    name: nameVar,
    required: reqVar
}) }}

…because if reqVar is empty, one would want the required attribute to not be written at all. To generate:
<input id="idstring" name="namestring" type="typestring">

…and not:
<input id="idstring" name="namestring" type="typestring" required>

The same thing applies to other boolean attributes like hidden.
Is there a way to do this with this function? What am I missing or not getting?


texts:
I'm using the Search Plus plugin with Craft, it's been a great help!
I have 2 questions I need help with, as the Search Plus docs are not too clear so far:

I have a search page with filters (facets) in place, however these
facets are arranged according to search count by default. I want to
sort them by alphabetical order instead, and I've seen that it is
possible with Algolia, but I need help to do that with Search Plus.
Upon clicking on a filter checkbox, the other filters disappear. How
do I trigger them to still appear but with a different CSS class
applied?


texts:
I'm trying to search through a set of results inside a Matrix field. Craft is giving me this error message: Craft\EntryModel and its behaviors do not have a method or closure named "avdelinger".

When I searched the information without the Matrix field it worked but now it's not. I'm using the smart map plugin to find the nearest office added in my Matrix field. Here's my code:

{% block content %}

<form action="">
    <input type="search" name="sted" placeholder="Search">
    <input type="submit" value="Go">
</form>

{% for block in entry.avdelinger %}

{{ block.navn }}

        {{ block.sted.street1 }}

        {{ block.sted.city }}, {{ block.sted.zip }}

        Latitude: {{ block.sted.lat }}

        Longitude: {{ block.sted.lng }}

{% endfor %}

{% set target = craft.request.getParam('sted') %}
{% set params = {
    target: target,
    range: 1000,
    units: "kilometers"
} %}

{% set blocks = entry.avdelinger(params).order('distance').find() %}

Showing results for "{{ target }}"

{% for block in blocks %}

        {{ block.sted.street1 }}

        {{ block.sted.city }}, {{ block.sted.zip }}

        {{ block.sted.distance | number_format(2) }} kilometers away

{% else %}

No results found

{% endfor %}

{% endblock %}

Thanks!


texts: Is it already built-in in CraftCMS to make multiple editableTable in a CP page? The behaviour would be similar to Matrix field where you add a matrix block, the matrix block appears. What I want is that instead of the matrix block, editableTable appears. Is it possible?


texts: Show matrix fields based on quantity [Sprig]

texts:
I'm using Commerce to sell tickets to an event and need to get the names of each person. I would like to do this via a Matrix field, showing fields based on the quantity selected.
I followed along with the new Sprigform tutorial, which covers part of it but it has an add button as opposed to a dropdown.
This is what I have so far, but on changing the select value the input field disappears, so maybe I'm just looping over things incorrectly?
{% set qty = qty ?? [['']] %}
<select sprig name="qty">
  {% for i in range(1, 5) %}
    <option value="{{ i }}" s-val:qty="{{ i }}" {{ qty == i ? 'selected' }}>{{ i }}</option>
  {% endfor %}
</select>

{% for guest in qty %}
  <input sprig type="text" name="options[guests[{{ loop.index0 }}][0]]">
{% endfor %}

Would appreciate any pointers!


texts:
I currently have the following code as part of the address form in Craft Commerce.

        First Name (*)
        <input type="text" id="{{ modelName }}-firstName" {% if model and model.getErrors('firstName') %}class="has-error"{% endif %} name="{{ modelName }}[firstName]" value="{{ model ? model.firstName : '' }}">
        {% if model and model.getErrors('firstName') %}

                <svg role="img" class="icon" title="Error Icon">
                    <use xlink:href="/assets/img/icons.svg#icon-error"></use>
                </svg>
                {{ model.getError('firstName') }}

        {% endif %}

This repeats several times for each form item (surname, address1, address2, postcode, country etc).

I also want to reuse the error code part for other areas on the website, when errors occur, be this discount code box, login form etc.

    <svg role="img" class="icon" title="Error Icon">
        <use xlink:href="/assets/img/icons.svg#icon-error"></use>
    </svg>
    {{ model.getError('firstName') }} //This part will change based on application.

My question is how can I extract this part to ensure it is DRYer and not repeat it over and over? So if I want to change the class, the icon etc, I won't have loads of separate pieces of code to update.


texts: Let's start with this I have Jobs, which would be added from the front end and backend as well, thouse jobs have to have Clients and Workers attached to them, which are basically users with differnt fields, the workers they have to have ability to login in the system, the clients maybe too in the future, that's why I would like to ask which will be the best way to accomplish this? I did some basic plugins in craft, but this one is more complicated and I woud like to ask for the best way of doing it. I was thinking if it's possible to use UserElementType to accomplish this.  I'm very new in craft so some plugin or some code snipped would be veryhelpful for me thanks in advanced!


texts: Is there any way to adjust the width of the custom field in the admin panel?

texts: I want to adjust the width as ( 25%, 50%, 75%, or 100%) of the custom field in the admin panel.


texts: Can SEOmatic pull from a Category Field to fill Entry - SEO Keywords or SEO Description?

texts:
Under SEO Entry Meta...

How do you set SEO Description and SEO Keywords?

I see that they can pull from Text, Rich Text, Tags and Matrix fields, can they pull from a Category field?


texts: How to render a state abbreviation in Craft Commerce?

texts:
Folks, this has to be easier than I've made it. In a front-end template, how do you grab a state abbreviation from a customer's address in Craft Commerce?

{$ set addresses = craft.commerce.customer.addresses $}
{% for address in addresses %}
  <-- this is where I want to show the abbreviation -->
  {{ address.state.abbreviation }}
{% endfor %}


texts: Local install does not start, PDO Exception

texts:
I wanted to install a single instance of craft on my local machine. However upon starting the installation via calling /admin/ or /admin/install, the only message I get, is

  SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
  The SQL being executed was: SHOW TABLES LIKE 'craft_%'

Which in itself is weird, since I have modified the configuration already to not use craft_ as a table prefix.

These are my settings:

OS: Mac OS X 10.11.3 (El Capitan)
PHP 5.6.25
MySQL 5.7.14
Apache 2.4.16
Latest Craft 2 build from today / Latest Craft 3 build from today

I have made the following changes to the configuration:

craft/config/db.php:

return [
    '.local' => [
        // The database server name or IP address. Usually this is 'localhost' or '127.0.0.1'.
        'server' => '127.0.0.1',

        // The database username to connect with.
        'user' => 'root',

        // The database password to connect with.
        'password' => '',

        // The name of the database to select.
        'database' => 'craft_cms',

        // The prefix to use when naming tables. This can be no more than 5 characters.
        'tablePrefix' => '',
    ],
];

craft/config/general.php:

return [
    '.local' => [
        'devMode' => true,
    ],
    '*' => [
        'omitScriptNameInUrls' => true,
    ],
];

I even went the extra mile and updated the my.cnf for mysql in order to work properly in 5.7:

[mysqld]
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Any suggestions?

Edit Since the mods removed the craft3 tag due to my typo, I thought it was necessary to say that this error occurs on both the latest version of craft3 and craft2.


texts:
I would like to create a plugin/function to move all unused assets (which are not related to a entry) to a specific folder in the same assets source. Now i try to create the function to move a single file by referring the id of the file. But i get always errors... The function should look like this:

public function moveFileToFolder($fileId,$idOfTargetFolder,$assetSourceId) {
 ....
}

Thanks for any help!


texts: Craft CMS Database Structure and Schema Schematics

texts:
Is there somewhere that we can find a the schematics of crafts database structure/schema. We  are looking into developing a database migration workflow between development and production environments.

Thanks


texts: How to compare just the date part of a dateTime field?

texts:
Ok I want to list event entries based on the start date of those events.

I have a route set up which provides the date in the same format as held in the start date field. But trying to compare this with:

{% for entry in craft.entries.section('events').startDate(date) %}

to pull out only entries for the specified date fails as the date variable only holds the date portion of the startDate field i.e. 2015-10-02 and not the time segment.

So is there some way I can format this call so that the comparison is like with like without the time segment. I have tried a few things with filters but nothing is working.

Cheers


texts: Related entries from level 2 in structure

texts:
I'm building a property developers website and it has a carousel at the bottom of the individual property pages, in which I want to show five other related properties from the same group in the structure and not the entry on the current page also.

This is what I have currently in the code:

{% for nextSibling in craft.entries.section('availablehomes').limit('5') %}
...content...
{% endfor %}

However, I've tried many different ways suggested, but I can only get it to show the current property in a continuous loop. So need some help please.

I've attached a screen shot of the carousel and the structure below.

So to clarify, when I'm in the page that's in Lockeswood / Plot 1, I'd like to show the other plots that are under it in the structure, and then if that is less than 5, I'd like it to include the next plots from level(2) in the structure to make it 5.

Cheers

Update:

I've now got it to show entries listed after only, but still need it to show the entries within the relevant group in the structure first before showing other groups entries.

{% set var = craft.entries.positionedAfter(entry).level('2') %}
{% for entry in var.limit('5') %}

{{ entry.parent ? entry.parent.title }} - {{ entry.title }}

{% endfor %}

Which is outputting the following for Lockeswood / Plot 1, however, the Plot 2 page would not include Plot 1 in it's list as it's now only show entries after the current entry and not the whole group.


texts:
Does anyone know if you can work with releatedTo between categories? I’d like to get all the categories in a categories.groups that are related to a single category

I have some entries in a channel, lets call it parts. The parts have two categories from two separate groups.

Group 1 is partType which has the categories engine interior and transmission
Group 2 is manufacturer which has the categories ford and chrysler.

On the category-page for ford, i’d like to list all the parts in the ford category, grouped by partType

But I don’t wand to show the partType categories that have no parts by the current manufacturer


texts: How can I pass a JS result into a Twig template?

texts:
I've got a frontend form which queries the openstates.org API to return a given set of data objects.

Those objects also exist in Craft as entries, and the API data includes a field that serves as a unique ID for the Craft entries - how can I pass those unique IDs back to the Craft template to retrieve the corresponding entries?


texts:
Just ran into this error while developing a plugin.  Not doing much of anything special, just editing and renaming a few templates.

What could cause this error to happen?


texts: How do I update a column value in my custom plugin with a simple controller?

texts:
I have a custom element type with its own table 'pluginname_entries'. I am trying to find a way to "dummy proof" changing the plugins status. So I came up, aka stole from the Events element type, with the idea of clicking a button that triggers a controller action - similar to the following example to delete my element types entry:

actionDelete()

/**
 * Deletes an entry.
 */
public function actionDelete()
{
    $this->requirePostRequest();

    $entryId = craft()->request->getRequiredPost('entryId');

    if (craft()->elements->deleteElementById($entryId))
    {
        craft()->userSession->setNotice(Craft::t('Entry deleted.'));
        $this->redirectToPostedUrl();
    }
    else
    {
        craft()->userSession->setError(Craft::t('Couldn’t delete entry.'));
    }
}

I love the concept or a quick way to delete or update the entry, more specifically the entry custom status, with a simple click of a button. So I came up with this:

actionDeny()

/**
 * Changes an entry to denied.
 */
public function actionDeny()
{
    $this->requirePostRequest();

    $status = PluginStatus::Denied;

    $entryId = craft()->request->getRequiredPost('entryId');

    $query = craft()->db->createCommand()
        ->select('id, status')
        ->from('entries')
        ->where(array(
            'id' => $entryId
        ))->queryRow();

    if ($query == null) {
        craft()->userSession->setError(Craft::t('Unable to deny the entry.'));
    }
    else {
        craft()->userSession->setNotice(Craft::t('The entry was denied.'));
    }

}

That works as intended, notifying the user but of course doesn't actually update the status column to the new value, is there a better way to handle this? Maybe more of a "Craft" way?


texts: CP doesn't recognize update from 2.7.3 to 2.7.4

texts:
I have a site running Craft 2.7.3. My update flow is to make sure that my development branch is up to date (with no outstanding commits) and that my local db is up to date with production.

I then log in to my development site (site.localhost) and click the Update button. Changes are tested. I then commit the updated files and merge/push to staging and then to production.

Occasionally, updating staging and production will require visiting /admin to trigger a db update. This doesn't seem to be the case with the update from 2.7.3 to 2.7.4.

So, development has been updated to 2.7.4. I then committed and pushed to staging. However, when I log in to the CP on staging, I still see an update badge and the system is telling me that I need to update to 2.7.4.

I have verified that the files changed as a result of updating to 2.7.4 have been deployed to the server. Specifically, I can see that craft/app/Info.php defines the CRAFT_VERSION constant as 2.7.4. When I log into the staging db and check the craft_info table, I see that the value in the version column is still 2.7.3.

I have subsequently clicked the "check for updates" links in the CP multiple times, but the system never recognizes the update to 2.7.4.

For what it's worth, I have also used Settings > Clear Caches just in case, but that hasn't had any effect.

Thanks!


texts: Adding all the Matrix Block field types of the same kind to get a total

texts:
I have a Matrix block with a description field and a number field for hours. Let's say while creating an entry I add in 3 of these blocks with each having a different amount for the hours.

How can I add each of those 3 amounts and get a total amount?

I've spent quite a while researching and can't figure out what kind of syntax would make this work.


texts: How might a construct a URL for an Event List of a specific calendar using the Solspace Calendar plugin?

texts:
I am using the Solspace Calendar plugin for Craft CMS. I need to construct a URL for the Events listing template for a specific calendar group. For example, I want to use the Events template, but only for the Academic calendar, so that I exclude events in the athletics or faculty calendars.

None of these work.

http://localhost/calendar/events/academics or http://localhost/calendar/events/calendar/academics

Help, please?


texts: Commerce 1 create a new order programmatically

texts: How can this be done in PHP?  I can't find anything in the docs.


texts: Can Craft convert requested url to lowercase?

texts:
I think this is normally done with .htaccess or httpd.conf, but it's a bit cumbersome on shared hosting, and it seems like a simple trick for a CMS...

Can Craft convert requested URLs to lowercase? So if the slug for the page is /meditate, but someone types in /Meditate that Craft delivers /meditate page?

I don't quite understand how one uses customAsciiCharMappings -- it seems unrelated to this.


texts: Set cookie and redirect back to referral URL

texts:
I'm setting up a site for a brewery that requires age verification.  When a user visits the site, I check for the presence of a cookie (I'm using nystudio107's cookie plugin) and if it hasn't been set, it should redirect them to a verification page, which will then take them back to the page they were originally trying to view.

If I just send the user back to the homepage after verification, it works fine. But when I try to pass a variable to get them back to the page they were originally trying to view, things break.

Here is my code to check for the cookie and redirect to the verification page (it works as intended):

{% if getCookie('age') %}
    Page Content
{% else %}
    {% redirect "age" %}
{% endif %}

Here is the verification page code (setting the redirect variable isn't working).

Are you 21 or older?

{% set redirect = craft.request.getUrlReferrer() %}
No
Yes

From here they go to the template that actually sets the cookie (again, issues with the query string):

{{ setCookie('age', '21', now | date_modify("+365 days").timestamp ) }}
{% redirect siteUrl ~ craft.request.getQuery('age') %}

If I take out the redirect variable and query string, and just redirect to siteUrl, it all works fine. I'm having trouble passing the original URL along to get the user back to the page they're actually trying to go to.


texts: Entries sorted by title have some entries not alphabetical

texts:
I have the following code to return some grants, but whilst most of the entries are coming back alphabetically ordered, after the last "Z" entry, there are a few more entries also alphabetically ordered. But they are all the same category.

{% set searchParams = {
    relatedTo:  relationParam,
    section: 'grants',
    limit: 9,
    order: 'categoryYearForSorting desc, title asc'
} %}

{% paginate craft.entries(searchParams) as pageInfo, pageEntries %}

I feel like i've seen this before, but cannot think what the reason might have been :(


texts: How can I incorporate a variable into a string?

texts:
How can I incorporate a variable into a string, so that the result is a longer string that includes the contents of a given variable?

For example, I have a variable called apple and its value is "Arlington Pippin" (it's a type of apple). I'd like to end up with a phrase that reads:

  There is an Arlington Pippin.

How could I accomplish this?


texts: Dev mode giving multiple errors but everything works

texts:
I use for example {{ craft.config.baseUrl }} where baseUrl is a custom variable in general.php

This works fine. But when I enable devMode it gives a template error 'craft variable unknown'.

I also get other template errors such as variable 'entry' unknown but I don't have a variable called entry in that template. These errors happen in my _layout template.

Weird thing is that with devMode false everything works fine.

I'm on mobile now but can post detailed code tomorrow if necessary.


texts: Edit meta property value in Open Graph meta tag

texts:
I would like to implement Pinterest Product Pin for my products. I need to update og:xxx values. Here is how i done:

{% set og = seomaticMeta.og %}
{% set og = og | merge({'type': "product", 'product:price:currency': "USD", 'product:price:amount': variant.price|number_format(2) }) %}
{% set seomaticMeta = seomaticMeta | merge({'og': og}) %}

This adds new tags but the property of the meta tag should not include 'og:' in product related meta tag. So this outputs something like:

<meta property="og:product:price:amount" content="300.00" />

but it should be something like this:

<meta property="product:price:amount" content="300.00" />

How can i achieve this?


texts: Conditional Logic to show or hide fields in the admin?

texts:
I'm looking for a way to show or hide fields when editing an entry based on items selected.

I need to manage a list of businesses and my plan is to have a channel to hold them all. But based on the type of business, there are different pieces of information I need to collect.

They all have common attributes (Name, Description, Location, Phone, etc.)
There are many types (Restaurant, Recreation, Venue, etc.)

Many types have subtypes, but not all (Restaurant: American, Chinese, Casual)
Some have additional Info based on their type (Venu includes a list of meeting rooms with Names, Dimensions, Amenities, etc.)
Businesses can have more than one type (Restaurant, Venu)

What I'd like to do is be able to show different sets of inputs based on what categories are selected.

Check Restaurant

Reveal a list of Restaurant types, because that is relevant only to restaurants.

Check Venue

Reveal a table field type so you can enter a list of room names with corresponding features and amenities.

Is there a way in Craft, or is there a plugin that lets you run logic based on inputs to show or hide other inputs?


texts: Workflow for re-using data structures and setups across projects?

texts:
I am wondering if there is a way to re-use pre defined field types and image crops over various Craft projects. I currently in the process of e.g. manually defining 20 different image crops I already defined for another project, which is a tedious task.

I am not really familiar with SQL and database structures, so I am not sure if there is a way to simply copy fields from one projects database to another or if this would corrupt my database?


texts: Disabling the target="_blank" on admin site title link

texts:
I'm looking to hook into this somehow to adjust the title home page link in the top left corner of the admin pages to stop opening in a new tab. Anyone have any good solutions for removing the target="_blank"?

Here's a sample of the code in question:

Site Name


texts: Updating Craft removed a channel from the CMS?

texts:
Anyone experienced this problem?

I have a dev site set up which we updated to 2.4.2702. After updating one of my section channels has disappeared from the CMS.

The entries for the channel are still showing and I can see the channel set up in craft_sections on the database so any ideas what has happened to it and why it is no longer in the CMS?


texts:
I'm attempting to run Craft (2.4.2696) on a server with PHP 7 RC, and I'm seeing the following PHP warning:

Declaration of Craft\DbCommand::addForeignKey($table, $columns, $refTable, $refColumns, $delete = NULL, $update = NULL) should be compatible with CDbCommand::addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = NULL, $update = NULL)

It's only a warning, and with devMode off, the site seems to function well. I'm not going to put anything that throws warnings into production, though.

My question(s): What is the cause for this warning, and is it something I can fix myself? Does Craft officially support PHP 7?


texts: Commerce 2 Stripe gateway seems to be working correctly, but order remains unpaid

texts:
I am using the Stripe gateway plugin for Commerce 2.

I have done the following:

Entered the stripe API keys correctly.
Set the Webhook URL up correctly in Stripe.
Correctly disabled CSRF protection for the webhook url.
Used the example templates with the stripe.js token submitting correctly.
Since I am using 3dSecure, I am getting redirect offsite correctly.
After returning from offsite, I see the completed order successfully.

In the control panel the order is completed, but it is unpaid.

The last transaction has the status 'processing'.

Any ideas why the order isn't paid?


texts: Can't resize image in Rich Text field since 2.5 update

texts:
after upgrade to 2.5, it seems it's not possible to click on the inserted image and resize it in the Rich Text Field. If you click it now, you directly get a popup to give in the Title, link or select the alignment.
It used to show an 'Edit' overlay & the option to resize it with the mouse.

Any others experiencing this?


texts: Loop through all possible options of a Dropdown-field

texts:
I'm currently trying to create a for-loop that loops through all options of a dropdown field created in Craft.

I have a field called "Season", with the possible options to choose from being "2015/16" and "2016/17". What I'm trying to do now is to create a loop that would loop as many times as there are options available in that field.

I'm thinking of something like this:

{% for option in fields.season %}
    ...code...
{% endfor %}`

Is there a way to accomplish this within Craft?


texts: Custom Field Settings: Unknown Property Error

texts:
I have a custom field with a setting for regionType, but when I try to save the field I get this error:

  Setting unknown property:
  kgrote\siteutilities\fields\Regionselect::regionType

In my fieldtype file I have this to load the settings field:

public function getSettingsHtml()
{
    // Render the settings template
    return Craft::$app->getView()->renderTemplate(
        'site-utilities/_components/fields/Regionselect_settings',
        [
            'field' => $this,
            'settings' => $this->getSettings()
        ]
    );
}

And the settings template looks like this:

{% import "_includes/forms" as forms %}

{% set input %}
    {{ forms.select({
        id: 'regionType',
        name: 'regionType',
        options: ({
            'usStates' : 'US States & Canadian Provinces',
            'countries' : 'Countries'
        })
    }) }}
{% endset %}

{{ forms.field(
    {
        label: "Region Type"|t('app')
    },
    input
) }}

My field is a simple pre-filled dropdown, so I'm importing most of the methods for my field from craft/vendor/craftcms/cms/src/fields/BaseOptionsField.php.

I don't see much in the source code that relates to settings, so I'm not really sure what's causing this error.


texts: Craft3, Plugin Craft Commerce, Tax without percentages

texts:
Is it possible to set Tax in the Rate field other than percentage?.
In Tax I want to place an example amount: 10.50 without percentages.


texts: 500 Internal Server Error on trying to install

texts:
Probably something really silly I'm missing here but I'm trying to test out Craft with a look at purchasing but can't even get to a first step in installing it :-(

As far as I can tell the server requirements are all covered. All files have been uploaded to FTP although I have my domain.com and then a craftcms folder then within that folder I have the craft and public folders.

I have had to do things like this as can't place craft as the main folder on the server due to the server already having a site on it although I'm fairly certain I should be able to run the craft site in this way shouldn't I? From a sub-folder I mean.

Anyway when I go to domain.com/craftcms/admin I get an Apache 500 Internal Server Error and not really much more information. I have also tried going to the alternative admin URLs to see if one of those works and they all come up with the same error.

Just wondering if I'm missing something obvious here?

Many thanks in advance.

Best wishes,

Mark


texts:
I'm testing with the Foxycart Plugin to update the stock in my code.
In the FoxyCartController.php I'm able to filter through the XML feed ok and get the new Stock value but it's doesn't seem to be getting saved.

My current code which picks up the correct product and $newQuantity value ok - but it doesn't seem to save the $newQuantity value back to the stock field in the entry.

//If you have custom code to run for each product, put it here:

$service = craft()->entries;

    $entry = $service->getEntryById($product_code);

    if ($entry != null) {
        $attrs = $entry->getContent();

        $newQuantity = $attrs['stock'] - $product_quantity;

        $entry->getContent()->setAttributes(array(
            'stock' => $newQuantity
        ));

        $service->saveEntry($entry);

        //return $entry;
    } else {
        //return null;
    }


texts: Can custom entry sources have their own URLs?

texts:
I can go to http://example.com/admin/entries/sectionHandle, and the Entries list has that source selected, but I can't find a way to do that with sources added through modifyEntrySources.

I've got two extra sources for entries that have been fully translated, and those that haven't, so we can track our progress as we translate the site.

Is there anything I can add to the array so that I could link to something like http://www.example.com/admin/entries/untranslated?

public function modifyEntrySources(&$sources, $context)
{
    if ($context == 'index')
    {
        $sources[] = array('heading' => 'Translations');

        $sources['translations:untranslated'] = array(
            'label' => Craft::t('Untranslated'),
            'criteria' => array('translationCompleted' => array('0', null))
        );

        $sources['translations:translated'] = array(
            'label' => Craft::t('Translated'),
            'criteria' => array('translationCompleted' => '1')
        );
    }
}


texts: insertAll() not inserting entries into database

texts:
I've created a database table that I am trying to add information too with a onBeforeSaveElement() hook.

For some reason, although it is telling me that the rows have been added in the $result, there is no records being added. Interestingly, if I run the page an then manually add a record to the database table, the id has been incremented by the amount of rows $result says it has added.. so it seems that the rows are being added then instantly deleted?

Thanks

SQL

CREATE TABLE `craft_lsclearance` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `path` text,
  `cleared` int(11) DEFAULT '0',
  `dateCreated` datetime DEFAULT NULL,
  `dateUpdated` datetime DEFAULT NULL,
  `uid` char(36) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=229 DEFAULT CHARSET=latin1;

Function

craft()->on('elements.onBeforeSaveElement', function(Event $event)
    {
        $element = $event->params['element'];
        $paths = craft()->plugin->getPaths($element);

        foreach ($paths as $path) {
            $newPath = preg_replace('/site:/', '', $path['path'], 1);

            if ($path['locale'] != 'en') {
                $newPath = $path['locale'] . '/' . $newPath;
            }

            $model[] = array(UrlHelper::getSiteUrl($newPath));
        }

        $result = craft()->db->createCommand()->insertAll('lsclearance', array('path'), $model);

        print_r($model);
        echo '<br /> Inserted: ' . $result . 'row(s)';

        exit;

    }
);

Output

Array (
  [0] => Array ( [0] => http://mydomain.com/ )
  [1] => Array ( [0] => http://mydomain.com/ )
  [2] => Array ( [0] => http://mydomain.com/results?q=regatta+ac )
  [3] => Array ( [0] => http://mydomain.com/watch/regatta-ac-titanium/19225 )
  [4] => Array ( [0] => http://mydomain.com/mens-watches )
  [5] => Array ( [0] => http://mydomain.com/mens-watches/p2 )
  [6] => Array ( [0] => http://mydomain.com/watch/ac-ii/19282 )
)
Inserted: 7 rows


texts:
This is a super basic question...

I've got a plugin that watches two events, in one event it creates a user. After another event I want it to activate that user.

How do I get/store/pass the id of the newly created user from the first event to the second?

public function init()
{
    craft()->on('thing.beforeEvent', function(Event $event){
        // Save the new user if they're not already a user
        if(!craft()->userSession->getUser()){
            $newUser = new UserModel;

            $newUser->firstName = craft()->request->getPost('firstName');
            $newUser->lastName  = craft()->request->getPost('lastName');
            $newUser->username  = craft()->request->getPost('username');
            $newUser->email     = craft()->request->getPost('email');
            $newUser->password  = craft()->request->getPost('password');

            $newUserSuccess = craft()->users->saveUser($newUser);
            if (!$newUserSuccess)
            {
                Craft::log('Couldn’t save the new user', LogLevel::Error);
            }
        }
    });

    craft()->on('thing.afterEvent', function(Event $event){
        // Activate the new user if they're not already a user
        //if(!craft()->userSession->getUser()){
        //  craft()->users->activateUser();
        //}
    });
}


texts: Safe number of related entries – before performance hindered?

texts:
Is there a safe limit to the number of entries related to another entry via the entry field (including nesting 2 deep) before putting too much strain on  performance? I'm approaching a products range using the entry field, e.g.

Parent
-child
-child
-child parent
-- child
-- child


texts:
Does Craft have a built-in Controller/action for clearing the cache?
We have auto-deployment set to a server and would be useful to set up a POST-receive hook to force the cache to clear when deployments are made.


texts: Using a Redirect plugin in conjuction with a wildcard route

texts:
I have Craft set up to serve a single page Vue App (vue-cli) for all routes it can't match in the sections.

return [
  '<url:(?!api).*>' => ['template' => 'index'],
];

This works perfectly.

However, I was hoping I could also use a Redirect manager plugin like Retour, Redirect Manager or Sprout Redirects.

I tried them all but they only take effect when I disable the routing rule.

How could I have both working together?


texts: How to access Craft classes within plugin?

texts:
I'm working with dates and want to use Craft's Class reference to speed things along but am struggling to figure out how to use them. For example, this works as expected and returns the siteUrl:

return craft()->getSiteUrl();

But how do I format something more complicated? Say I want to format a date variable, how do I use any of these classes: https://craftcms.com/classreference/etc/dates/DateTime? I've tried all sorts but generally end up with:

Craft\WebApp and its behaviors do not have a method or closure named...


texts: Localization - Getting page not found from CP when trying to edit new locale

texts:
I've set up a new locale fr_ca according to the localization guide.
I've defined my site url's accordingly and set the files like so that english is on the top level and an fr_ca folder contains the index.php file.

I've set the craft folder accordingly, and defined CRAFT_LOCALE.
I've also enabled the locale in all my sections.

Now when i access a singles entry, and I click Canadian French on the right to switch locales, I get a Page Not Found error, the requested URL was not found on this server.

I've also set my templates so that inside my templates folder, i have a folder fr_ca containing a new index.html file to be served. When I try to access the site from the front end, using www.example.com/fr_ca, I get an entry is not defined error (which makes sense).


texts: How do you set an "If" option on an entry that includes "contains"

texts:
I am trying to set an if statment that will show a li if there is only one entry displaying. The issue I am having is that this entry is put into two different places via checking if it contains a checkbox.
I can only seem to managed to get it to display all the time or not at all

The code I have at the moment is this
    {% if entry.ENTRYNAME.contains('CHECKBOX OPTION') == 0 %}
CONTENT
 {% endif %}

But that does not seem to work.
I am using the Check box contains option else where and it works fine. It's  just the value check that I cannot seem to get to work. I've also tried adding both .length and |length but neither of those seem to work.


texts:
Is craft's username field case sensitive when logging in?

I'm importing 80 users into the database and when emailing the users I want to be sure how this works so we don't hit issues when they all try to log in.

Many thanks


texts: Problem with matrix if statement for hero image other content ends up in my div

texts:
Been playing with a hero matrix field and can't seem to get this working correctly when all block types are not used.

I have four possible block types for this hero matrix field. Image, Heading, Sub Heading, and CTA. If I use each block type it will display fine, if I don't use all of the block types the rest of the page content ends up in my container for the headings and cta of the hero image.

Example I create a hero but don't add a cta button so I only used 3 of the 4 types.

Pretty sure this has something to do with my if statement.

Here is my code.

{% for block in entry.hero %}
    {% if block.type == "image" %}
        {% set image = block.heroimage.first() %}

                {% elseif block.type == "heading" %}

{{ block.heading }}

                {% elseif block.type == "subHeading" %}

{{ block.heading }}

                {% elseif block.type == "cta" %}
                    {% set ctaURL = block.ctaURL.first() %}
                    {% set ctaText = block.ctaText %}
                    {% if ctaURL %}
                        {{ ctaText }}
                    {% endif %}

    {% endif %}
{% endfor %}

Here is a screenshot of my matrix config.


texts: Local MAMP site keeps redirecting to live production site

texts:
I've imported a craft install and its database from a production site to make some changes to it. I've set it up to work locally in MAMP but whenever I go to example.local it keeps redirecting me to example.com. I'm using a multi-environment config so I'm not sure where it could be going wrong.

return array(

// Applies to all enviroments
'*' => array(

    // Base site URL
    'siteUrl' => null,

    // Environment-specific variables (see https://craftcms.com/docs/multi-environment-configs#environment-specific-variables)
    'environmentVariables' => array(),

    // Default Week Start Day (0 = Sunday, 1 = Monday...)
    'defaultWeekStartDay' => 0,

    // Enable CSRF Protection (recommended, will be enabled by default in Craft 3)
    'enableCsrfProtection' => true,

    // Whether "index.php" should be visible in URLs (true, false, "auto")
    'omitScriptNameInUrls' => 'auto',

    // Control Panel trigger word
    'cpTrigger' => 'admin',

    // Dev Mode (see https://craftcms.com/support/dev-mode)
    'devMode' => false,

    // Preserve Image’s Colour Profiles
    'preserveImageColorProfiles' => true

),

// Applies just to local dev server
'.local' => array(
    // Site URL
    'siteUrl' => "http://example.local:8888/",

    // Devmode
    'devMode' => true,

    // Turn off timeout
    'userSessionDuration' => false,

    // Image assets paths
    'environmentVariables' => array(
        'basePath' => '',
        'baseUrl'  => 'http://example.local:8888/',
    )
),

// Applies to production site
'.com' => array(
    // Site URL
    'siteUrl' => "http://example.com/",
    // Devmode
    'devMode' => false,

    // Image assets paths
    'environmentVariables' => array(
        'basePath' => '',
        'baseUrl'  => 'http://example.com/',
    )
)
);

And my current .htaccess

<IfModule mod_rewrite.c>
RewriteEngine On

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]


texts:
I have checked all other questions on stack exchange with similar titles and they don't seem to help my situation.
I have added assets sources to craft CMS. but when uploading I get the following error:

  The error message was: "Error uploading the file:  The file system path "{siteUrl}assets/images/hero-images/" set for this source does not exist."

I am working locally using MAMP. I do not have multiple environments. only local.

the siteUrl variable seems to work fine when used directly in templates. just doesn't work for assets.

File system path is

assets/images/hero-images/

URL is

{siteUrl}assets/images/hero-images/

General config is set to

return array(

    // Base site URL
    'siteUrl' => "//projectname:8888/html/",

    // Environment-specific variables (see https://craftcms.com/docs/multi-environment-configs#environment-specific-variables)
    'environmentVariables' => array(),

    // Default Week Start Day (0 = Sunday, 1 = Monday...)
    'defaultWeekStartDay' => 0,

    // Enable CSRF Protection (recommended, will be enabled by default in Craft 3)
    'enableCsrfProtection' => true,

    // Whether "index.php" should be visible in URLs (true, false, "auto")
    'omitScriptNameInUrls' => 'auto',

    // Control Panel trigger word
    'cpTrigger' => 'admin',

    // Dev Mode (see https://craftcms.com/support/dev-mode)
    'devMode' => false,

);

If I open the assets in chrome, this is their file path.

http://projectname:8888/html/assets/images/hero-images/be-inspired-mobile.jpg

This is driving me mad and have checked everything.

I am using exactly the same config settings as all my other sites which work absolutely fine.
Any help will be really appreciated :)


texts:
Occasionally, after deploying Craft, without warning I am unable to access the admin dashboard and get the following PHP error:

PHP Parse error:  syntax error, unexpected '.', expecting '&' or variable (T_VARIABLE) in /var/www/html/releases/1444051402/craft/storage/runtime/compiled_templates/9/f/9fb1fb61cba0ba044bdd7fb03e82130398321f3315b85408215cc636d2ff3f4c.php on line 177

I am really struggling to replicate the issue. It doesn't occur on my local development environment: it only happens after a seemingly random amount of time sitting on my live server.

Deleting the compiled_templates folder in /craft/storage/runtime fixes the issue but I do not do what is causing it to occur in the first place.


texts: Override "sameAddress" option when updating cart

texts:
I'm working on a new checkout process which involves taking the shipping address first.

To do this I am setting sameAddress to 1 in my shippingAddress form.

Then, at a later stage I want to offer the customer the option to change their billing address. I thought I could just present the customer with a new form for billingAddress fields and set sameAddress to 0, or false.

However, this doesn't seem to let me override the already stored billing address. It seems that once sameAddress is set, it cannot be unset.

I have tried setting a hidden billing address when setting the shipping address but again it's not letting me override that later.

Is there way I can achieve this checkout flow?

Shipping address info -> shipping method selection -> payment (with option to use a different address for billing)?


texts:
I'm using Calendarize and I'm not sure how I can grab the 'To' time?

https://plugins.craftcms.com/calendarize

 {% set monthStart = now|date_modify('-1 day') %}
 {% set monthEnd = '2022-01-31' %}
 {% set occurrences = craft.calendarize.between(monthStart, monthEnd, {
 section: ['events'] }) %}
 {% for occurrence in occurrences %}
<h2>{{ occurrence.title }} - {{ occurrence.next|date('D j M') }}</h2>
{{ occurrence.description }}

//START TIME
{{ occurrence.next|date('H:ia') }}-
//TO TIME???
{{ occurrence.next|date('H:ia') }} occurrence.endTime.format('H:ia')}}

{% endfor %}


texts: Using values from one entry as default values in another?

texts:
Is it possible to do the following in Craft?

I want to set up course information as follows:

1) have a courseType which contains default values for that type of course - name (i.e. 3 hour skills, full day masterclass etc), price, capacity, trainers etc

2) have a course which has a courseType entry filed among other details such as details of the course, equipment used, etc. The course will also have fields for price, trainers & capacity.

Is it possible to have the course price, trainers & capacity fields filled with the value of the courseType selected when it is chosen in the CP new course page? These course fields should then be able to be overridden if required on a course by course basis.

Any suggestions would be very welcome - I'm new to craft and can find any examples like this.

Thanks in advance.


texts:
After a standard search with something like:

{% set results = craft.entries.search( query ) %}
{% for result in results %}

{{ result.link }}

{% endfor %}

Is there a way to find out which field the query was found in?


texts: Plugin Development: extending a vendor plugin

texts:
I'm using composer to import a third-party (vendor) plugin into my own Craft plugin. But can't figure out how I extend the functionality of the imported (vendor) plugin.

For example assuming imported plugin defines a base class of XXX I can try to extend this with class YYY extends \XXX but not sure where I save this so I can access this in my code, eg I want to extend the base plugin through a class, eg

class YYY extends \XXX
{
    public function doThis($str) { return $str; }
}

I'd then want to access this in my Craft plugin with

$var = new \XXX();
$var->doThis = 'CONTENT HERE';

Obviously grossly simplified but hope you get the gist.
Just can't figure out how to achieve above or where I should save the code that is extending the vendor class?

Any thoughts?


texts: Manually creating Security Key gives PHP error

texts:
I'm going on 5 days of banging my head on my desk here.

I'm simply not getting how to install it on my production server. I have Craft working beautifully locally...but getting it to my server is a whole other matter.

So I have ssh'd into my VPS, then run 'wget 'https://craftcms.com/latest-v3.zip'' and unzipped it to try and get it running as just a barebones install. So now I'm going through the install instructions, and am running into an error when running the './craft setup/security-key' step:

PHP Warning:  Module 'Phar' already loaded in Unknown on line 0

Craft requires PHP 7.0 or later.

I created a phpinfo file and it's returning PHP Version 7.0.30.

Any ideas why I'm getting this error?

Thanks in advance.


texts: Redactor air not visible when code mirror is enabled

texts:
I'm using Redactor 2 and I set config air: true and plugin: ['codemirror'].
The issue is when I click on html button the air toolbar disappears and is not possible to have toolbar on redactor again.

Is there a solution?

Thanks in advance.


texts: I am hoping craft supports MariaDB. Also, since version 10, InnoDB transaction engine in MariaDB has been replaced with XtraDB. Will this work with Craft?


texts: Selecting a random entry based on conditional

texts:
I'm trying to select 1 random entry out of a section based on whether a field has content (schedulerBio). I can get all the entries based on the conditional but can't seem to randomize a single selection. Any help would be appreciated.

{% for entry in craft.entries.section('team').limit(1).find() if entry.schedulerBio|length %}
... stuff
{% endfor }


texts: Event or hook to access when needing to show session messages via AJAX within Asset Events in the control panel

texts:
I am using EVENT_BEFORE_HANDLE_FILE on the asset class to moderate images before they are uploaded.
I am setting session errors which show fine on the frontend templates on page refresh, however in the CP they do not show until you press the Save button or you refresh the page if you used the cmd/ctrl + S shortcut.
Is there an event or hook that I can access to show the error messages in the AJAX messages on the save shortcut, and which would stop the entry saving if the user clicked the Save button and show the session error messages?
Thanks


texts:
How do I output one random line of an array?

{% set img = [
  { bildli: 'http://i.giphy.com/I0xDz0htjsiME.gif' },
  { bildli: 'https://i.giphy.com/fA3JALhIi5YVa.gif' }
 ] %}
 {% for item in img %}
   <img src="{{ item.bildli }}" alt="">
 {% endfor %}

I tried {% for item in img.limit(1).order('RAND()') %} like you would on a normal entries.section but that doesn't work on array.

I also tried: {% for item in random(img) %} as statet in the twig doc but that doesn't work eyther. What's the catch here?


texts:
I was using the FeedMe plugin engram-design to move my podcast xml items to entries in a podcast section I tried running a task to update some entries and it broke my site. Now I am unable to access the admin portion of my site. I receive the following error.

Fatal error: Class 'Craft\FeedMe_FeedModel' not found in /www/sites/mywebsite/craft/app/helpers/ModelHelper.php on line 587

I've tried replacing the app folder with a fresh copy, but nothing. Any suggestions?


texts:
I've got a use case where I'd like to be able to not only upload an image for a blog entry's "featuredThumb" but also have the ability to upload a video. I was originally using animated GIFs but they are huge. So much like twitter I'm going to switch them for videos.

Currently, I have something that I'm sure you'll be very familiar with. I've got an asset field within my blog section that accepts an image and my template code looks like this:

{% for entry in craft.entries.section('blog').find() %}

                {{ entry.title }}

{% endfor %}

I'd like to be able to switch the image for a small HTML5 video. This poses a few problems, as numerous video formats are required for cross browser compatibility, along with an image as a poster / fallback.

My current solution is to switch the "featuredThumb" asset field, for a new matrix field that contains two block types:

Image

Asset field - Name: Image

Video

Asset field - Name: Videos (allows multiple files so the user uploads MP4, OGV, WebM)
Asset field - Name: Fallback Image

Then in my template update to:

{% for entry in craft.entries.section('blog').find() %}

            {% for block in entry.featuredThumb %}
                {% switch block.type %}

                    {% case "image" %}

                    {% case "video" %}

                        <video width="320" height="180" autoplay loop>
                            {% for video in block.videos %}
                                <source src="{{ video.url }}" type="{{ video.getMimeType() }}">
                            {% endfor %}

                        </video>

                {% endswitch %}
            {% endfor %}

                {{ entry.title }}

{% endfor %}

This is the best solution I'm able to come up with, but it seems a little over-engineered. I'd love to see other people's take on this.

Cheers,

Tom


texts: How do I get the Site/Revision/Draft in a field in the control panel?

texts:
Is there an easy way to fetch the selected Site, Revision and Draft of the dropdown (the one an editor would use to switch the Site/Revision/Draft) in control panel in a plugin?

The only way I found so far is to get it from the provided URL parameters. This works but I don't feel very safe using it and it won't work in any CLI script, because of the missing Request.


texts: Dynamic Navigation with Condition to check slug

texts:
I'm trying to achieve one pretty simple thing, but putting it into my dynamic nav is making it a little difficult. I want to have a little number of the total amount of entries in my channel "listings" and keep it on one of the links "Our Properties".

I currently have this code that is displaying the total amount of entries

{% set totalListings = craft.entries.section('listings').total() %}
{{ totalListings }}

How can I make this work: {% if link == "properties" single entry %} {{ totalListings}} {% endif %}

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

    {% nav link in menu.all %}

           {{ link.title }}

    {% endnav %}


texts: Charge: send metadata to Stripe on same template as where it's collected

texts:
I'm recording some custom data in Charge, but my client wants to see it within Stripe's control panel. I see you can set a meta array in craft.charge.setPaymentOptions() which should do the trick. But I'm collecting the custom data on the same page where I'm setting the payment options.

So for example, I've got a custom field called giftAid:

<input type="checkbox" name="fields[giftAid]" value="1"{{ charge is defined and charge.giftAid ? ' checked="checked"' }}>

On the same template I tried adding this to my payment options:

{% set options = {
    ... other options ...
    meta: {
        'giftAid': charge.giftAid
    }
} %}
{{ craft.charge.setPaymentOptions(options) }}

... but then I get the error Variable "charge" does not exist.

How can I pass this data to Stripe if it's only set when this form is submitted?


texts: Redactor clips plugin removes DIV tags from inserted HTML?

texts:
I'm trying to insert a clip
my text
. But when I insert the clip, the DIV tags are removed.

I have this setting in my Redactor config json: replaceDivs: false


texts: Omitting unused letters from A to Z list

texts:
I'm displaying lists of members grouped by their surname initial which the user navigates using a list of letters from A to Z. This part was straightforward enough and the following code works to return all members with a particular initial.

{% set searchString = 'surname:' ~ searchLetter ~ '*' %}
{% set members = craft.entries.section('members').search(searchString).order('surname', 'firstName') %}

Where I'm struggling is listing only the letters for which there are members to use for navigation, or to be able to list them all but disable those that don't have members.

Currently I just loop over the characters in the alphabet and output all of them.

{% set characters = 'a'..'z' %}

If someone clicks on a letter that has no members they get a blank list, but this isn't ideal as it would be better if there wasn't a link to this page.

I know with SQL I could do something like a SELECT DISTINCT with grouping to return just a list of initials in use, but is this possible with Twig or would I need to look at writing a plugin?


texts:
I've written a custom plugin and added a custom button to the right panel of an entry page

Now I'm trying to show a Garnish Hud if I click the red button (like the one when you re-index assets)

The content of the hud would be two radio buttons and a button which triggers a controller function. It should also show the progress bar and the success icon after the button was clicked (so basically the same behaviour as the assets indexing thing)

I put this code in my plugin specific js file

var hud = new Garnish.HUD($('#generate-pdf'), 'test', {
        orientations: ['top', 'bottom', 'right', 'left'],
        hudClass: 'hud toolhud',
    });

But this shows the hud after page load and the trigger (that's the button with the id #generate-pdf) doesn't work at all.

Can anyone point me in the right direction?


texts:
The question isn't that relevant to Craft's scope but it bounds to understand How entry from front end is processed... I think.

Thanks to P&T I'm learning on GuestEntries plugin to send a POST request using AMP-FORM. A validation and sending is done via their JavaScript where XHR request is sent without a full load of the page. So AJAX request.
One of AMP's requirements were to set a headers for CORS requests.

So I set the header in my .htaccess file like this:

Header set AMP-Access-Control-Allow-Source-Origin "https://example.craft.dev"

With no header set I couldn't pass through validation.

After fulfilling AMP's requirements to submit a AMP-FORM I get this error:

POST https://example.craft.dev/someURI/send?__amp_source_origin=https%3A%2F%2Fexample.craft.dev
400 (Bad Request)

This is my simple form I'm sending:

<form method="post" action-xhr="{{ craft.request.url }}" target="_top" accept-charset="UTF-8" enctype="multipart/form-data">

    <!-- {{ getCsrfInput() }} -->

    <input type="hidden" name="action" value="guestEntries/saveEntry">
    <input type="hidden" name="sectionId" value="18">
    <input type="text" name="title">

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

</form>

I had to comment getCsrfInput() because It was throwing me an error about some polifiling JSON or something.
I hope You folks can give me some pointers Whether Craft can handle it.


texts:
Per documentation I am getting a selected tag:

{% set tag = entry.myTagsField.first() %}

How to check if its name is equal to "Flower"?


texts: Within my plugin, I have a need to open an Assets sheet and pick a file that has been uploaded and make use of it in my plugin. How is this possible? I am looking for something similar to the EE version of Assets that will allow me to programmatically use Assets with JS.


texts: When image transforming png to jpg, alpha layer become lined

texts:
I have several png images that when transformed from png to jpg, the alpha layer is transformed to an horizontally lined pattern.

Therefore I have to keep them as png, wich is in my case unnecessary and a drastic data load issue.

The problem appears in production, wich is an ArcusTech server.

Anyone knows what it could be ?

Thanks !


texts: Is it possible to bulk-edit a field across multiple entries at once?

texts: I would like to know if it's possible to select multiple entries and update a field for them all at once – for example, give all the selected entries the same category.


texts: How to make fields required on the contact form?

texts:
When using the Pixel & Tonic contact form (https://github.com/pixelandtonic/ContactForm) how do you make the fromName field required?

When using the form as seen on github, only the message and email field are required.

Thank you!


texts: I installed "Amazon S3" in a website. Is there anyway so that I can sync existing local images to Amazon S3?


texts: Passing null values to queries, Sprout Reports

texts:
In Sprout Reports, I am creating a list of users in my settings file. I first need an option with value of null.
{% set options = [] %}
{% set options = options|merge([{ label: 'All users', value: null }]) %}
{% for user in users %}
  {% set fullname = user.firstName ~ " " ~ user.lastName %}
    {% set options = options|merge([{ label: fullname, value: user.id }]) %}
{% endfor %}

{{ forms.selectField({
    label: "Choose one"|t,
    name: "userId",
    options: options,
    })
}}

Then, in my index file (the report), I do something like this:
{% set purchases = craft.entries()
  .section('purchases')
  .authorId(settings.userId)
  .all()
%}

My query runs fine if there is a value for userId, but when it is null, the query does not return any results.
What am I doing wrong?
Do I need to do something like this?


texts: Get field type of product or variant with element api

texts:
Trying to get type of a field (dropdown, checkbox, etc) to render those fields in app, there is all sorts of info available in $variant->fieldLayout->fields like handles, values, ids except type of a field.
Based on docs there is no property like type in craft\fields class.
Maybe someone knows the way how to get this type of a field.

Here is my element-api config for getting a product:

'api/products/<slug:{slug}>.json' => function($slug) {
  return [
    'elementType' => Product::class,
    'criteria' => ['slug' => $slug],
    'one' => true,
    'transformer' => function(Product $product) {

      $variants = [];
      foreach ($product->variants as $variant) {
        $fields = $variant->fieldLayout->fields;
        $fieldsSelected = $variant->fieldValues;
        $variant = (array)$variant;
        $variant['fields'] = $fields;
        $variant['fieldsSelected'] = $fieldsSelected;
        $variant = (object)$variant;
        $variants[] = $variant;
      }

      return [
        'title' => $product->title,
        'url' => $product->url,
        'defaultVariant' => $product->defaultVariant,
        'variants' => $variants
      ];
    }
  ];
}


texts: How to stop rendering errors being output in production

texts:
Due to a server problem one of our production sites was unable to connect to the DB.

While it was unable to connect the site was outputting the error:

An exception has been thrown during the rendering of a template ("Craft can't connect to the database with the credentials in craft/config/db.php.") in "_layout" at line 10.

I'm a little concerned that a production site is outputting this kind of information, is there a way to stop these errors being output?

(The site is currently running Craft Pro 2.1.2561 with dev mode disabled.)

Thanks.


texts: Serialization of 'Closure' is not allowed when upload image

texts:
I built up a form at the frontend to allow users to upload their avatars,my code looks like below

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="users/save-user">
    <input type="hidden" name="redirect" value="users/{{ currentUser.username }}">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">
    ...some other fields
    <input type="file" name="photo">

    <input type="submit" value="upload">
</form>

But I got error 'Serialization of 'Closure' is not allowed' from '/Users/rain/dev/valet/tr3ndsideas/vendor/yiisoft/yii2-queue/src/serializers/PhpSerializer.php' . Any idea please


texts: In entries query, is there a way to check if matrix block is used?

texts:
I would like to get entries if a matrix field is used. Something like this:

{% set query = craft.entries()
    .section('blog')
    .search('myMatrixField|length')
    .limit(10)
 %}


texts:
Is is possible to populate a FreeForm checkbox group by an entries listing? I've got a series of courses with an entry for each one, and I'd like to create a series of checkboxes and values for each course.

The value of the checkbox gets shown in the email notification but not in the control panel. Is this possible to change?


texts: Folder Permissions for Assets, Cache, and temp

texts:
I have set 755 permissions to these folders and they are owned by the PHP web user.

However, I'm still getting logs that say:

[error] [application] Could not delete the file /var/www/craft/storage/runtime/assets/sources/76.jpg because the file does not exist.

Tried to read the folder contents of /var/www/craft/storage/runtime/temp/, but could not.

Tried to read the folder contents of /var/www/craft/storage/runtime/cache/, but could not.

76.jpg does exist. And I don't know why it can't read those folders. Any ideas how to fix this??


texts: How do I send a specific payment source to a subscription?

texts:
There doesn't seem to be a way to use a specific card when signing up for a subscription. it will automatically choose the last entered card the user has. I need a way of sending one of the craft.commerce.paymentSources.getAllPaymentSourcesByUserId to the subscribe action on the controller. The controller accepts the planUid, but I don't see anything about a payment source id.
I think based on these lines in the controller:
$paymentForm = $gateway->getPaymentFormModel();
                $paymentForm->setAttributes($request->getBodyParams(), false);

                if ($paymentForm->validate()) {
                    $plugin->getPaymentSources()->createPaymentSource(Craft::$app->getUser()->getId(), $gateway, $paymentForm);
                }

(and the Javascript commerce has as one of their examples in the templates)
// Tokenize the credit card details and create a payment source
            this.stripeInstance.createPaymentMethod('card', card, paymentData).then(function(result) {
                if (result.error) {
                    this.displayMessage(result.error.message);
                    $form.data('processing', false);
                } else {
                    // Add the payment source token to the form.
                    $form.append($('<input type="hidden" name="paymentMethodId"/>').val(result.paymentMethod.id));
                    $form.get(0).submit();
                }
            }.bind(this));
        }.bind(this));

They're appending $form.append($('<input type="hidden" name="paymentMethodId"/>').val(result.paymentMethod.id)); and I think whenever paymentMethodId is sent to the controller, it will automatically try to create a new payment source.
I can't find how to just send an existing payment source to this action and have it charge that card.


texts:
I've set up a global set "attachmentGlobals" with a matrix field inside named "globalFiles". This matrix has only one block "files" which has a text field "fileId" and an Asset field "fileAsset".

I would like to retrieve a specific row searching for the "fileId" content.

I've triyed in those ways:

Test 1:

attachmentGlobals.globalFiles.fileId('sitelogo')

Return me an Error saying no method "fileId" is available

Test 2:

attachmentGlobals.globalFiles.find('fileId:sitelogo')

No error, but no results

Test 3:

attachmentGlobals.globalFiles.search('fileId:sitelogo')

No error, but no results

I've search Craft documentation and some examples on Stack Exchange, but nothing seems to help.

In the first place, is this possible? or were am I wrong?

Thank you in advance.

PS: I know this issue could be solved using only assets fields, but I would like to know if is possible to search for matrix fields by filed content.


texts: Change/update the default user profile photo/thumbnail folder location

texts: I'm having a hell of a time tracking where i can change/update the default user profile photo/thumbnail folder location. I keep reading and have tested that you can create a new volume for assets. My interest is is being able to locate and change the default folder location. Any advice?


texts: How to output only the first instance of a Matrix block type field

texts:
I've got a Matrix block in my Latest News/Index template and I can't figure out how to only output the first instance of a block type field.
Here is my code, working great except it outputs the first 250 characters from ALL {{block.newsContent}} content block fields not just the first. I know this is what my code is actually set up to do, but I can't figure out how to only output the first one!

{% for block in entry.newsBlock %}
    {% switch block.type %}

        {% case 'nbTitle' %}

 {{ block.newsTitle }}

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

        {% case 'nbContent' %}

{{ block.newsContent | striptags | slice(0, 250) ~ '...' }}

    {% endswitch %}
{% endfor %}

The {{block.newsContent}} part outputs every instance of that field, but I only need the first, as it's the 'excerpt' intro to the complete article.

Here is the front end:
https://www.ancamotion.com/latest-news

Any help appreciated, thanks!


texts: Include an extension in your template name, including ".twig" (e.g. robots.txt.twig)

texts:
I like to use .twig for my templates for easy syntax switching, but it doesn't seem to work when my template requires an extension as part of its name.

For instance:

robots.txt works fine
robots.txt.twig, doesn't. The matching request is now {siteUrl}/robots.txt.twig, and I don't get the automatic Content-Type matching that happens when it is just robots.txt.

I figure this just isn't currently supported, but I would be nice!


texts: Has someone figured out Craft 3 content migrations?

texts:
One of the big features for craft 3 is content migrations. Migrating fields and sections between environments (like deploying code to test or production).
I'm just having a hard time figuring out what options there are. I did find some simple examples, but they are a little limited...

https://craftcms.com/news/craft-3-content-migrations
https://docs.craftcms.com/v3/content-migrations.html

Since there is a separate documentation page which seems incomplete i created an issue. If anyone has some additional info i would like to make a pull-request to complete the docs.


texts:
Hope you guys can help. I was working on my Craft site locally and now trying to upload it to the server but no matter what it says "Craft can’t connect to the database with the credentials in craft/config/db.php"

I have created the database in phpmyadmin along with the username and password.

Also my hosting provider is HostGator

This is what I have locally for the db.php.

return array(

    // The database server name or IP address. Usually this is 'localhost' or '127.0.0.1'.
    'server' => 'localhost',

    // The name of the database to select.
    'database' => 'simple-portfolio',

    // The database username to connect with.
     'user' => 'portfolio-rc',

    // The database password to connect with.
    'password' => 'r*****',

    // The prefix to use when naming tables. This can be no more than 5 characters.
    'tablePrefix' => 'craft',

);

And the server's db.php.

return array(

    // The database server name or IP address. Usually this is 'localhost' or '127.0.0.1'.
    'server' => 'localhost',

    // The name of the database to select.
    'database' => 'rchohan9_website',

    // The database username to connect with.
    'user' => 'rchohan9_portfol',

    // The database password to connect with.
    'password' => 'p************',

    // The prefix to use when naming tables. This can be no more than 5 characters.
    'tablePrefix' => 'craft',

);

Also the whole site is put in a folder so its not sitting in the root directory

Locally general.php looks like this

return array(
    'devMode' => true,
    'siteUrl' => array(
        'en' => 'http://localhost/portfolio',
    ),
    'environmentVariables' => array(
        'baseUrl'  => 'http://localhost/portfolio/',
    )
);

and on the server it's:

return array(
    'devMode' => true,
    'siteUrl' => array(
        'en' => 'http://rachnachohan.ca/website',
    ),
    'environmentVariables' => array(
        'baseUrl'  => 'http://rachnachohan.ca/website/',
    )
);

I am completely out of ideas of why its not able to connect to the db.


texts: Sprout SEO best practice - single or multiple field types?

texts:
I think I know the answer for this (multiple) but I just wanted to see how others are doing it?

Right now I have a single default meta field type that I add to most of my sections. At this stage I've got the advanced 'Meta Details' turned off but we're starting to need to make per section tweaks and I'm looking at enabling this.

Given we want finite control (and better sectional specific fall backs if the meta information isn't supplied) I'm now realising that most people probably have a meta field for each section?

If I do migrate from a single to multiple (~30 sections atm) there's not a simple way to migrate the existing meta data is there?


texts: What is the best way to handle errors in plugins and templates?

texts:
What's the best way to prevent exceptions in my plugin from blowing up my entire page? try/catch and return null, and then check for null in the template?

For example: my plugin fetches data from a remote REST API. If that request fails for any reason I get an error page. I understand why, but I'm looking for the best way to handle it. I'd appreciate any input, even if it seems glaringly obvious to you.


texts: Craft 2 to Craft 3 upgrade: User Photos not migrated to User Accounts

texts:
I followed the instructions in the docs at https://docs.craftcms.com/v3/changes-in-craft-3.html#user-photos.

I can browse the User Photos in the User Photos Asset Volume in the Control Panel. However, the User Photos are not linked to their respective User Accounts. I noticed that in the C3 craft_users table the photoId col is NULL. I can add an asset ID manually and the User Photo displays in the User Account in the CP.

I can upload new User Photos in User Accounts in the Users section of the CP.

How can I link the original Craft 2 User Photos to the User Accounts (ca. 100) in Craft 3?


texts: Is the length filter required when checking if a field has content or not?

texts:
When checking if a field has content or not in my templates I usually write something along the lines of:

{% if entry.fieldHandle|length %}

{{ entry.fieldHandle }}

{% endif %}

Writing the same code without the |length filter does also work, so can I just exclude the use of the filter from my code altogether? Are there any caveats with not using the filter?

As an aside, I am aware that |length does have its uses. You can use this to check the exact value of something, etc etc.

This question was more suited for a simple yes/no check to see if a field has any content and outputting something if it does.

Another example of the |length filter in my code would be something like:

{% set homepageServices = craft.entries.section('services').type('serviceGroup').level(1) %}
{% if homepageServices|length %}

Output the services here

{% endif %}

Would removing |length (which does work at the moment) cause me any headaches down the line?


texts: How we can set an image as default value in assets field

texts: I have a field for upload an image in asset field. Can we set a default image in this field. Means when I create a new entry a default image has been already selected in asset field.


texts:
We've had this problem for a while now and it's largely gone un-noticed but I'd like to raise it.

We have a bunch of products that are discounted when you buy them in bulk. E.g. 12 products for 69.99.

In order to achieve this we calculate what the price should be for each product, by dividing 69.99 / 12, which is 5.8325.

We put this in the database as the product price and I can see it is stored in the database correctly.

However when you add 12 items to the cart, the total is 69.96 - anything past 2 decimal places is being rounded off prior to multiplication.

I've managed to work out a fix for this, but its not ideal as it will get wiped out if anyone ever updates the LineItemModel.

Here is my solution to change the calculation:

public function getSubtotal()
{
    // The subtotal should always be rounded.
    return $this->qty * CommerceCurrencyHelper::round($this->salePrice);
}

to

public function getSubtotal()
{
    // The subtotal should always be rounded.
    return CommerceCurrencyHelper::round($this->qty * $this->salePrice);// Modified: JL
}

and change

public function fillFromPurchasable(Purchasable $purchasable)
{
    $this->price = $purchasable->getPrice();
    $this->taxCategoryId = $purchasable->getTaxCategoryId();
    $this->shippingCategoryId = $purchasable->getShippingCategoryId();

    // Since sales cannot apply to non core purchasables yet, set to price at default
    $this->salePrice = $purchasable->getPrice();
    $this->saleAmount = 0;

    $snapshot = [
        'price'         => $purchasable->getPrice(),
        'sku'           => $purchasable->getSku(),
        'description'   => $purchasable->getDescription(),
        'purchasableId' => $purchasable->getPurchasableId(),
        'cpEditUrl'     => '#',
        'options'       => $this->options
    ];

    // Add our purchasable data to the snapshot, save our sales.
    $this->snapshot = array_merge($purchasable->getSnapShot(), $snapshot);

    $purchasable->populateLineItem($this);

    //raising onPopulate event
    $event = new Event($this, [
        'lineItem' => $this,
        'purchasable' => $this->purchasable
    ]);
    craft()->commerce_lineItems->onPopulateLineItem($event);
    // Always make sure salePrice is equal to the price and saleAmount
    $this->salePrice = CommerceCurrencyHelper::round($this->saleAmount + $this->price);
}

to

public function fillFromPurchasable(Purchasable $purchasable)
{
    $this->price = $purchasable->getPrice();
    $this->taxCategoryId = $purchasable->getTaxCategoryId();
    $this->shippingCategoryId = $purchasable->getShippingCategoryId();

    // Since sales cannot apply to non core purchasables yet, set to price at default
    $this->salePrice = $purchasable->getPrice();
    $this->saleAmount = 0;

    $snapshot = [
        'price'         => $purchasable->getPrice(),
        'sku'           => $purchasable->getSku(),
        'description'   => $purchasable->getDescription(),
        'purchasableId' => $purchasable->getPurchasableId(),
        'cpEditUrl'     => '#',
        'options'       => $this->options
    ];

    // Add our purchasable data to the snapshot, save our sales.
    $this->snapshot = array_merge($purchasable->getSnapShot(), $snapshot);

    $purchasable->populateLineItem($this);

    //raising onPopulate event
    $event = new Event($this, [
        'lineItem' => $this,
        'purchasable' => $this->purchasable
    ]);
    craft()->commerce_lineItems->onPopulateLineItem($event);
    // Always make sure salePrice is equal to the price and saleAmount
    $this->salePrice = $this->saleAmount + $this->price;// Modified: JL
}

Can anyone tell me if this is a known issue and whether there is any reason why the code is not like this to begin with? Why store values at 4dp if it's always rounded off to 2dp when calculated?


texts:
Just deployed to a server which has the following open_basedir setting:

{DOCROOT}/:/usr/tmp:/var/www/vhosts/mydomain.com/httpdocs/

The webroot is at

/var/www/vhosts/mydomain.com/httpdocs/public_html

and craft is at

/var/www/vhosts/mydomain.com/httpdocs/craft

So all standard however I'm still getting this:

  Could not find your craft/ folder. Please ensure that $craftPath is set correctly in /var/www/vhosts/domain.com/httpdocs/public_html/index.php

Any suggestions please?


texts: redirect index.php in urls on Craft site to NEVER show index.php

texts:
We’ve recently had some issues with a staging site being down and it turned out the reason for this was: In the words of Brad at Pixel and Tonic, the redirect is "intercepting the update request for the plugin causing Craft to no longer think it's a POST request”.

caused by:

# make sure index.php is always removed from url (google analytics   tracks duplicate)
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php(/[^\s\?]+)? [NC]
RewriteRule ^ %1 [L,R=301]

we also have in all our craft sites the normal CRAFT removal of index.php from the urls:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ index.php%{REQUEST_URI} [L,NC]

Essentially, a lot of our sites are existing sites that we redesigned and developed, so the .htaccess files contain a lot of redirects for analytics. We noticed that google analytics started tracking duplicate URLs (duplicate being some contained index.php). After some investigation, I found out that the URLs containing index.php were from redirects (although none of the redirect rules contained index.php).

So in order to make sure no urls ever contain index.php, I added the above mentioned rule.
However, we learnt the hard way that that doesn’t work with Craft.

What recommendations do you have in order to never have index.php in URLs? I realize that the standard rewrite rule that the Craft CMS comes with is good enough to hide/remove the index.php from the url and you will normally only see the index.php in the url if you type it in manually - but for some reason, it does show up sometimes when people land on a redirect url which messes with the analytics data.

The way we got around it in the end was asking the folks that take care of the analytics to merge the URLs, which ended up being easy enough to do. I was just wondering if there was any other way?


texts: How to edit the Date Created value that appears on the Entry page

texts:
I've just noticed that there's a Date Created value that appears for each entry in the control panel. Here's a screenshot:

.

How can I edit this Date Created value?

I've just looked at the craft_entries table and edited the dateCreated value for the entry in question, but when I refreshed the entry in the control panel, the Date Created value remained as it was previously.


texts: How can I order search results by the post date?

texts:
I want to order my search results by the post date (not the created on date).  And, this did not work...

{% if entries|length %}
    {% for post in entries.groupBy('postDate') %}
        {% include 'partials/card-standard-4' %}
    {% endfor %}
{% else %}

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

{% endif %}


texts: Error when rendering a template (for HTML email) on users.saveUser

texts:
I'm writing a simple project-specific plugin that sends a notification to the site admin when a new user is registered. I have an HTML template that I'd like to use for this.

In my plugin's main class, I have the following function:

public function init()
    {
        parent::init();
        // Events
        craft()->on('users.saveUser', function(Event $event) {
            $user = $event->params['user'];
            $isNewUser = $event->params['isNewUser'];

            if ($isNewUser)
            {
                // Send notification email
                craft()->aeiMember->registrationNotification($user);
            }
        });
    }

which calls a one of my plugin's services, 'registrationNotification'. Here's the code I have for that service:

public function registrationNotification(UserModel $savedUser)
    {
        $user = new \stdClass();

        $user->firstName            = $savedUser->firstName;
        $user->lastName             = $savedUser->lastName;
        $user->email                = $savedUser->email;
        $user->aeiGroups            = $savedUser->aeiGroups;
        $user->phone                = $savedUser->phone;
        $user->mailingAddress       = $savedUser->mailingAddress;
        $user->city                 = $savedUser->city;
        $user->state                = $savedUser->state;
        $user->zip                  = $savedUser->zip;
        $user->country              = $savedUser->country;
        $user->preferredDealer      = $savedUser->preferredDealer;
        $user->dealerAccountNumber  = $savedUser->dealerAccountNumber;
        $user->school               = $savedUser->school;
        $user->expectedGraduationDate = $savedUser->expectedGraduationDate;

        $email = new EmailModel();
        $email->toEmail = '...myemailaddress...';
        $email->subject = 'New User Registration: ' . $user->firstName . ' ' . $user->lastName;
        $email->htmlBody = craft()->templates->render('aeiMember/registration_notification', array(
            'user' => $user,
        ));

        // Send
        if (craft()->email->sendEmail($email))
        {
            return true;
        }
    }

When I submit the registration form, I get the following error: "CDbException: CDbTransaction is inactive and cannot perform commit or roll back operations.". I narrowed down the issue, and if I use a non-HTML email body, everything works fine, so apparently there's an issue with rendering a template at this event.

Here's a link to a Google Doc with the stack trace: https://docs.google.com/document/d/1atFNkktuZQ91hU9QipXYMhOCHNGAavO5qUI_TF5jSeE/edit?usp=sharing

Am I doing something wrong, or is there a workaround to accomplish what I'm after? It seems like it should be pretty simple.


texts: How do I query for all users that bought a license?

texts:
I’m trying to use Craft Commerce with the Digital Products plugin for a site where users can pay for being listed on that site.

Therefore I need to query for all users with certain criterias plus a valid license.

I’m not sure how to tackle this. I tried something like this, but it doesn’t work.

{% for user in craft.users({
    group: 'profiles',
    relatedTo: craft.digitalProducts.products({type: 'access'})
}) %}

Another approach would be to list all licenses, collect the related users and then list them. But that doesn’t seem like a good idea either, in terms of performance.

Any hint is much appreciated.


texts:
I'd like to know if it's possible to extend another plugin with my own.

I'm currently using the Sprout Forms plugin to create a contact form on our website, and I would like to extend that so when a user submits the form, it signs them up to a campaign monitor list as well (with their permission of course).

Is this possible with Craft? If so where in the documentation would I look for more info?


texts: Craft Commerce — Billing / Shipping Address validation / required Fields

texts: As default Craft has only First Name and Last Name as required. Is it possible to set more as this two fields as required fields? And is it also possible to set custom Fields as required too?


texts: Live preview + share button missing when switching to PRO licence

texts: At first, I thought the latest update was the problem, but apparently, by buying a license and switching to PRO, the buttons disappeared. Is there a magic trick to get them running again?


texts: Send to a friend that sends an email to a defined email of the users choosing

texts:
using the contactForm plugin, I want to make a contact form, that sends to an email address of the users choosing, not the email set up in the admin.
Does anyone know the simplest way of doing this?


texts: index.php in output HTML - channel pages

texts:
is there are anything to do to delete index.php from output html? This is not very "clear"...

In my case its channel array and I call {{entry.url}}...
Any idea how could be this fixed / avoid?

Big TNX for any idea!


texts: Check if a field a included in a Matrix block

texts:
Situation: I have a matrix with about 10 block types, 3 of which have a certain field. I want to check if the current block has that field.

The field in question is a dropdown with values in all 3 options.

I've tried:

{{ attribute(block, 'backgroundColor') is defined ? 'true' : 'false' }}

=>  returns true for all blocks

{% if block.backgroundColor|length %}

=> errors out with Craft\MatrixBlockModel and its behaviors do not have a method or closure named "backgroundColor".

{% if block.backgroundColor is defined %}

=> same error as above

Anyone know how to do this?


texts: Pulling images from other sections with image transform

texts:
I would like to display images from various sections, in this case the home page. I am still coming to terms with Twig/Craft's criteria models and the transform makes it confusing.

{% for image in craft.entries.section('news').limit(1) %}
    {% set transformedImage = craft.imager.transformImage(image, { width: 1420, height: 550, position: image.focalPoint }) %}

    <img src="{{ image.bannerImage.first().getUrl }}" alt="" />
{% endfor %}`

Where do you then define the image? (bannerImage is a asset field)


texts:
I need to setup a way to quick-edit products while viewing them in a list, similar to woocommerce bulk edit feature:

I can't find any documentation on actual editing of the products, as opposed to editing the product in a cart (such as quantity.)

For example, I can grab products in my plugin template file using:

{% set products = craft.commerce.products.order('title ASC').limit(10) %}

But that doesn't give me access to things like how much inventory is left, so that I can output that and offer a field to edit it.

Did I miss the docs to do this? Not sure if Commerce is setup with services available for other plugins to edit products.


texts:
I have lots of products and I want to filter them a certain way.
I want to retrieve all products that have stock = 1 or where product.myField = checked.

I don't know how to do this exactly. This is what I have for now

{% for prod in craft.commerce.products({
    search: 'myField:0 or hasVariant:{hasStock:true}'
}).type(myType).order(sort ~ ' ' ~ order).limit(35) %}

Thanks in advance!


texts: What does {{ hiddenInput('enabled', '1') }} in an entry form do?

texts:
What's the purpose of {{ hiddenInput('enabled', '1') }} in an entry form?

<form method="post" accept-charset="UTF-8">
{{ csrfInput() }}
{{ actionInput('entries/save-entry') }}
{{ redirectInput('viewentry/{slug}') }}
{{ hiddenInput('sectionId', '2') }}
{{ hiddenInput('enabled', '1') }}


texts:
I broke permissions in a critical craft install. My solution was to install a new version of the craft, move all of the templates from the old site to the new site and restore the MySQL database.

Problem is that craft wants to run the setup installer.

Can anyone provide me a quick recipe for restoring a craft3 site from backups? I have the database and all of the assets/templates etc.


texts: Is there any way to prevent Craft from doing anything with uploaded GIF assets?

texts:
I'm having an issue where Craft seems to change (significantly slowing down) the framerate of animated GIF assets on upload (this doesn't seem to be an image transform problem: if I add the file as an asset in Craft, and then open the uploaded version of the file, the framerate has already changed).

The server is on the latest version of php-imagick (3.1.2) and ImageMagick (6.6.7-10) that are currently available for the version of Ubuntu that we're running (14.04 LTS)

So my question is: is there any way (config setting or similar) of preventing Craft from messing with uploaded GIFs in this way?


texts:
We're using Stripe for an ecomm project that we're testing out right now and nothing is hitting Stripe. If we use a bad card number (per Stripe's docs) like 4000000000000002, the order still goes through.

The Stripe account is brand new (hasn't fully been activated yet) and in Test mode and the test secret and publishable keys are in Commerce's settings. I'm not sure what else to check.

EDIT:

I had forgotten stripe.js altogether but now I'm getting "Payment information submitted is invalid." which I think is a Craft/Commerce error. Here's a link to my checkout template code. The wrapper template (extended template) contains this javascript before the closing body tag.


texts: How to get a product variant by SKU and get parent product details as well?

texts:
I need to get a product variant as an object in Twig, as well as get its parents details (the product fields, not just the variant fields). My first guess starts with this:

{% set variant = craft.commerce.products.sku('my-sku-number') %}

But that doesn't work. I've also tried adding a the .first() limiter to the end. What am I missing?

Edit

Thoughts... should I be trying a search/find?


texts:
I have just discovered that all Craft sites on our server no longer let users upload PNG files and I'm struggling to find the issue / fix.

The craft.log simply says 'Save operation failed' and the JS console mentions 500 internal server error.

I've tried various PNG formats, and weirdly other systems on our server using Imagemagick are running fine.

Anyone had a similar issue / suggestions for debugging?


texts:
I'm outputting a timeline for company history and i'd like to add a graphic for the Year before the first entry of each year. My current code is as follows:

{% set companyHistory = craft.entries.section('about').slug('company-history').first() %}

{% for moment in companyHistory.children.type('history') %}
    <li>{{ moment.title }}</li>
{% endfor %}

My date field is simply called 'date'. How might I go about this with the fewest possible DB queries?