texts: Closure in plugin class/ saving and passing a public property

texts:
I am struggling with closure and saving a variable.

In my class somePlugin i do have a public var $customerId , which should be updated after i execute my setUser() function. To do so i have a setter and getter function. In my init() function i do want to use the new var on a later EVENT_BEFORE_COMPLETE_ORDER event. However the variable $customerId does get reset to the default value after page reload.

How would i avoid that?

I tried using session but it seems like the session has been overwritten on reload as well

class somePlugin extends Plugin {

    public $customerId = '1234';

    public function init() {

        parent::init();
        self::$plugin = $this;

        Event::on( Order::class, Order::EVENT_BEFORE_COMPLETE_ORDER, function( Event $e ) {
            $order             = $e->sender;
            $customerId        = $this->getCustomerId();

            // on every page reload it does get reset to the default var, what is not wanted
            $order->customerId = $customerId;
        } );
    }

    public function setUser( $userId ) {

        self::$plugin = $this;

        // get userModel by userId
        $userModel = Craft::$app->users->getUserById( $userId );

        // check if  commerce record for craft user exists
        if ( ! $this->customers->getCustomerByUserId( $userId ) ) {

            // create and save new customer
            $newCustomer       = new Customer();
            $newCustomer->user = $userModel;
            $this->customers->saveCustomer( $newCustomer, false );
        }

        // store customerId
        $customerId = $this->customers->getCustomerByUserId( $userId )->id;

       // sets the new and wanted it wich gets overwritten by page reload
        $this->setCustomerId( $customerId );

    }

    public function setCustomerId( $customerId ) {
        $this->customerId = $customerId;
    }

    public function getCustomerId() {
        return $this->customerId;
    }
}


texts: In the sample code, Logout doesn't actually do anything. Once a user has created a cart / order and the go to a different page, I want to force log them out, so if they go back to the cart page, it's a new order etc where they have to enter their email in again. Thanks


texts: Plugin with multiple locales and relations

texts:
First i would like to say that Craft CMS really impresses me and im really interested in learning more about it

However in a recent project i am having a bit of problems, i have looked at the sample cocktail recipes plugin and it all makes sense however my project is a bit more complicated than that, it adds about 10 new tables and i need to be able to use more than one locale

I will describe a small portion of what im trying to achieve and maybe someone could point out where to look for some code examples within craft core files

For the sake of this example i will have 4

disease (diseaseSort)
disease_translation (diseaseId, locale, diseaseTranslation, diseaseTranslationDescription)
treatment (diseaseId, treatmentSort)
treatment_translation (treatmentId, locale, treatment, treatmentDescription)

The idea is we would have a list of diseases (in more languages)

and each of those would also have multiple treatments that are available, and also they would be in all the different languages

what i would like to find out is how can i have a form where i add the disease and it also update the relevant translation table.

I have looked at the source code but at the moment its still bit hard to understand the data flow.

To Clarify why i am thinking of separating the plugins data structure from crafts structure and not using elementsModel i will outline a more detailed plugin description

The plugin will have Diseases with locales
Each Disease will have a Grid

A Grid would have a table based layout where there would be treatments as columns ranging from 2-5 treatments for each grid

And 5-15 questions about the effects of a disease as rows.

the cells of the grid would be answers to a specific question for a specific treatment
a simple example would be :

even with this very simple example i have 9 elements and if i have 5 locales it amounts to 45 entries in the database however most grids will have far more data

Am i wrong into thinking that it will slow things down considerably ?

A suggestion that would help me and probably other people as well would be extending the cocktail recipes plugin a bit so it would have:

Cocktail Ingridients

Cocktail Recipies (A group of ingridients)

Locales integrated with both the ingridients and recipies

This would provide an example for both the locale integration and more advanced relations between tables

Thanks in advance


texts: Add a button to the entry edit screen via plugin

texts:
I would like to add a button to the edit entry screen, only for already saved entries, alongside the "Share" button.

When clicked, I'd like to call my plugin's controller action and post the entry ID.

Where would I look to see how to do this?


texts: Problem saving new entry populated with setContentFromPost() while setContent() works

texts:
I'm building a cinema program, and I'm trying to build entries for movies and shows loading external data via a plugin.

I'm getting close, but now I've hit a roadblock trying to save the entries. I build an array of the data to set as content that looks something like this:

$movie = [
  'movieID'       => (int)$ctx_movie['MOVIE_ID'],
  'title'         => $ctx_movie['VERANSTALTUNGSTITEL'],
  'audioLanguage' => $ctx_movie['SPRACHVERSION'],
  'country'       => $ctx_movie['COUNTRY'],
  'director'      => $ctx_movie['DIRECTOR']
]

Then I make an entry model, and try to set the content to the above array:

$entry = new EntryModel();
$entry->sectionId = craft()->sections->getSectionByHandle('movies')->id;
$entry->typeId    = craft()->sections->getSectionByHandle('movies')->type('movie')->id;
$entry->authorId  = craft()->userSession->getUser()->id;
$entry->enabled   = true;

// This doesn't work:
$entry->setContentFromPost($movie);

// This seems to work, creating an entry and populating fields:
// $entry->setContent($movie);

$success = craft()->entries->saveEntry($entry);

I keep getting this error for every entry:

array ( 'title' => array ( 0 => 'Name cannot be blank.', ), )

The value I set to the 'title' element definitely has a value, and even if I hard code it to be a dummy string, it still fails in the same way.

It seems to work when using setContent($movie) instead of setContentFromPost($movie), but from what I've read the latter is the correct (or best practice) way to do it.

I'm guessing it has something to do with the extra validation, but I can't for the life of me understand why a simple string like 'Dummy title' fails the same way as my variable. The name setContentFromPost throws me off a bit, as I'm unsure if it means the data should come via a post request, but it seems to be fine with my other variables, and from the documentation they seem to be used in the same way, passing an array of values.

(On a side note, I got a similar error for a field that is of type dropdown. I guess here I just haven't understood what value to pass to a dropdown fieldType, so if someone has any tips here too, that would also be great, but I assume it may be two different issues.)


texts: In the entries listing (backend), how can I disable the preview button in Craft 3?

texts: I'm building a single page site, so there wont be a page for each entry. How can I disable the preview (world) button for each entry? I'm using the structure section type.


texts:
Can these things work together? Right now, after verification I am being redirected to the dashboard (/gistApp) instead of being routed through /actions/gistClient/loginControl where I have some user business logic. I know that /actions/gistClient/loginControl works because I can direct navigate to that URL.

Here is my general.php

return array(
 'omitScriptNameInUrls' => true,
  'loginPath' => '/gistapp/login',
  'setPasswordSuccessPath' => '/gistapp/login' ,
  'purgePendingUsersDuration' => 'P2M',
  'devMode' => true,
  'autoLoginAfterAccountActivation' => true,
  'postLoginRedirect' => '/actions/gistClient/loginControl',
  'enableCsrfProtection' => true,
  'csrfTokenName' => 'cranberryCsrfToken',
);


texts: Craft Routing / Variables with Differing URI

texts:
I have a project which I'm working on which is going to need something similar to the following URL Structure :

site.com/dfe45c4f/news_title, site.com/gyb66dx/news_title or site.com/76vvg3s/news_title

The First URI Segment is the 'Partner Reference' - a hash value for every partner we work with, the second is a simple entry url title. Every page will show the same data, but each page will be 'branded' differently based on the Partner Reference.

What I need to do is to query a Craft channel a set a variety of variables (styling/logo/branding etc) for the page based on the partner reference.

How would I set routing to look up the first Segment URI to look at the partner section and return all the field information as variables?

Thanks


texts: Including the category group in nested category URIs?

texts:
I've asked already about nested categories here, but I've just upgraded to Craft 3 and things seem to have changed a little.

I have three top-level category groups:

- Home
- About
- Funding

Each of these has multiple categories, and some of these categories are nested up to three levels deep.

My problem: the nested category URIs don't include the category group (which I appreciate doesn't have its own slug). Instead I get stuff like this:

/cat-A/subcat-1/
/cat-B/subcat-2/subcat-6/

... when what I want is:

about/cat-A/subcat-1/
funding/cat-B/subcat-2/subcat-6/

If I manually add funding/ or about/ as part of those categories' URI formats (eg. funding/{parent.uri}/{slug}) then it appends funding/ at each level, eg: funding/funding/funding/cat-B/subcat-2/subcat-6.

I've managed to achieve what I want for entries, by setting their URI format like so:

{category.first().group.handle}/{category.last().uri}/{parent.uri}/{slug}

... which gives me stuff like:

funding/cat-B/subcat-2/subcat-6/entry-title-slug

I only really need this feature to work because I envision users browsing the categories and potentially clicking the URI/links and being taken to the wrong place.

In my earlier post I created a top-level category group called "Navigation" which contained all my categories – this achieved the correct URIs. This feels messy/hacky though and means my users have to see a redundant "Navigation" group when editing categories.

It's likely I'm misunderstanding some aspect of Craft here – can anyone help me achieve what I'm trying to do here?


texts:
Want to do two things and wondering if I'm missing something in the docs or if someone has tackled this already:

User registers on the front end and get success messages saying they will be notified when approved.
Admin is notified that they just did that.
Admin activates them
They get email saying they are good to go. (optional I guess)


texts: Is it possible to share a field between Matrix Blocks?

texts:
I'm attempting to do some advanced layout orchestration using Matrix blocks. I'll need different blocks types – Image, Quote, Body – that can be combined, but they'll each need to share a few fields that allow their layout to be customized, such as Padding, Alignment, or Width. I'd rather not have to create the exact same field (e.g. Alignment could be a 4-option Dropdown) for each block type, but there doesn't seem to be a way to share fields between Matrix Blocks the same way you can share them between Sections.

Am I correct that there is no better way to accomplish this than just recreate the shared fields for each block type?


texts: How should I organize/structure my channel sections?

texts:
To me, I have a large dataset of 2,000 - 2,400 entries.  It's a static dataset.  I only need to update a few fields annually.

I plan to use channels.   But, how should I organize the channels?

Option 1  The entries can easily be divided between development and production.  Each production entry has a corresponding development entry.  This makes it easy to setup related records. This would result in roughly 1,000 to 1,200 entries in each channel.

Option 2
The entries can also easily be divided between 4 entities.  Entity 1, Entity 2, Entity 3 and Entity 4.   This would result in 4 channels of roughly 500-600 entries per entity.  So, the development and production relationships would exist within in the same channel.  (I think - assume - this does not present any challenges.)

Which channel structure might be easier to build out and manage?

Thanks


texts: CP is throwing Mixed Content over the place & HTTP 400 – Bad Request

texts:
New Install of Craft on AWS Lightsail with HTTPS and I am getting mixed content warnings on all of the frontend cp resources.
Added https://... to  siteUrl, useSslOnTokenizedUrls, baseCpUrl and also updated .httaccess but still getting mxied content on the login page.  Even deleted all of the files and folders in cpresources.
tried to login to see maybe I could update paths via the unstyled CP, but got:
HTTP 400 – Bad Request – yii\web\BadRequestHttpException
Unable to verify your data submission.
Am I missing anything?


texts: Redactor deleting   and other inline markup

texts:
I'm running the latest version of Craft
Craft Pro 2.5.2760
I've tried this on a vanilla install and on a current site where the issue was highlighted initially.

If I copy and paste "this is some text" into a richtext field, regardless of "Clean up HTML" and "Purify HTML" options being checked or not, when I press save or switch into and out of HTML mode I'm left with

 "this is" where the text within the  and  tags have been stripped out.

If the markup looks like

this is some text

everything is fine, nothing gets stripped out.

There is clearly an issue with

 and  and possibly other tags.

A work around I've found is using in a custom .json in the redactor folder in config.

pasteInlineTags: ['b', 'i']

which instantly removes the b and i tags on paste, however this removes the formatting that the user is trying to copy and paste in which kind of defeats the point of being able to copy and paste.

So I need a solution that will allow the copy and paste of content from word, or pages or another system where the b and i tags are not stripped out immediately.

Just to cover myself I have also tried removing all plugins to see if any of them were causing an issue but again this had no impact.

Thanks in advance for your help you lovely people.


texts: I've just realised that when I duplicate my boilerplate Craft site to start a new client project, I haven't been deleting the license.key file as per the docs here. What are the potential problems here? Does Craft regenerate a key file if it's already used, or have I somehow licensed a single key multiple times?


texts: Can I send a status message from an external (standalone) PHP script to the Craft engine?

texts:
Note: this question pertains to Craft 2 Pro. Craft 3 is not currently an option.

What I need to do

I have some stand-alone utilities that don't need to exist within the Craft framework, so I would really rather not have to go down the road of learning how to develop Craft extensions.

The trick is that these stand-alone utilities do their thing, and then redirect the user to various Craft entries, and I need some way to send arbitrary status messages from the standalone utilities that can then be displayed by the Craft templates.

Example Scenario

We are using a external utility for online fundraising. The user starts on a page that exists as a Craft entry ('Donate'), proceeds to the external utility's web space, and is sent back to the Craft site.

If something goes wrong in the transaction, I need to be able to display any number of error messages to the user, on the original Craft entry, allowing the user to try the donation again. I don't want to create multiple copies of the original Craft entry, one for each possible error message. That seems like an unreasonable duplication of effort and data, and a nightmare in the making if any changes need to be made to what the user sees.

What I hoped would be possible

The external utilities exist on the same domain, so I hoped I might be able to use PHP's $_SESSION variable to set the status message, and then have the Twig template display the message.

Based on what I found, it seems that Twig (at least in Craft 2) doesn't have access to $_SESSION without editing the Craft application code to create a new global variable corresponding to $_SESSION. I want to avoid editing Craft application code to ensure that nothing gets clobbered by updates to Craft.

What to do?

How can I send arbitrary external messages to a Craft entry so that they can be displayed by the Twig template? I don't think I know Craft well enough to know all the possibilities, and so I am not even sure how to search well for what other people have done.

I hope that writing my own extension isn't the answer to this because I haven't figured out how to do that, yet!

Update!

I went ahead with what was recommended in the "accepted answer" below, and it has worked. Here are the steps that I took:

Add a custom route in config/routes.php that looks like this:
'(?:[-a-zA-Z0-9@:%_\+.~#?&\/=]+\/)+error/(\d+)' => '_entry',
This matches any URI that ends with /error/ and a number, and will capture the number as a variable. For an explanation of the regex, here it is on regex101.com.
Note: The version on regex101.com needs one of the forward slashes escaped, but that slash in config/routes.php should not be escaped.
Create a macro that will look up and return the correct error message by using a switch statement on the error number, which will be captured in the matches variable. The macro looks like this:

{% macro show_error(error_id) %}
  {% switch error_id %}
    {% case 10072 %} Error: bad transaction, please try again
    {% default %} Error: error message not found
  {% endswitch %}
{% endmacro %}

Add code at the beginning of _entry to detect if the matches variable exists, and then:

look up what entry would have been loaded by the CraftCMS engine, if this weren't a custom route: {% set entry = craft.entries.uri(matches[0]).first() %}
save the error message to a variable, using the previously defined macro: {% set error_message = show_error(matches[1]) %}

Display the error message at the appropriate place in the template:

{% if error_message is defined and error_message|length %}

{{ error_message }}

{% endif %}`

Result: I can append /error/123 to any entry's URI, and the _entry template will be able to integrate the externally-chosen error message in an internal template.


texts: How to save a matrix content of a new entry in my plugin?

texts:
I have a section of type channel with a matrix field. I want to know how I would save the matrix content while I save the entry as well. I know I can save the entry as follows:

    $entry = new EntryModel();
    $content = array('productName' => $data[0]['Product'][0], 'productQuantities' => $data[0]['Product'][1]);
    $entry->sectionId = 10;
    $entry->typeId = 10;
    $entry->postDate   = date('Y-m-d');
    $entry->authorId   = 1;

    $result = $entry->setContentFromPost($content);

    $entry->getContent()->title = "Fancy Title";

    craft()->entries->saveEntry($entry);

The content variable above stores the content matrix block for this entry should have. So the Matrix has two fields within it one is of entry type and the other is numerical. I want to set these two fields before "craft()->entries->saveEntry($entry);". Please someone tell me how this is possible. I know for the entries type field I have to create a relation but please help me by letting me know how to do that as well as how to create this new matrix block containing that relation etc.


texts: Start Matrix loop from item that contains todays day

texts:
I have a Matrix block weeklyMenuItems, each item in the block has a dropdown with days of the week (Monday, Tuesday etc). Each entry will have a Matrix block with 7 items, matching the 7 days of the week.

In the template, I would like to start the loop from todays day but still include previous days in the loop, at the end. So, according to the example, whichever item.dayOfTheWeek matches {{ now|date('l') }}.

For instance, if today's day is Wednesday, the loop will output...

Wednesday
Thursday
Friday
Saturday
Sunday
Monday
Tuesday

Here is part of my code, the entries that are being looped are from an entries field of another channel menuSection but I don't think that matters in this instance.

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

    {% for menuItem in entry.menuEntries %}

{{ menuItem.title }}

            {# Matrix blocks #}
            {% for item in menuItem.weeklyMenuItems %}

{{ item.dayOfTheWeek }}

{{ item.itemTitle }}

            {% endfor %}

    {% endfor %}

{% endfor %}

Any guidance will be welcomed, let me know if I can clarify anything!

Thanks


texts: How can I start a loop at a specific number?

texts:
First off, I'd like to thank Jeremy for his help.

I have a set of add-on products that go along with my primary product. The options are a radio group.

I am using Multi-Add to tie everything together - and it's all working great. I'm able to add the primary and optional products to the cart.

Where I am hung up is, because I have a radio group - no matter which option I choose, I am always ending up with the last option being chosen.
Which makes perfect sense since that's the last radio in the group that gets picked up.

Here is what I have so far:

...
// items[1][qty] is a <select> input for the primary product
...

{% for foo in products %}
    <div class="radio">
        <label>
            <input type="radio" name="items[2][qty]" value="1">
               {{ foo.title }} &ndash; {% if foo.defaultVariant.price == 0 %} Included with registration {% else %} {{ foo.defaultVariant.price|currency(cart.currency) }}{% endif %}
        </label>
        <input type="hidden" name="items[2][purchasableId]" value="{{ foo.defaultVariant.purchasableId }}">
    </div>
{% endfor %}

As you can see whatever the last radio input is, will be the value that is picked up by Craft regardless of what the user has actually chosen.

So I thought since each radio is a product (with no variants), I could just use the loop index:

<input type="hidden" name="items[{{ loop.index }}][purchasableId]" value="{{ foo.defaultVariant.purchasableId }}">

Which works, but the loop will start at 1 each time. I am hung up on how I can start the loop at a specific number. Or, perhaps there is a better way?

If I were using checkboxes, I'd only have one option per product/input name.

I have also tried using a <select> element, but I get hung up on how I can offer a "No thanks" option.

<select name="items[2][purchasableId]" class="form-control required">
    <option value="">Select</option>
     {% for foo in products %}
         <option value="{{ foo.defaultVariant.purchasableId }}">
         {{ foo.title }} &ndash; {% if foo.defaultVariant.price == 0 %} Included with registration {% else %} {{ foo.defaultVariant.price|currency(cart.currency) }}{% endif %}
         </option>
    {% endfor %}
</select>
<input type="hidden" name="items[2][qty]" value="1">

Which also works well, but if the user does not choose an option, because I am passing a value of 1 with the hidden input, I get an error that I am attempting to use an invalid purchasable ID. Which also makes perfect sense.

I feel like I am so close, but just can't quite see clear enough to know what to do. Worst case I suppose I just listen for either a change/click event via javascript and update the qty value accordingly.

Thank you for any suggestions!


texts: Getting blocks from matrix and injecting them throughout a page, NOT a single loop statement

texts:
I have a matrix field that allows the user to add little 'designed' features throughout the page.
These are placed in certain positions on the page and so I want to loop through these but because they are dotted about he page,  I cannot do a simple, for loop.
Instead I could get all the blocks like this:
  {% set nuggets = entry.nuggets
    .with([
    'nugget:nuggetBody',
    'nugget:icon'
  ])
    .all() %}

Then I could place them like so:
{% set nugget = nuggets[0] %}
{% include '_includes/_components/nugget.twig' with {
  self: {
    size:'xl',
    bgColor: nugget.circleColour.color[0].class,
    iconPath:nugget.icon[0].path,
    body: nugget.nuggetBody[0].bodyPlain
  }
} %}

{% set nugget = nuggets[1] %}
{% include '_includes/_components/nugget.twig' with {
  self: {
    size:'xl',
    bgColor: nugget.circleColour.color[0].class,
    iconPath:nugget.icon[0].path,
    body: nugget.nuggetBody[0].bodyPlain
  }
} %}

etc etc

I wondered if there is a better or more streamlined way than this?
And what happens if they don't have 'enough' blocks, how to accomodate, if for example, I have placed 6 around the page in the design and code, but they only add 4.  I know I could do this...
{% if nuggets|length >= 3 %}
  {% set nugget = nuggets[2] %}
  {% include '_includes/_components/nugget.twig' with {
    self: {
      size:'xl',
      bgColor: nugget.circleColour.color[0].class,
      iconPath:nugget.icon[0].path,
      body: nugget.nuggetBody[0].bodyPlain
    }
  } %}
{% endif %}
etc

But is there a better approach...?


texts:
I currently use Feed-Me to pull data from an API-Endpoint. This API-Endpoint does change from time to time, providing new elements with each change.

I don't want to manually trigger the Feed-Me-Reimport each time I notice a change.
I do know that Feed-Me provides actions URLs for each feed-entry but as the amount of different import-feeds will grow rapidly soon, I don't think it's feasable to manually create those feeds, and after creation also manually put the URL into a custom cronjob.

So in the end what I'd like to have is simply a script that is triggered by a single cronjob, then gets all Feed-Me feeds and for each feed run the reimport.

Via PluginFactory I already generated a plugin that provides me an endpoint(/controller) to be called by cron

public function actionAutoImport()
    {
        $result = 'Autoimport engaged';

        return $result;
    }

But now I am wondering: How do I get information from the Feed-Me plugin i.e. get all existing feeds and trigger a run on each?


texts:
Currently looking into a site which requires a simple invoice payment form which needs to checkout with Worldpay.
Forms fields are simply Name, Email, Address, Invoice No and Invoice Amount.
I would like the payments to be stored in the backend of the CMS - and whether successful or not.

What is the most straight forward way to achieve this?

Current Thoughts:

1 - Craft Commerce - Will I need this full solution? Can it accept custom price fields - as per Invoice Amount?

2 - Create Basic Form which can save the entries using the Guest Entries Plugin - When submitted it saves the details and loads a page on my site to verify information which also loads the details into the basic Worldpay Form method with a Complete Payment button.
Then to update record if payment successful - enter a url in the Worldpay Callback url which calls a custom plugin which will update the Payment Status of the entry. (I haven't created any plugins yet but in theory this one should be straight forward?)

3 - Use some of the existing form solutions out there and hook into some events with those to update payment status? Sprout Forms, Freeform, Form Builder, AM Forms-


texts: Get data from another loop from outside the current loop

texts:
Sorry the question title is so random - feel free to correct it to something more succinct if you can think of one.

Related question: How to query for multiple relations with SuperTable

I have a front end Entry form which I'm using to create/edit an Entry which contains one field, a table called guestNames. The number of rows allowed in that table is set in another section's Entry (event). The SuperTable field in the event that defines how many rows are allowed is called guestAllocation. There two rows in that SuperTable, partner (Entries) and places (Number).

In my front end Entry form I want to create the correct number of input fields that are allowed. I have no problem doing that with this code:

{% for row in 1..entry.guestAllocation.relatedTo(partner).first.places %}

    Name {{ loop.index }}
    <input id="fields[guestNames][{{ loop.index0 }}][col1]" type="text" name="fields[guestNames][{{ loop.index0 }}][col1]" class="form-control">
    {% if entry is defined %}{{ errorList(entry.getErrors('fields[guestNames]')) }}{% endif %}

{% endfor %}

For the purposes of this example, that could be a static number like 5. However, I also need to provide editing functionality rather than just creating a new entry each time, so with the following line:

{% if partnerGuestList|length %}<input type="hidden" name="entryId" value="{{ entry.id }}">{% endif %} {# If there's a guest list for this partner, update it #}

I can check if the entry exists already. Now I need to provide the correct number of input fields from entry.guestAllocation.relatedTo(partner).first.places, but in those input boxes, I need to provide the data from the rows in the table partnerGuestList guestNames

To get the names I need, I can query:

{% for row in partnerGuestList.guestNames %}
    {{ row.guestName }}
{% endfor %}

Please comment if I can clarify any more!

Short version: How can I show data from an entry in a loop that isn't related to that entry?


texts:
Is there a way to define a route that can only receive POST data?
In Laravel you can do this:

Route::post('admin/content/{id}', 'ContentController@update');

Is there a way to do this with a Craft route?

Tried this to no avail:

'POST, newseventsapi/v1/login' => array('action' => 'api/Login')


texts: Import large number of entries every day - 1 million

texts:
I have a shopping product feed that is generated every day with around a million products. This can be in any format needed - CSV, JSON, XML etc, and will live on an S3 bucket.
Each day, I need to import this feed to entries in Craft and assign them categories etc. A large percentage of the products will be duplicates but it may need to update data within the product.
What would be the best way to import this large of a data set?
I have used FeedMe in the past, but I'm not sure whether it could handle this many products.
Thanks in advance.


texts:
I'm wondering what kind of performance I should expect from Craft 3's Control Panel.

I've created a (clever) structure, where I have matrix field which contains a superTable field.

Matrix

Row (block type)

Column (superTable)

Style (dropdown)
Image (an asset)
Text (redactor)

The idea being that I can add rows, and inside the rows I can add a number of columns and fill the column with an image and/or text. From this I create a bootstrap grid.

Problem is that editing entries get really slow if and when the entry has larger amount of rows and columns. On the worst page I have 24 rows and loading the page makes 362 db queries and takes well over 10 seconds to load all redactor fields. This is way too slow to be usable.

Then I started again from an empty page, which has fields for:

title
categories
hero image
ingress/description
and a button to add rows

An empty page creates 116 db queries. Every time I add a new row it adds 9 db queries. Every new column adds 3 db queries. So 10 new rows would create at least 90 new db queries, which is beginning to be problematic.

So is this the amount of db queries that I should expect, ie. is this normal? Is there something fundamentally wrong in the way I created the fields for the page using matrix and a superTable? What can I do to improve the performance?

(Running Craft 3.0.10.2 on Windows/IIS and MariaDB)


texts: What's the best approach to building a photo gallery in Craft?

texts:
I'm thinking about the best way to implement a photo gallery in Craft.

A channel section with an assets field should do the job, but would like to hear how other devs have approached this problem.


texts:
We are looking to place a contact form across all pages and want to integrate HubSpot. I noticed that there was the ability to match up the fields with HubSpot - which is great - my question is how do we pass through the current page's Title and URL the form is shown on?

Is there a way of matching the field that or is it done a different way?.

Thanks in advance.


texts: Query for entry related to current entry in section URI settings

texts:
My entries within specific section can be related to each other using "Entries" field.

If entry1 "Entries" field is filled with entry2, i want to entry2 url look like this:

entry1/entry2

How can this be acomplished?


texts: HTML5 date input field in Chrome ignores twig formatting?

texts:
Im sorry, as I was formulating this question I discovered the answer. Chrome only accepts dates in ISO format (the accepted format for Chrome Date field is YYYY-MM-DD). So use:

<input type="date" name="date" value="{{ "now"|date("Y-m-d") }}" />

...which now looks aweful in Firefox, and not to mention the Date Picker issues.


texts: User-determined price for a product variant?

texts:
Is there a way in Craft Commerce 2 to have a user-input price as a product variant? In my case, I'm offering several pre-set amounts for a donation product (each is a variant), but I also want to offer a "custom amount" option.

Is there a native way to do this? Or a way I can accomplish this with a plugin action?


texts:
Entry is disabled
https://monosnap.com/file/l8tgvr5Fxpw0OXPbpcwiI57JmZjL51

But despite that on its address I see its template loaded only without entry data.

I expected to see 'Page Not Found'.


texts:
I updated to the latest Craft version.

This error shows under the field in entries (backend):

This field’s target subfolder path is invalid: {slug}

I checked the field and there is no {slug} tag at all.

Fronted shows images fine, but with that error I cannot update my entries.


texts: FormBuilder 2 - Notification email to the form submitter

texts:
I have been using the FormBuilder2 plugin and it's fantastic. I am trying to understand if there is anyway that I can send an automatic email to the form submitter using this plugin. There is a possibility to insert a fixed email address in the plugin setting but this, of course, doesn't answer my need.

Any help would be appreciated a lot!


texts: Problem with Adjuster plugin Class not found

texts:
I'm basically having this problem Getting started with Order Adjuster plugin

I have the file plugins/carbonbalance/carbonBalancePlugin.php containing;

<?php

namespace Craft;
Craft::import('plugins.carbonbalance.adjusters.carbonBalanceAdjuster');

class CarbonBalancePlugin extends BasePlugin {

    ... usual standard plugin methods ...

    public function init()
    {
    }

    public function commerce_registerOrderAdjusters()
    {
        return [
            new CarbonBalanceAdjuster
        ];
    }

}

and then in plugins/carbonbalance/adjusters/carbonBalanceAdjuster.php I have

<?php

namespace Commerce\Adjusters;
use Craft\Commerce_LineItemModel;
use Craft\Commerce_OrderAdjustmentModel;
use Craft\Commerce_OrderModel;

class CarbonBalanceAdjuster implements Commerce_AdjusterInterface {

    public function adjust(Commerce_OrderModel &$order, array $lineItems = []){

    $myAdjuster = new Commerce_OrderAdjustmentModel();

    return [$myAdjuster];

   }

}

But I get the following error message

Class 'Craft\CarbonBalanceAdjuster' not found

I understand this is most likely a naming issue, but I cannot see where I'm going wrong in that respect.

Update
I think I have got past this problem by using;

public function init()
    {
        //Craft::import('plugins.carbonbalance.adjusters.carbonBalanceAdjuster');
        require_once('adjusters/carbonBalanceAdjuster.php');

    }

public function commerce_registerOrderAdjusters()
    {
        return [
            new \Commerce\Adjusters\CarbonBalanceAdjuster
        ];
    }

This appears to load the Adjuster, but shows other errors because I haven't yet completed the adjust method.


texts: Get disabled related entry's data within plugin

texts:
I'm looping through products ($rawProduct) within Craft Commerce, within a plugin, and returning products which fulfill a certain criteria. I'm then returning a $products array of objects with the following:

$product = new \stdClass;
$product->url = $rawProduct->url;
$product->courseTitle = $rawProduct->relatedFieldTitle[0]['title'];
$product->courseUrl = $rawProduct->relatedFieldTitle[0]['url'];
array_push($products, $product);

This is working great. However, when the target entry of the related field is disabled, lines three and four above are returning empty. I'd like to get this information no matter whether the target entry is disabled. Any ideas?


texts: Javascript console logs in devMode not always showing?

texts:
Im only recently noticed that sites with devMode turned on add some helpful information about queries and other logs into the console.

See this screenshot:

but im also noticing that some of our sites that also have devMode turned on locally arent showing the console log information?  I cant seem to figure out what else needs to be on to get this output to show up?

related to this is there anyway to add more grouping to the "logs" group to mirror the exiting log folder (ie. give plugins their own group of logs)

Any ideas?


texts:
We have created a site with locales (English, German and Italian). We want to add an extra locale to the home page so we went into the locales admin area and added the new locale. But when we edit the home page this new locale does not show up, it seems like the locale list for a page is setup when the page is created and the new locales are only available to newly created pages.

regards

Andrew


texts: Craft\Exception on saving entries having images

texts:
I have created a new entry in which user can also add images(already uploaded or new upload)
I can save entry successfully if I don't add any images to it. When I add any image and try to save the entry following error is displayed-

Craft\Exception
This file type is not allowed

Earlier different error was displayed which was related to imagick.
Since I have installed imagick and it's php extension, the error is replaced by this new error.


texts: Can I install Craft 3 using cPanel instead of composer. Any suggestion or guide on it? I tried find tutorials but found for Craft 2, not for Craft 3.


texts: Migrated site - now dashboard keeps logging out

texts:
I've migrated my client's Craft site to a new host. On the front end the site is fine and working as it should.

The problem is with the Craft admin area. I can login, but once logged I can’t access anything other than the main dashboard screen. Clicking any of the links within the dashboard brings up the login screen.

One thing I did try was to remove the cpTrigger I’d set in /craft/config/general.php. For a moment I thought this had worked. I could access other areas of the dashboard, but then the dashboard logged me out after a minute or so.

I’ve seen a few other posters with similar issues and have tried solutions that worked for them…

I’ve delete the contents of craft/storage/runtime.

I’ve checked the file permissions of craft/storage/runtime. They are currently set to 774.

I’ve tried adding the following to craft/config/general.php:

'overridePhpSessionLocation' => false
As described here - Craft constantly logging out from admin area

and also:

'overridePhpSessionLocation' => true

As described here - Migrated Server, Now Getting Logged Out Constantly

I’ve tried 'requireMatchingUserAgentForSession' => false too.

Nothing has worked so far.

Is there anything else I could try?

I understand this is likely to be related to permissions for where session files are stored. Are there any questions I should be asking the the hosting company in relation to this? The site is on a shared hosting account.

Any help or advice with this much appreciated.

* An update... *

I looked at /admin/utils/phpinfo in the dashboard to check where session.save_path is pointing.

By default it's set to /tmp.

If I add 'overridePhpSessionLocation' => true to craft/config/general.php, the session location is set to:

/var/www/vhtdocs/xxxxxxxx/craft/storage/runtime/sessions/
/tmp

That looks a bit odd to me? There are two paths – the craft path and the default session path below it. Is that correct?


texts:
We run all our images through a CDN to perform various manipulations. This works create for any image managed via assets, but I'm a bit stuck on any image that has a cpresources URL. In particular I'm running into this issue with profile photos which have a URL much like this:

http://www.mydomain.com/cpresources/userphotos/janedoe/100/JaneDoe.jpg

In the above, I just need to change the URL to something like http://cdn.mydomain.com/cpresources/userphotos/janedoe/100/JaneDoe.jpg

This image will then get downloaded from the www.mydomain.com host.

I did run into this issue with assets too tonight, where there was an issue with an image that didn't get moved into it's final destination, and ended up living in the temp folder, with a cpresources URL.

Is there any way to change this URL?


texts:
I am getting the following error:

Internal Server Error
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #34 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'pottings_website.sources1.sortOrder' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

I have no idea how to fix it.

Its Craft 2.6.2911
PHP 5.6


texts:
I have adjusters that dynamically add/remove costs to things like baseShippingCost and baseDiscount, and want to be able to specifically show the numbers for those adjusters on the cart page - not just the total baseDiscount or baseShippingCost number - as things like shipping costs, or coupons, are also bundled into those.

Here's the adjuster example from documentation, I'll use this as the example:

class BusinessLogic_TaxRemover implements Commerce_AdjusterInterface {

    public function adjust(Commerce_OrderModel &$order, array $lineItems = []){

    $myAdjuster = new Commerce_OrderAdjustmentModel();

    $order->baseDiscount = $order->baseDiscount - 5;

    $myAdjuster->type = "Tax Remover";
    $myAdjuster->name = "Australian GST Remover";
    $myAdjuster->description = "Removes the 10% GST";
    $myAdjuster->amount = -5.0;
    $myAdjuster->orderId = $order->id;
    $myAdjuster->optionsJson = ['lineItemsAffected'=>null];
    $myAdjuster->included = false;

    return [$myAdjuster];

    }

}

How would I access the $myAdjuster->amount in the template/twig file for the order? I've tried {{ cart.myAdjusterName.amount }} and I simply get the error "Craft\Commerce_OrderModel and its behaviors do not have a method or closure named "myAdjusterName".

Does anyone know how to get this information? Any help would be great!


texts:
The {% cache %} tag is quite powerful, and can be used to greatly increase the performance of templates.

But ultimately the whole thing is still pretty mysterious. I can see three tables in the database which seem to relate to caching:

craft_templatecachecriteria
craft_templatecacheelements
craft_templatecaches

I'm still trying to grasp how it all ties together... If I can get a better understanding of how it all works in the "big picture", it will help me to make better decisions as to when & where to use caching.

I know the answer is probably complex, but I'd still love to know... How does caching work?


texts: Stub out the global craft() object for PHPUnit tests

texts:
As best I can tell, the 'mockBuilder' function is exactly what I want, and based on other examples, should work.

Am I missing something?
How can I stub out the global craft() object?

under test:

<?php

namespace Craft;

class JobsVariable
{

     // Grab all Jobss
     public function jobs()
      {
            return craft();
      }
 }

test file:

    <?php

    namespace Craft;

    require_once 'www/craftcms/plugins/jobs/variables/JobsVariable.php';

    class JobsVariableTest extends \PHPUnit_Framework_TestCase
    {

        public function testJobs()
        {

            $craft = $this->getMockBuilder('\\Craft')
                ->disableOriginalConstructor()
                ->setMethods(array('craft'))
                ->getMock();

            $craft->method('craft')->willReturn('xxx');

            $jobs = new \Craft\JobsVariable();
            $this->assertEquals('xxx', $jobs->jobs());

        }
    }

output:

PHP Fatal error:  Call to undefined function Craft\craft()


texts:
in order for my client to have the choice of selecting options or not, I entered an empty (blank) option in a dropdown field.

In the frontend, I use this code:

{% if entry.dropdownFieldHandle|length %}

Title

{{ entry.dropdownFieldHandle }}

{% endif %}

The problem is even if the client chooses the blank option, it still makes the code appear.

Where am I wrong?


texts: Bulk resave user entries to trigger onSaveEntry event

texts:
Is it possible to bulk save user entries to force an onSaveEntry event. I added a new custom preparse field to Users, but need to trigger a save event to propagate.

Regular sections can reindex by saving the Section title (Bulk resave entries to trigger onSaveEntry event) but it doesn't seem like that's possible with Users? Any known workarounds or obvious tricks I'm missing?


texts: Upload and crop profile photo in frontend

texts:
When you are in the backend and go to a user > profile tab. You'll see a very nice photo upload. I want to build this for the frontend users as well. I have a basic form and I'm loading in the following js files

{% includeJsFile "/build/libs/jquery-ui.min.js" %}
{% includeJsFile "/build/libs/jquery.iframe-transport.js" %}
{% includeJsFile "/build/libs/jquery.fileupload.js" %}

My HTML frontend form looks like this:

<form method="POST" accept-charset="UTF-8" data-saveshortcut="" data-saveshortcut-redirect="gebruiker/profielfoto">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="gebruiker/profielfoto">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">

    <input id="image-upload" type="file" name="image-upload" style="display: none;">

upload

</form>

Here comes my JS:

$(function () {
    $('#image-upload').fileupload({
        dataType: 'json',
        type: 'POST',
        url: 'actions/users/saveUser',

        progressall: function (e, data) {
            console.log('progressall');
            console.log(e, data);

            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .bar').css(
                'width',
                progress + '%'
            );
        },

        add: function (e, data) {
            console.log('add');
            console.log(e, data);

            data.context = $('
').text('Uploading...').appendTo(document.body);
            data.submit();
        },

        done: function (e, data) {
            console.log('done');
            console.log(e, data);

            data.context.text('Upload finished.');
            $('
').text(file.name).appendTo(document.body);
        },

        fail: function(e, data) {
            console.log('fail');
            console.log(e, data);
        }
  });

  $('.upload-photo').on('click', function() {
      console.log('upload-photo trigger');
      $('#image-upload').trigger('click');
  });
});

The fileupload jquery keeps triggering its fail function. When I log the data I see that it throws and unexepected error on the response.

Can someone lead me in the right direction and try to mimic the same profile photo upload WITH cropping tool?


texts: How to display a flash message in a template

texts:
I have a plugin that accepts a form post. I need to return a notice or error, plus the original data. Starting with the notice/error first, I have tried this:

if (craft()->broadbean_jobs->createJob())
{
    craft()->userSession->setNotice(Craft::t('Job created.'));
}
else
{
    craft()->userSession->setError(Craft::t('Unable to create job.'));
}

$this->redirectToPostedUrl();

How can I display the notice or error in my template?


texts: Assign a category group to a category field via migration

texts:
I am writing a plugin that sets up Craft in a particular way and have created a category field, but can't figure out how to assign a category group to the field, I have the following:

 protected function createCategoriesField() {

        // Get the field group
        $group = (new \craft\db\Query())
            ->select("id")
            ->from("fieldgroups")
            ->where(["name" => "common"])
            ->one();

        // Get the category group
        $catGroup = Craft::$app->categories->getGroupByHandle("categories");

        // Initialize the field
        $field = new \craft\fields\Categories([
            "groupId" => $group["id"],
            "name" => "Categories",
            "handle" => "categories",
            "selectionLabel" => "Select categories",
            "sources" => $catGroup
        ]);

        // Save the field
        return (Craft::$app->getFields()->saveField($field));
    }

It seems sources is the correct setting, but it accepts 'source keys' which I'm unfamiliar with


texts:
I am attempting to build an application where Craft handles all of the API based data (JSON). I am using the Element API. I can't find an example anywhere online that outputs Users.

I am trying to output some basics first before I start outputting the custom Matrix fields etc. Here is my elementapi.json:

<?php
namespace Craft;

return [
    'endpoints' => [
        'players.json' => [
            'elementType' => 'User',
            'criteria' => ['group' => 'player'],
            'transformer' => function(EntryModel $entry){
                return [
                    'username' => $entry->$username,
                    'jsonUrl' => UrlHelper::getUrl("player/{$entry->id}.json")
                ];
            },
        ]
    ]
];

Any help or an example with some custom matrix user fields would be much appreciated! Thanks a bunch!


texts: How to only show entries older than 12 months

texts:
I want to build an archive template where only entries older than 12 months show up.
Is there an clean and easy way to do so? I only have strange calculations in mind.
Something like this would be nice :)

{% for entry in craft.entries.section('news') if entry.postDate > 12monthsago %}
{% endfor %}


texts: Craft 2.2 with enabled enableCsrfProtection: Failed to load resource: the server responded with a status of 400 (Bad Request)

texts:
Since the update to version 2.2 I can't upload assets.

I get this error message in the console:

Failed to load resource: the server responded with a status of 400 (Bad Request)

And the upload stops:

Any idea why?


texts: Change title url of elementtype in the list

texts:
I have a plugin. In this plugin I did elementtype which extends the user one, but with only one source "clients". I have and New Client button which points to my plugin Plugin_ClientController which looks like this:

class Plugin_ClientController extends UsersController
{

    public function actionIndex( array $variables = array() ) {

       $this->renderTemplate('plugin/client/_index');

    }

    public function renderTemplate($path, array $variables = array()) {

        $path = str_replace('users/', 'plugin/client/', $path);
        parent::renderTemplate($path, $variables);

    }

}

I don't know if this is the right way to do this, but it seems to work,
so like this I can have my one view for Client edit, which is almost the same as users one.

My elementtype is look like this:

class Plugin_ClientElementType extends UserElementType
{

    public function getSources($context = null)
    {
        $sources = array(
            '*' => array(
                'label'    => Craft::t('Clients'),
                'criteria'  => array('groupId' => 1),
                'hasThumbs' => true
            )
        );
        return $sources;
    }

}

So all fine up to here. The problem is in that list:

where I list all my clients the url on the title in my case now User1 is pointing to admin/users/[ID]
I would like to change it to plugin/client/[ID] if that possible I know that it has to be in the model like this:

class Pluign_ClientModel extends UserModel
{

    protected $elementType = 'Plugin_Client';

    public function getCpEditUrl()
    {
        return UrlHelper::getCpUrl('plugin/client/' . $this->id);
    }

}

But it seems that it's not coming from there. If someone can help me with this would be great. Thank you in advance.


texts: Ordering entries by custom field (integer)

texts:
I'm new to craft so may it be a basic question, however I can't find an answer for it :-/

I have custom field 'width' in my entry type defined as integer.
What I need to achieve is quite simple:

{% set entries = craft.entries.section('windows').find({'width':'> 0'}).order(width) %}

The important now is the .order part it's not working right now :-(. What is correct way to do this? I have found some plugins but I believe craft can do this somehow… It always does (so far).

Thanks for any info on this.


texts: How to create a query to group alternate language pages?

texts:
I'm trying to create a sitemap for a site with multiple locales.  An example of the format is described here, but as a quick summary: I need to output locales of related translated pages aside one another.

<url>
  <loc>http://www.example.com/english/</loc>
  <xhtml:link
     rel="alternate"
     hreflang="de"
     href="http://www.example.com/deutsch/"
     />
  <xhtml:link
     rel="alternate"
     hreflang="de-ch"
     href="http://www.example.com/schweiz-deutsch/"
     />
  <xhtml:link
     rel="alternate"
     hreflang="en"
     href="http://www.example.com/english/"
     />
</url>

To output a list of all entries like this I believe I need to query: All entries, from all locales, grouped by elementId.

I've tried to do this using $criteria->find() but I seem to run into two problems.

First, there appears to be no way to query all locales.  The best way I've found is to loop through all the locales.  I'm wondering if I'm overlooking something.  Right now I have:

foreach (craft()->i18n->getSiteLocales() as $locale)
{
  ...
}

A potential problem with doing it this way is that I won't be able to group the results of all locales by elementId during the query.

Second, once I have all the entries, I need to make sure they are grouped by elementId.  This does not happen by default.  The entry for each locale just gets the next available ID when it's created.  It seems the way to do this would be to use $criteria->order = 'elementId'; however, it doesn't appear Craft supports ordering a result set by elementId.

The ideal query would look something like this:

$criteria            = craft()->elements->getCriteria(ElementType::Entry);
$criteria->limit     = null;
$criteria->status    = 'live';
$criteria->sectionId = $sectionId;

// Problem #1: I want to return all locales like you can return all entries using null
$criteria->locale    = null;

// Problem #2: I want to group my results by Element ID
$criteria->order     = 'elementId';

$entries = $criteria->find();

Any ideas on what the best approach would be here?  Is there any crafty way of doing this or will I have to resort to using a custom query?


texts:
I'm trying to wrap my head around Pagination in Craft. I have a template that outputs a list of products based on the Category that is passed to it from this thread:
{# Fetch the entries related to auto-injected category variable #}
{% set entries = craft.entries()
    .section('mySection')
    .relatedTo(category)
    .all()%}

{% for entry in entries %}

{{entry.title}}

{% endfor %}

It works great, but I need to paginate it. I'm new to Craft so I'm sure I'm missing something simple, but all the examples I've seen, plus the docs, show how to paginate based on all the entries in a section, but that's doesn't work for me here. Also, the examples seem to conflict with my code, in so far as they are using 'set entries' to get the pagination working, but I'm using it already to get every item from a category. As I said, newbie here so I'm sure I'm missing something simple; any help appreciated.
I'm also hoping I can generate a numeric pagination, but at the moment I'd settle for understanding how to get the basics working in my category example.


texts: How do i get sites by group handle/name?

texts:
How can I get sites by their group handle/name within twig templates?
Documentation only mentions querying sites by group id - getSitesByGroupId.


texts:
Is it possible to set up a 404 page, and after x amount of time redirecting to the homepage?

{% extends "_layout/_layout" %}

{% set metaTitle = "404" %}

{% set bodyId           = "404" %}
{% set bodyClass        = "404" %}

{% block content %}

Page not found

What’s worse, a hilarious 404 page can’t be found either.

{% endblock %}


texts: Display images in Matrix block in grid view

texts:
I have images in matrix block
I want to display in grid format
Each raw will have three column.

Images 1   images 2  image2
Images 4  images4  image 4

I tried to used batch filter but did not work with matrix block.

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

{% case "profilebuilder" %}

{% set debfilter = block.department %}

        {# use the variable to filter the entries #}

        {% if block.department == craft.request.lastSegment   %}

                 {% for image in block.uploadImageProfile %}

             {% endfor %}

        {% endif %}

 {% endfor %}

  {% endfor %}


texts: Animated GIFs not working in Craft with ImageMagick installed

texts:
When I upload a GIF I either get the first frame or a garbled image (https://share.getcloudapp.com/L1u7BXrA).

Looking around at similar questions, Craft needs ImageMagick installed to properly transform GIFs after upload.

I can confirm ImageMagick is installed and being used as the image driver (https://share.getcloudapp.com/BluZKGYw).

Server has php-imagick and imagemagick installed.

I have 'imageDriver' => 'imagick' set in general.php

Using Amazon S3 to store images.

Anything else I should be trying? Thanks.


texts: 'Create a new entry' CP is blank if matrix field exists

texts:
I set up an matrix field and put it into section type.

If I am trying to create new entry a kind of broken 'Create a new entry' CP is shown up. Only title 'Create a new entry' and an broken 'save' button. Also rest of header seems not to rendered nice. Horizontal scrollbars appear.

If I change same field to other type, all works as expected.
It really only happens if I am using matrix field.

All happens on fresh setup:
No plugins installed. (Just this one task tried and failed).
Mac, Mamp Pro.
Craft (version 2.5.2757)

Console in Browser says nothing.

What I tried:
 + Fresh installation with user permissions for all craft folders read&write.
 + PHP memory config on 128mb. (Mamp Pro).

UPDATE: SOLVED It had something to do with php error settings in Mamp Pro. Once disabled, all is working, also with Matrix.


texts:
I have a sports site I'm building where each team is set up as a user within a 'team' member group.  I have a channel called 'Schedule' that has only 2 fields; a user field to relate the schedule to a team and then a table for the list of games.

On the front-end if I have a profile page for each team (ie: http://www.example.com/{username}).  I'm having trouble outputting the correct schedule based on the username in the URL?


texts: What is the proper way to set `currentSite` in a CP template when managing multi-site stuff in Craft 3?

texts:
In some of our plugins, we have added multi-site support. For the most part, things are working fine but I'm feeling a bit confused about the correct way to set the currentSite in the Control Panel.

On the front-end, I would expect currentSite could be determined from the Base URL matching that of the request.

On the backend, since all admin behavior is managed from the same base domain, there is nothing specific about the request that would indicate the request is for a certain site so using something like Craft::$app->getSites()->currentSite seems to always give back the same answer.

Does Craft define the currentSite on backend requests? What role should a plugin take in defining the currentSite? Should we go as far as creating the variable for current site itself or could we just set the current site using something like Craft::$app->getSites()->setCurrentSite() and expect Craft to do several things for us?  Should we expect different behavior of the currentSite variable when working with Elements vs other components?

Understandably, these are some broad questions. I'm mostly just looking for a better framework to understand what assumptions Craft makes about multi-site on the CP side of things and how we can best plan our code to take advantage of what is already there instead of reinventing the wheel.


texts: How to remove entire Craft CMS folder? or rather uninstall it

texts: I have to reinstall it because i f'up by changing "localhost" to "mysite.dev" on the installation page.


texts:
I am not sure why, but I cannot seem to get the short name/handle/slug of a matrix field that is a category field.  I need to get it's slug.

{% for row in entry.matrixField %}

 {{ row.matrixChild.slug }}

{% endfor %}


texts: Multilang Bug with Matrix, Neo, SuperTable (with Video)

texts:
We have a big problem with CraftCMS and Multilang.

We have the default language German (DE) in Craft.
We have news entries with matrix fields
We create a new language English (EN) as second language
We activate this language (EN) in the News section
We open an existing news entry and click on the second language (EN)
The content of the matrix field does not exist
We go WITHOUT saving back to the source language (DE) and save the post
We switch back to the second language (EN) and now the Matrix Content is here

For us it seems that the Autosave function, which is triggered when you add a new language to a section, does not process the matrix fields (Neo + SuperTable same problem) properly.

The Problem is on all our client sites which use multilang.

Here is a Video
https://www.dropbox.com/s/7jzg6ts3l90xze1/craftbug.mov?dl=0


texts: Deleted plugins still in database? (and reappearing in project.yaml)

texts:
I can see about 10 plugins in the craft_plugins table that have been long removed via the Craft CP panel, and removed from the composer files also.

However when I enable project config, these deleted plugins appear in the plugins section of the yaml file with their status set to 1, which - I think maybe - prevents it being applied to other environments.

Is the best thing to do just manually delete the old plugins from the db? Or is there a 'proper' way to clean them up/out?

(Project is running Craft 3.1.34)


texts:
I'm looking for a way to offer "3 for 2 / 2 for 1" type options with Commerce.

I've been able to achieve this just by adding a default value to a coupon code input.

It works, kinda. If we need to stick with that then we'd be satisfied but where it fails is; say I have 6 items in the cart, I only get the offer on the first 3.

This is a small store with just a handful of items for sale so not a deal breaker but I can imagine other larger stores doing similar.

Adjusters have been mentioned on Twitter but unsure how to follow that through.


texts: Craft Commerce View Order PDF, Not Download

texts: Is it possible to 'view' an order's PDF rather than download/create it first? I ask because I'm working on PDF templates and I can't figure out how to view the progress/changes I'm making without having to re-download a order PDF everytime.


texts:
I am trying to filter an entry's matrix blocks to just the ones with either operational OR hazardous checked (lightswitch). I can chain it together with one, how do you grab items with either checked? See the end of the following line.

{% set filteredComponents = entry.propertyComponents.relatedTo(category).status('live').order('componentName asc').operational('= 1') %}


texts: How to create a new subfolder to an asset with plugin

texts:
I have a plugin that uploads and associates files/assets to users and entries. I would like it to store these files under a user ID subfolder of the asset folder. I know how to do this within the controlpanel, working with assets there. But how would I create and register subfolders within my plugin? If I just create the folder with my php script, it doesnt show up in the assets folder until i do a "Update Asset Indexes".

The way my plugin works now, It creates an asset with the craft()->assets->insertFileByLocalPath, and then associates the fileId with my entry after its created/uploaded. Maybe this is not the right way to do it?

Any help much appreciated.


texts:
I have 3 sets of globals, which use the same fields handles.

{{ firstGlobalHandle.aFieldHandle }}
{{ secondGlobalHandle.aFieldHandle }}
{{ thirdGlobalHandle.aFieldHandle }}

In a child template, I set a variable corresponding to the handle of the global group which I need to call

{% set globalHandle = "secondGlobalHandle" %}

Now in the In the parent template, I would like to do the following :

{{ '{{ globalHandle }}'.aFieldHandle }}

Is there any way to do so ?


texts:
I have a public registration form and want to redirect to a payment page where I will need some details about the newly created user. I tried doing this in my form:

<input type="hidden" name="action" value="users/save-user">
{{ redirectInput('join/payment/?user={id}') }}

I have set a custom route to allow for the query parameter:

   if url = join/payment/*  load template join/payment

but the resulting url does not include the query string, just the first two segments, 'join/payment'.

Am I doing something wrong here?

Thanks!


texts:
I need to make the address fields in craft commerce required, as well as the phone number, etc. I tried to add the 'required' tag to the input element, but it breaks the form so you can't submit it -- at least in chrome. The submit button just stops working.

Is there any way to make these fields required without a plugin? Seems that this should be a feature included (or something optionally set in the code).

Thanks!


texts: Content-Security-Policy Header vs. CSRF Token and login.html

texts:
My company would use the current version of the Content-Security-Policy header.

We have problems with inline JavaScript and would not use MD5 checksums with the policy.

Eg:

CSRF Token support

https://craftcms.com/support/csrf-protection#updating-your-javascript

the login.html template

https://github.com/craftcms/cms/tree/master-v2/src/templates/login.html#L15

Maybe other source code files

Both the CSRF suggestion and the login implementation uses inline javascript.

Exist best practices to solve the problems?
Without ESI how could I include the CSRF token in a separate Javascript file (access the Craft environment variables)?

Is it possible to add the header only for none CP requests?

Thanks


texts: Getting errors back to a template whilst in an event

texts:
I have a plugin which is trying to create a user whilst inside the Charge plugin's onBeforeCharge event.

Here's the relevant code in MyPlugin.php:

craft()->on('charge.onBeforeCharge', function(Event $event){
    $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');

    if ($newUser->validate()) {
        // create user
    } else {
        MyPlugin::log('User supplied details were invalid, attempting to redirect with errors.', LogLevel::Error);

        craft()->urlManager->setRouteVariables(array(
            'myErrors' => $newUser
        ));

        $route = craft()->urlManager->parseUrl(craft()->request);
        craft()->runController($route);
        craft()->end();
    }
}

My problem: this logs my message to the MyPlugin log, and it redirects the page back to the calling template: but "myErrors" is blank. Nothing available.

What am I doing wrong?


texts: How to compare currentUser with entry.author?

texts:
How can I compare the results of currentUser and entry.author on an entry page?
I've tried the following, but none of these get a positive result:

{% if  currentUser == 'entry.author.id' %}

Or

{% set author %}{{ entry.author.id }}{% endset %}
{{ author }}
{% if currentUser.id == '{{ author }}' %}

(I'm aiming to provide a way for the author of an entry to be presented with a form to edit the entry)


texts: How do I add a block to a matrix that already has content via a plugin?

texts:
I'm building a plugin that adds blocks to a matrix in an entry from the front end. I got it up and running by following the answer in this post:

How to save a matrix content of a new entry in my plugin?

How do I check if the matrix already has blocks when I fetch the entry? And then, once I know if the matrix already has blocks, how do I retain the existing data while saving new blocks via the plugin?


texts: We have a channel called Articles with multiple entry types. Is it possible to filter the entries within Craft (on the Entries page) by entry type?


texts: Is it possible to exclude multiple sections from an entry search query?

texts:
I'm trying to build a search function that excludes results from certain sections all together. This is the code I was trying to use.

{% set entries = craft.entries.search(query).section('not testimonials, not authors').id('not 2').order('score') %}

When I use just one section, it works fine:

{% set entries = craft.entries.search(query).section('not authors').id('not 2').order('score') %}

Any thoughts on how I could construct this query?


texts:
Hey I have a problem that i need to fix for a client. I have to send emails from different email addresses in different circumstances. Is it possible that I can setup multiple system email addresses and use one of them in my different plugins?

I tried to change the fromEmail attribute as well as the sender attribute on the email model but it still sends from the same email (which I thought would be the case ).

Anyway please let me know if there is any plugin out there that can do that.

Thanks in advance!


texts: Save and show card fee for Commerce plugin

texts: How do I save and show the credit card fee on the order page. When I get the response from the gateway I too get the credit card fee amount but it's not being added to the order and isn't viewable anywhere - does anyone have any experience with that?


texts: What's the largest number of elements Craft can handle well?

texts:
We are in talks with a client about developing a database that currently has about ~7000 items in it, each with at least one photo so thats likely almost 20,000 with ambitions to grow it to be at least twice that size.

Should I be concerned about scaling a Craft to that size?
What's the largest craft database any of you are running?
Has anyone had any issues with large number of elements slowing down the system to unusable levels?


texts: Element API endpoint without a resourceKey

texts:
The output of a Element API endpoint allows you to change the resourceKey which contains the json data. Is it possible to return just the data without a resourceKey at all?

Values such as null, false and empty string just default to data.


texts: How do you filter matrix blocks by type?

texts:
Is there a way to filter a matrix by block type, or get a count of how many items there are of a certain type? Can't find a syntax example.

I created a matrix with two blocks. In pseudo code, basically what I want to do is this:

{% set typeOneBlocks = theMatrix blocks where type == "typeOne" %}

{% if typeOneBlocks != null %}

        {% for block in typeOneBlocks %}

{# do stuff #}

        {% endfor %}

{% endif %}

Same with typeTwo blocks. If there are no items of one type or the other, I don't want to create that container and have it sitting empty.

If there is not a way to filter or get a count, I'd have to use for loops to increment vars for how many of each block type there are and then act based on those counts. Seems there should be a simpler way.


texts: Get all entries with linked entry in entries field

texts:
I have a channel called 'projects'.
This channel has two entries fields:

relatedThemes
relatedAreas

What I want to do is perform a search query which filters all projects where the relatedThemes field has an entry with a certain id.

I figured out how to search custom fields. Here's an example of a filter with a plain text field with a handle test.

{% set entries = craft.entries({
  section: 'projects'
}).search('test:testValue') %}

This returns all project entries where the test field has the testValue value, as expected.

But I can't seem to make this work with an entries field. I thought I could do something like this

{% set entries = craft.entries({
  section: 'projects'
}).search('entriesfield.id:relatedThemesID') %}

But this does not work.

Another important thing is that I can't actually use template logic, because the query is to be used in the element api (for Craft 2).

I'm not a backend dev, so I test the criteria array in templates first and then convert it to php.

So the correct criteria array for the test text field would be

'criteria' => [
  'section' => 'projects',
  'test' => 'testValue'
],


texts: Are there any alternatives to the deprecated Export plugin?

texts:
This thread Export Craft Data leads me to add a new question.

What is a good Craft 3 export plugin?

I know several for imports, for example the FeedMe plugin is doing a great job, but nothing to export data.

What I need:

Export buttons for all views in CP. (Columns can be defined)
related entries/categories can be included in the export
in an extra view you can prepare templates of exports (like in the Wordpress plugin WPAllExport)
It should also be possible to define a path where it exports the data on a regular basis

(And I think you can imagine much more benefits...)

And NO, the ElementAPI Plugin does not fit my needs. It has to be Client-Usable.

We created a lot of web applications where we always implement some kind of export. If there is nothing out there I am really thinking of creating a plugin. Is there anyone else out there willing to support an ideal Export Plugin (and is also willing to pay for a Pro Version )


texts: Craft and Plugins are licensed, but I'm still seeing warnings on Production

texts:
In my production environment, I have administrative changes disabled, so I see the following messages:
* You’re running Craft Pro with a Craft Solo license. Please fix on an environment where administrative changes are allowed.
* 3 plugins have licensing issues. Please fix on an environment where administrative changes are allowed.

Fair enough. I logged in to my local environment, and licensed the CMS as well as the plugins. This triggered a change to project.yaml and I can see the addition of the licenses. I then pulled to my production environment, synced changes, and I expected to see these warnings disappear. However, the warnings are still there.
Any suggestions as to what I'm doing wrong here?
====
UPDATE
Brad's answer below resolves the issue, but there's one additional note. There are many caches in the CMS > Utilities > Clear Caches. The cache that stores licensing is "Data caches".


texts:
I am new to Craft. I have done some ajax in the distant past. I have searched this forum and see lots of issues with ajax but it seems that there are a lot of different approaches. Craft docs have very little on Ajax.

I am wondering if there is a clear tutorial on doing ajax within craft. I have an address field set up and would like to click a button to retrieve all entries in a certain state and replace currently displayed data with the new data.


texts:
craft.request.urlReferrer returns the full URL of the referrer, while craft.entries.uri accepts the URI only.

Do I need to split the URL just to get URI path, write a twig filter, a custom plugin?

Maybe I can’t see the forest for the trees, but it seems like there should be an easier way.


texts: Field name for customer name in Squarebit Charge for Stripe

texts:
I am using the Charge plugin and am not able to pass the customer name to Stripe. The form field name I am using is "customerName" and I have successfully done this in the past - it shows up in the Craft CP, but not in the Stripe account.

Anyone have any ideas?


texts: List Only Available Times/Dates in Solspace Calendar

texts:
I have the following code that will output the UNAVAILABLE (previously booked) times of a Target Date. How would i edit this to output (in 30 minute increments) only the AVAILABLE times with Solspace Calendar?

{% set targetDate = "2016/09/27" %}
{% set calendarHandle = "default" %}
{% set day = craft.calendar.day({
     date: targetDate,
     calendar: calendarHandle
}) %}

{% for event in day.events %}
    {{ event.startDate.format('g:i a') }} - {{ event.endDate.format('g:i a') }}
{% endfor %}


texts: Getting PHP Error on upgrade from 3.0.36 to 3.1

texts:
I just updated to 3.1 and I'm getting the php error:

PHP Notice – yii\base\ErrorException

Undefined index: settings

It probably has to do with the Cheat Sheet plugin.  I deleted that folder in the vendor directly but no luck.

I can send along the link showing the errors.

Thank you!


texts: Access env variables in custom php files

texts:
Craft Version 3.2
PHP Version 7.2

Below is my folder structure:
Root
  - Other Craft Folder
  - Web
     - Services
         - Db.php
     - env file

I want to read the connection string of the SQL SERVER from the env file.
Things I have already tried:

App::env
require_once 'C:\wamp64\www\craftApp\vendor\autoload.php'; use craft\helpers\App;

print_r(Craft::parseEnv('$sqlServerName')); // Throws Error

But it doesn't work.


texts: Channel index page linked in a structure

texts:
I come from expression engine and what I want to do is the following: I have a channel filled with entries. All I want to do is to list all these entries on a page.
However, I don't want to link through to a detail page. So I disable the "Entries have their own URL's".

Now I can link to this channel by linking to its handle in my url.

Problem now is that I use a structure to build up my navigation. And you can't link to a channel in a structure, only to its entries. So I need to create a (useless) extra single section to link to and list all entries from my channel in that single.
Shouldn't it be simpler than that?

I didn't find a better way to handle navigations yet.


texts: What's the best way to add a copy to clipboard button to the Preview / View button group in the entry editing UI?

texts:
View and Preview buttons work fine, but I want editors to be able to easily share links to drafts with others. The nicest solution would be a Copy button which would copy the preview URL to the clipboard. I'm operating under the assumption that I need to create a plugin to do so, but if anyone has any specifics (or example plugins that do something similar), that'd help greatly.
I'll note that I'm using Craft as a headless CMS and the View link redirects before an editor would have time to copy it. In any case, I wouldn't consider that an adequate solution to this.


texts: Element API throws 404 when not logged into CP

texts:
My element API endpoint throws a 404 when I'm logged out of the CP, but works fine when I'm logged in.

When logged out it throws a regular 404 with stack trace exactly as any other non-existing url, when logged in it spits out JSON as it should be.

HTTP 404 – Not Found – yii\web\NotFoundHttpException
Template not found: news.json

Notably the front-end of the page works fine always..this just affects the element API.

I tried clearing craft caches + all cookies, still the same.
Found nothing suspicious in web.log, phperrors.log or web-404.log
I tried it with a very simple element-api.php and it still produces the same issue.

For example, even this element-api.php does not work:

<?php

use craft\elements\Entry;

return [
    'endpoints' => [
        'news.json' => function() {
            return [
                'elementType' => Entry::class,
                'criteria' => ['section' => 'news'],
                'transformer' => function(Entry $entry) {
                    return [
                        'title' => $entry->title,
                    ];
                },
            ];
        },
    ]
];

(copied straight from the docs. The section "news" exists in my DB and has valid entries.)

Any idea what could be the cause of this or where to further investigate?

This is on Craft 3.1.12.


texts:
This question is a summary of my working with tags yesterday, I'm posting my findings to SE so other people can benefit.

For the purposes of this question, I'm going to be using a tag with the title 'Two Words'.

I'm trying to add a tags listing and filtering system to a blog. As tags don't have a 'slug' property, I've been having issues using them in URLs. If I use the following links:

{% for tag in tags %}
    {{ tag.title }}
{% endfor %}

Then you get unfriendly urls such as http://craft.dev/news/tags/Two%20Words. If I use :

{% set tag = craft.tags.search(craft.request.getSegment(3)) %}
{% for entry in craft.entries.relatedTo(tag) %}

Then I get a list of articles that may contain the term "two words", but aren't actually tagged with Two Words.

I want to list articles related to the tag in the URL, so how can I pull the specific tag from the url, making sure it stays 'url-friendly'?


texts: Calling Related Entries using the Element API

texts:
I have two sections, each with a single entry type:

Sites
Locations

In the Locations entry type I have a Entries field called Site that you can use to relate a Location to a Site entry.

My questions is: how do I show which locations were related to a Site entry when using the Element API? I'd like to display it as an array when using a sites/.json endpoint.

This is what I've tried, but it breaks the endpoint:

'v1/sites/<entryId:\d+>.json' => function($entryId) {
  return [
    'elementType' => 'Entry',
    'criteria' => ['id' => $entryId],
    'first' => true,
    'transformer' => function(EntryModel $entry) {
      $locations = $entry->getChildren()->type('locations')->find();
      foreach ($locations as $location) {
        $locationsInfo[] = [
          'name' => $location->title
        ];
      }

      return [
        'id' => $entry->id,
        'name' => $entry->title,
        'tagline' => $entry->tagline,
        'about' => $entry->about->getParsedContent(),
        'locations' => $locationsInfo,
        'jsonUrl' => UrlHelper::getUrl("v1/sites/{$entry->id}.json")
      ];
    },
  ];
},


texts: Contact Form plugin - different recipients per locale

texts:
What is the best way to define different sendto emails addresses for the ContactForm plugin, depending on the locale the site is currently viewed in?

I am setting up a multilanguage site, and the clients want to have different emails for each language version.

So far I figure a possible way would be to have separate, localized contactform templates, and in each of them define a dynamically-added recipient. But I wondered if there's a better option, e.g. locale-specific options in craft/config/contactform.php?

Thank you


texts: Eager Load Matrix Field with Assets Field Type

texts:
I am trying to eager load an image asset assigned to a matrix. The template is pulling entries in from a section and each entry has the matrix field assigned to it that serves as an image gallery.

The error I am getting back using the syntax below is
Craft\EntryModel and its behaviors do not have a method or closure named "primaryImage".

Section Handle: products

Matrix Field Handle: gallery

Block Type Handle: productImages

Field Handle: primaryImage, Field Type: Assets

 {% set products = craft.entries({
     section: 'products',
         with:[
                    ['gallery.productImages:primaryImage', {
                      withTransforms: [
                      'heroImage'
                    ]
              }],
          ]
  }) %}

Template Code:

 {% for entry in products %}
      {% for block in entry.gallery %}
            {% if block.type == 'productImages' %}
                 {% set img = entry.primaryImage[0] ?? null %}
                       {% if img %}
                            <img src="{{ img.url('heroImage') }}">
                       {% endif %}
            {% endif %}
      {% endfor %}
 {% endfor %}


texts:
I need to validate the form submitted at the frontend by applying additional validation rules.

For that I have created the plugin that listens to "EVENT_BEFORE_SAVE_ENTRY" event and should validate input fields of the form.

Yii2 documentation suggests to override model rules() method to add custom rules, and then to apply validate() method.

The problem is that I cannot find how to override default rules of the Entry class, and how to use overridden classes as entries in Craft3.
Also I need to filter saving entry data from script tags of slashes to prevent script injection.

I am quite new to the Craft3, so please prodive some code examples and where exactly should I put my code
Thank you in advance!


texts: Unexpected token "punctuation" of value "?"

texts:
We’re running into issues with the null coalescence operator in the latest version of Craft (2.6.2989).

Does anyone know why this might be happening?


texts: Commerce - How can I get the values of a category field from a plugin?

texts:
I have a purchasable that has a categories field. When the user visits the cart, I inspect the cart via my plugin.

I am able to see the field, but I am stumbling on how to actually check the values of the field (get the chosen categories).

MyPlugin

...

$lineItems = $cart->getLineItems();

if ($lineItems) {
    foreach ($lineItems as $lineItem) {
        error_log(print_r($lineItem->purchasable, true));
    }
} else {
    // The cart is empty.
}

...

...
[myCategoryField] => Array
    (
        [model] =>
        [column] => text
        [type] => mixed
        [label] => My Category
    )
...

If I go a step further into the field:

...
error_log(print_r($lineItem->purchasable->myCategoryField, true));

I can get something like this:

[relatedTo] => Array
    (
        [sourceElement] => 174
        [sourceLocale] => en_us
        [field] => 25
    )

This is the correct field ID, but I'm not sure how to get to the values of the category field. For example "Category A", "Category B".

Thank you for any suggestions!


texts: How to load a different template for parent page

texts:
So, I'm newer to Craft, and so I need to figure out the best way to set up a portfolio page with child entries. I've set up a structure, but I need the parent page to load a different template than _entry.html. I still haven't been able to figure out a good solution for this, so any help would be great.

Thanks!


texts: "Unknown error" constantly, seems tied to user preferences

texts:
I have a user group called Content Loaders with limited permissions. After creating a test user in this group I got an "An unknown error occurred" message every time I navigated anywhere in the CP or saved a change (though both were successful). I started adding back permissions and when I re-enabled General > Perform Craft CMS and plugin updates, the errors went away. Not sure if this is a configuration issue on this new staging server, but everything else seems to be working. I can't find any posts about similar issues. Obviously I don't want people doing data entry to be able to perform Craft updates! ;) Anyone have a clue what might be causing this?

Possibly related: even with an admin account checking for updates just shows the spinner image endlessly. I have no problem checking for updates on my local install. This is running on DigitalOcean (with ServerPilot), Ubuntu 14.04.4 x64 with PHP 7.

The only errors I saw in craft.log (which I cleared before doing something that caused the cpanel error to appear) looked like this:

2016/07/31 03:45:43 [error] [php] include([snipped path]craft/plugins/commerce/vendor/composer/../guzzle/guzzle/src/Guzzle/Http/Client.php): failed to open stream: No such file or directory ([snipped path]craft/app/vendor/composer/ClassLoader.php:412)


texts: How to show entries with IF statement based on field

texts:
I'm showing entries on a page. Depending on the value of the field postAspectRatio, I would like the layout of this shown entry to change just slightly and thus requiring it's own unique markup.

I've tried to do this using what I know about twig IF syntax but it's not working.

Any help?

{% block content %}

{% for entry in craft.entries.section('projects').order('postDate asc').limit(500).find() %}

        {% if entry.postAspectRatio == 'Portrait' %}

{{ entry.studio }}{{ entry.title }}

        {% endif %}

        {% if entry.postAspectRatio == 'Landscape' %}

{{ entry.studio }}{{ entry.title }}

        {% endif %}

{% endfor %}

{% endblock %}


texts: Display rich text redactor menubar with superscript/subscript buttons

texts:
So my client want to have superscript and subscript buttons in the redactor toolbar like this :
https://imperavi.com/redactor/examples/buttons-sup-and-sub/

I saw this Stack Exchange post here but it is just talking about the shortcuts and the way of making a plugin.

I tried adding the plugin directly in Craft Redactor config file plugins: ['fullscreen','video','table','scriptbuttons'], but of course did not work so easily.

Got Craft 2.4.2699. Is it possible ?
Is it on the Craft roadmap ?
Or should I make a feature request ?


texts: Throwing 500 error, but nothing logged in error logs or apache logs?

texts: I am trying to export query data to a CSV file, everything works fine when I limit the number of rows to 500 ($criteria->limit), but when I increase it to around 530 it gives a 500 Internal Server error. I changed PHP timeout time to 300 from 30 seconds and the issue is still there. I feel like it might be a memory issue or a PHP issue. Does anyone has this happened to them, if so how could you fix it?


texts: Guest Entries required fields fatal error

texts:
I've built a comment system using Guest Entries. If I set fields to be required and don't fill them in in the front-end, I get the following error.

Fatal error: Class 'Craft\GuestEntriesEvent' not found in ****/craft/plugins/guestentries/controllers/GuestEntriesController.php on line 136

New entries are set to disabled by default, I have tried with all fields set to required, and with only certain fields set to required.


texts: first() don't seem to work while using an image transform

texts:
This "standard" set-up for rendering asset transforms works as expected.

                {% set image = entry.articleImages %}

                {% if image | length %}

                            {% for asset in image %}

                            {% endfor %}

                {% endif %}

When I only want the first image out of the assets loop I would normally add .first() to the set image loop.

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

However this ends op in unclear error messages while rendering on the front-end ( Impossible to invoke a method ("getUrl") on a string variable ("111"))!
Or am I missing out on something?


texts: Craft 3 doesn't translate static strings

texts:
I am making a website with Craft 3 and I have some static text that needs to be translated.

I followed Craft's documentation on it. I created my translations/fr/site.php file and use the {{ 'String'|t }} format to translate my strings.

I tried everything I found on the web, but I can not make it work. My strings stay in english and doesn't translate. It doesn't even seem to access the site.php file.

I tried to clear my cache, restart my Docker container, change the folder name to fr-CA instead of fr ...

I found another member here that had the same problem as me, but he updated Craft and it worked. My Craft configuration is up to date...

Is there something I am missing?

Thank you.


texts: Selling tickets to repeating events with Commerce (and Solspace Calendar?)

texts:
We need to build a ticketing system for venue tours, that happen every week within certain date ranges, and with an option to exclude specific dates from the availability list.

Looking at Solspace Calendar, it offers almost exactly the fields we need for this out of the box: (screenshot below)

But I can't figure out how to either:

(1) Recreate this setup as fields on a Commerce product .

(2) Create a relationship between a Solspace Calendar event and a Commerce product (that only allows for a certain number of products to be sold for each date in the calendar).


texts: Disable image cleansing for public facing form uploads

texts: We want the public uploads to remain in raw state. Is it possible to disable image cleansing for entries created through public facing form? (Image cleansing to continue working for uploads through Control Panel.)


texts:
Good morning,
I have inherited a Craft CMS site from a previous developer, and am running into issues when looking to add images to the site.
Following instructions I grabbed the copy of the SQL database for local use, and am running MySQL and Apache via XAMPP
I added new images to the local file structure (assets/images/) but when I go to the template being used and add the standard <img src="./assets/images/name"> I get an error in the console of 404 http://localhost:3000/assets/images/image.jpg could not be found.
I then tried adding it directly into the same folder with my template code (just to see if I can get it working) but this time I got a 500 server error.
I am completely at a loss now since I never worked with CMS before (am an internal React/Node developer). I hope I explained the issue clearly, would anyone be able to point me in the correct direction?
Many thanks.


texts: I want to use progressive jpg files and want to know if craft image transforms save jpg images as progressive, or can they be made to?


texts:
I am very new to craft. installed craft3 very long ago, as a beginner, and trying to solve a long-lasted-issue with my url.
my goal:

Change my base url from www.mywebsite.com/web to www.mywebsite.com

At the moment www.mywebsite.com shows 403 forbidden error.

My directory structure looks as below. As you can see, I installed craft only under public_html/mywebsite.com. I cannot move the files in /mywebsite.com into /public_html folder.
I researched and tried to follow this article however quiet unsure with the different folder structure I have.
Just in case I moved index.html file to the /mywebsite.com root, and at least forbidden error was gone while only blanc page was loaded.
I had the feeling that I could do something with index.php file to redefine('CRAFT_BASE_PATH', dirname(__DIR__));. However also not sure what to write..
Thanks a lot for your help in advance!


texts: Localized Site -> howto redirect Browser

texts:
How would you redirect users with an "english browser" automatically to the english site? I have no idea if this can be made with craft or if this is an apache webserver thing. Any idea?

'domain.de' => array(
    'siteUrl' => array(
        'de' => 'http://domain.de/',
        'en' => 'http://domain.de/en/',
    ),
),


texts:
So Im working on a site migration that had a lot of images stored in Amazon s3.  I was able to get all those images into craft pretty easily by just pointing at the old S3 server.

The problem seems to come when im trying to use any import plugins they seem to all fail to find the assets because they are all in sub folders. Id make sources for each of the folders but there are more than 350 so id rather not do that.

So I've been in excel all day doing some lookups and i finally have a list of elementIds and the assetIds that go with them and i was going to import them into the database myself but now i cant figure out where they go.  I assumed it was using the craft_relations table but no dice?  Anyone have any insight into how asset->matrixblock field relationships are stored in the database or a better way to get all the images imported?


texts:
I changed the language locale to Hungarian, but the translation for the singles looks a bit funny. Is there an easy way to override it with my version?

Singles are translated to "Egyedülállók" but that 99% of the time here means a single person and not a single something.


texts: What's the best way to create a multiple account architecture?

texts:
(I have a lot of experience with custom PHP and JS code and multiple frameworks and a few CMS's, but little experience with Craft.)

I'm working on a site and they want to have multiple accounts and admins and users that fit in that paradigm, and I'm not sure the best way to approach it.

So general admins should be able to create new accounts and account admins. Account admins can log in and add products for their account only. And then the regular site is locked behind a login so that "regular" users must log in and be associated with an account and can. Both Account Admins and General Admins should be able to create "regular" users (but the former for their accounts only).

I was maybe thinking of associating extra fields to User Groups and trying to go at it in that route. I see you can edit User Profiles with Pro, but I don't see a way to customize User Groups (maybe we don't fully need that, but maybe just let those general admins create User Groups (can this be renamed "Accounts?").

I realize this is a bit of a vague/open ended question. Maybe this isn't really practical in Craft, or will need a lot of custom work...? Or maybe someone has a plugin with this in mind? Just looking for some general help, and this seemed like the place to start!


texts: Redactor 2 error 'accessibility-help-label'

texts:
I made the update for Redactor 2 and I'm getting this error:

VM463:1 Uncaught TypeError: Cannot read property 'accessibility-help-label' of undefined

Can anyone help? I can't find the problem.