<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kushal Bansal on Medium]]></title>
        <description><![CDATA[Stories by Kushal Bansal on Medium]]></description>
        <link>https://medium.com/@kushaler2010?source=rss-3e1200b23dcc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HezYi2-HMWVDRMfX2pCxRQ.jpeg</url>
            <title>Stories by Kushal Bansal on Medium</title>
            <link>https://medium.com/@kushaler2010?source=rss-3e1200b23dcc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:14:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kushaler2010/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unraveling Vue 3: A Comprehensive Guide to Data, Methods, and Computed Properties in Options API…]]></title>
            <link>https://kushaler2010.medium.com/unraveling-vue-3-a-comprehensive-guide-to-data-methods-and-computed-properties-in-options-api-07d6993db3c5?source=rss-3e1200b23dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/07d6993db3c5</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[drupal]]></category>
            <dc:creator><![CDATA[Kushal Bansal]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 23:14:47 GMT</pubDate>
            <atom:updated>2024-02-03T23:14:47.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unraveling Vue 3: A Comprehensive Guide to Data, Methods, and Computed Properties in Options API and Composition API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*akmnL8Y6xnXPKqTy4SR9bA.png" /><figcaption>VUE3</figcaption></figure><p>Vue 3 introduces two distinct paradigms for structuring components: the time-tested Options API and the revolutionary Composition API. In this comprehensive guide, we will delve into the concepts of data, methods, and computed properties, exploring their usage in both APIs. Understanding when to use each and how they differ in the Composition API will empower you to make informed decisions in your Vue projects.</p><h4>Options API: Classic Structure</h4><p>In the Options API, data, methods, and computed are properties defined within the component options object.</p><h4>data:</h4><ul><li>Purpose: Define reactive data properties for a component.</li><li>Usage: Returns an object containing reactive data properties.</li></ul><pre>data() {<br>  return {<br>    count: 0,<br>  };<br>}</pre><h4>methods:</h4><ul><li>Purpose: Define methods that can be called from the template or within the component.</li><li>Usage: Returns an object containing methods.</li></ul><pre>methods: {<br>  increment() {<br>    this.count++;<br>  }<br>}</pre><h4>computed:</h4><ul><li>Purpose: Define computed properties based on reactive data.</li><li>Usage: Returns an object containing computed properties.</li></ul><pre>computed: {<br>  doubledCount() {<br>    return this.count * 2;<br>  }<br>}</pre><h4>Composition API: Flexibility and Modularity</h4><p>In the Composition API, functions like ref, reactive, and computed are employed within the setup function to create and expose reactive values.</p><h4>ref:</h4><ul><li>Purpose: Create a reactive reference to a simple value.</li><li>Usage: Returns a reactive object with a .value property.</li></ul><pre>import { ref } from &#39;vue&#39;;<br><br>const count = ref(0);</pre><h4>reactive:</h4><ul><li>Purpose: Create a fully reactive object.</li><li>Usage: Takes an object as an argument and returns a reactive proxy of that object.</li></ul><pre>import { reactive } from &#39;vue&#39;;<br><br>const user = reactive({<br>  name: &#39;John Doe&#39;,<br>  age: 25,<br>});</pre><h4>computed (Composition API):</h4><ul><li>Purpose: Define computed properties based on reactive values.</li><li>Usage: Takes a getter function and returns a reactive ref with a .value property.</li></ul><pre>import { ref, computed } from &#39;vue&#39;;<br><br>const count = ref(0);<br>const doubledCount = computed(() =&gt; count.value * 2);</pre><h4>When to Use What:</h4><ul><li>Use ref for Simple Values: If you need a reactive reference to a simple value, use ref.</li><li>Use reactive for Objects: If you have an object with multiple reactive properties, use reactive to create a fully reactive object.</li><li>Use computed in Both APIs for Computed Properties: Whether in the Options API or the Composition API, computed is used to define computed properties.</li><li>Use data, methods, and computed in Options API: In the Options API, these options are the conventional way to structure a component.</li><li>Use ref, reactive, and computed in Composition API: In the Composition API, these functions are more modular and provide a clearer separation of concerns.</li></ul><h4>Differences with Composition API:</h4><ul><li>ref vs data: In the Composition API, ref is used to create reactive references, whereas in the Options API, data is used for reactive data properties.</li><li>reactive vs data: reactive in the Composition API is similar to data in the Options API, as it is used to create fully reactive objects.</li><li>computed (Composition API): In the Composition API, computed takes a getter function directly, providing a more concise syntax compared to the Options API.</li></ul><blockquote>While the Composition API is a powerful alternative in Vue 3, the Options API remains fully supported and is suitable for many scenarios, especially for smaller projects or when developers are more comfortable with its syntax. The choice between the Options API and the Composition API depends on your project requirements, team preferences, and the complexity of your application.</blockquote><h3>Conclusion:</h3><blockquote>The Composition API introduces a more flexible and modular way to structure Vue components by utilizing functions like ref, reactive, and computed within the setup function. While the Options API remains valid and suitable for many scenarios, the Composition API offers a more scalable and organized approach, particularly for complex components and larger projects. The choice between them depends on your project&#39;s requirements and your team&#39;s preferences.</blockquote><blockquote>By mastering the usage of data, methods, and computed in both APIs, you&#39;ll be equipped to navigate the Vue 3 landscape with confidence, building dynamic and maintainable applications. Whether you opt for the classic elegance of the Options API or embrace the flexibility of the Composition API, Vue 3 empowers you to create robust and scalable frontend solutions.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07d6993db3c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js3: Project Setup using Vue Cli and GUI]]></title>
            <link>https://kushaler2010.medium.com/vue-js3-project-setup-using-vue-cli-and-gui-2b30d3e23484?source=rss-3e1200b23dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b30d3e23484</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[vue-cli]]></category>
            <category><![CDATA[vuejs-3]]></category>
            <dc:creator><![CDATA[Kushal Bansal]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 11:40:48 GMT</pubDate>
            <atom:updated>2024-02-02T11:57:48.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*akmnL8Y6xnXPKqTy4SR9bA.png" /></figure><h3>A Guide to Creating a Vue 3 and TypeScript Project with Vue CLI</h3><p>In the ever-evolving landscape of web development, staying on top of the latest technologies is crucial. Vue.js, a progressive JavaScript framework, has gained widespread popularity for its simplicity and flexibility. When combined with TypeScript, a statically typed superset of JavaScript, developers can create robust and maintainable code.</p><p>In this blog post, we’ll walk through the process of setting up a Vue 3 project with TypeScript using the Vue CLI. The Vue CLI is a powerful tool that streamlines the process of scaffolding and managing Vue projects, making it an ideal choice for both beginners and experienced developers.</p><h3>Installation</h3><p>Node Version Requirement</p><p>Vue CLI 4.x requires <a href="https://nodejs.org/">Node.js</a> version 8.9 or above (v10+ recommended). You can manage multiple versions of Node on the same machine with <a href="https://github.com/tj/n">n</a>, <a href="https://github.com/creationix/nvm">nvm</a> or <a href="https://github.com/coreybutler/nvm-windows">nvm-windows</a>.</p><p>To install the new package, use one of the following commands. You need administrator privileges to execute these unless npm was installed on your system through a Node.js version manager (e.g. n or nvm).</p><pre>npm install -g @vue/cli<br># OR<br>yarn global add @vue/cli</pre><p>After installation, you will have access to the vue binary in your command line. You can verify that it is properly installed by simply running vue, which should present you with a help message listing all available commands.</p><p>You can check you have the right version with this command:</p><pre>vue --version<br>// Expected output should be something like @vue/cli 4.5.12</pre><h3>Upgrading</h3><p>To upgrade the global Vue CLI package, you need to run:</p><pre>npm update -g @vue/cli<br># OR<br>yarn global upgrade --latest @vue/cli</pre><h3>Creating a Project using vue cli</h3><p>To create a new project, run:</p><pre>vue create hello-world</pre><p>You will be prompted to pick a preset. You can either choose the default preset which comes with a basic Babel + ESLint setup, or select “Manually select features” to pick the features you need.</p><pre>Vue CLI v4.5.12<br>? Please pick a preset: <br>  Default ([Vue 2] babel, eslint) <br>  Default (Vue 3 Preview) ([Vue 3] babel, eslint) <br>❯ Manually select features</pre><p>The default setup is great for quickly prototyping a new project, while the manual setup provides more options that are likely needed for more production-oriented projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6J1uZ1VBe5GIjlaBcm1Kg.png" /></figure><p><em>If you’re planning on building something like a business application or app, testing is an important part of development and should be added. In that case, make sure you check the </em><strong><em>Unit Testing</em></strong><em> and </em><strong><em>E2E Testing</em></strong><em> features.</em></p><p>The vue create command has a number of options and you can explore them all by running:</p><pre>vue create --help</pre><h3>Creating the project</h3><p>The CLI will now create the project, create the necessary configuration files and download all the required npm packages. This will take some time and you will see below output</p><pre>🎉  Successfully created project your-project-name.<br>👉  Get started with the following commands:$ cd your-project-name<br>$ npm run serve</pre><p>Once it is run, it will show you something like the below:</p><pre>DONE  Compiled successfully in 2767ms                                           3:01:22 PMApp running at:<br>  - Local:   http://localhost:8080/ <br>  - Network: http://192.168.192.225:8080/Note that the development build is not optimized.<br>  To create a production build, run npm run build.No issues found.</pre><h3>Using the GUI</h3><p>ou can also create and manage projects using a graphical interface with the vue ui command:</p><pre>vue ui</pre><p>The above command will open a browser window with a GUI that guides you through the project creation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEVnjxp5w2y3S1SXHilZ-Q.png" /></figure><h3>Pulling 2.x Templates (Legacy)</h3><p>Vue CLI &gt;= 3 uses the same vue binary, so it overwrites Vue CLI 2 (vue-cli). If you still need the legacy vue init functionality, you can install a global bridge:</p><pre>npm install -g @vue/cli-init<br># vue init now works exactly the same as vue-cli@2.x<br>vue init webpack my-project</pre><h3>Installing Plugins in an Existing Project</h3><p>Each CLI plugin ships with a generator (which creates files) and a runtime plugin (which tweaks the core webpack config and injects commands). When you use vue create to create a new project, some plugins will be pre-installed for you based on your feature selection. In case you want to install a plugin into an already created project, you can do so with the vue add command:</p><pre>vue add eslint</pre><blockquote>vue add is specifically designed for installing and invoking Vue CLI plugins. It is not meant as a replacement for normal npm packages. For normal npm packages, you should still use your package manager of choice.</blockquote><p>If a plugin is already installed, you can skip the installation and only invoke its generator with the vue invoke command. The command takes the same arguments as vue add.</p><blockquote>If for some reason your plugins are listed in a package.json file other than the one located in your project, you can set the vuePlugins.resolveFrom option in the project package.json with the path to the folder containing the other package.json file.</blockquote><p>For example, if you have a .config/package.json file:</p><pre>{<br>  &quot;vuePlugins&quot;: {<br>    &quot;resolveFrom&quot;: &quot;.config&quot;<br>  }<br>}</pre><h3>Presets</h3><p>A Vue CLI preset is a JSON object that contains pre-defined options and plugins for creating a new project so that the user doesn’t have to go through the prompts to select them.</p><p>Presets saved during vue create are stored in a configuration file in your user home directory (~/.vuerc). You can directly edit this file to tweak / add / delete the saved presets.</p><p>Here’s an example preset:</p><pre>{<br>  &quot;useConfigFiles&quot;: true,<br>  &quot;cssPreprocessor&quot;: &quot;sass&quot;,<br>  &quot;plugins&quot;: {<br>    &quot;@vue/cli-plugin-babel&quot;: {},<br>    &quot;@vue/cli-plugin-eslint&quot;: {<br>      &quot;config&quot;: &quot;airbnb&quot;,<br>      &quot;lintOn&quot;: [&quot;save&quot;, &quot;commit&quot;]<br>    },<br>    &quot;@vue/cli-plugin-router&quot;: {},<br>    &quot;@vue/cli-plugin-vuex&quot;: {}<br>  }<br>}</pre><p>The preset data is used by plugin generators to generate corresponding project files. In addition to the above fields, you can also add additional configuration for integrated tools:</p><pre>{<br>  &quot;useConfigFiles&quot;: true,<br>  &quot;plugins&quot;: {...},<br>  &quot;configs&quot;: {<br>    &quot;vue&quot;: {...},<br>    &quot;postcss&quot;: {...},<br>    &quot;eslintConfig&quot;: {...},<br>    &quot;jest&quot;: {...}<br>  }<br>}</pre><h3>CLI Service</h3><h3>Using the Binary</h3><p>Inside a Vue CLI project, @vue/cli-service installs a binary named vue-cli-service. You can access the binary directly as vue-cli-service in npm scripts, or as ./node_modules/.bin/vue-cli-service from the terminal.</p><p>This is what you will see in the package.json of a project using the default preset:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;serve&quot;: &quot;vue-cli-service serve&quot;,<br>    &quot;build&quot;: &quot;vue-cli-service build&quot;<br>  }<br>}</pre><p>You can invoke these scripts using either npm or Yarn:</p><pre>npm run serve<br># OR<br>yarn serve</pre><blockquote>You can run scripts with additional features using the GUI with the vue ui command.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ifgp6yAfJo_I71aY7y9dmg.png" /></figure><p>Now, you have successfully created Vue 3 project using the Vue CLI. This example demonstrates a basic setup, but as your project grows, TypeScript will provide enhanced tooling and improved code quality, making it easier to maintain and scale your application. For official documentation of this, please refer to <a href="https://vuejs.org/">https://vuejs.org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b30d3e23484" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Vuex: Efficient State Management for E-commerce in Vue.js]]></title>
            <link>https://kushaler2010.medium.com/mastering-vuex-efficient-state-management-for-e-commerce-in-vue-js-80614b93ae36?source=rss-3e1200b23dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/80614b93ae36</guid>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nuxt]]></category>
            <dc:creator><![CDATA[Kushal Bansal]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 02:20:03 GMT</pubDate>
            <atom:updated>2023-11-26T02:22:36.169Z</atom:updated>
            <content:encoded><![CDATA[<p>State management in Vue.js applications is a crucial aspect, especially in complex scenarios like e-commerce platforms. Vuex, Vue’s official state management library, provides a structured and organized approach to managing application state. In this comprehensive guide, we’ll explore Vuex’s core components — State, Mutations, Actions, and Getters — while implementing a detailed example of an e-commerce platform to manage product inventory and user shopping carts.</p><h3>Understanding Vuex Components</h3><h4>State</h4><ul><li>Role: Represents the application’s data, including product inventory and user cart details.</li><li>Purpose: Centralizes and tracks the current state of the e-commerce platform.</li><li>Example:</li></ul><p>The state might contain product listings, cart items, user details, and other relevant data.</p><h4>Mutations</h4><ul><li>Role: Performs synchronous modifications to the state.</li><li>Purpose: Ensures controlled and explicit changes to the state based on defined actions.</li><li>Example:</li></ul><p>Mutations handle adding/removing products from the cart, updating product availability, and modifying user-related data.</p><h4>Actions</h4><ul><li>Role: Executes asynchronous operations and commits mutations.</li><li>Purpose: Handles API requests, data processing, and commits mutations to update the state.</li><li>Example:</li></ul><p>Actions manage fetching product data, updating the user cart, and handling checkout operations.</p><h4>Getters</h4><ul><li>Role: Retrieves and computes derived state data.</li><li>Purpose: Provides computed access to specific state properties or performs calculations.</li><li>Example:</li></ul><p>Getters calculate the total cart value, available product quantities, and user order history.</p><h3>Implementing Vuex in an E-commerce Application</h3><h3>Setting Up Vuex Store</h3><p>Let’s create a Vuex store to manage the e-commerce application’s state:</p><pre>// store/index.js<br>import Vue from &#39;vue&#39;;<br>import Vuex from &#39;vuex&#39;;<br><br>Vue.use(Vuex);<br><br>export default new Vuex.Store({<br>  state: {<br>    products: [<br>      { id: 1, name: &#39;Product A&#39;, price: 20, quantity: 10 },<br>      { id: 2, name: &#39;Product B&#39;, price: 30, quantity: 15 },<br>      { id: 3, name: &#39;Product C&#39;, price: 25, quantity: 8 },<br>      // ... more sample product data<br>    ],<br>    cart: [],<br>    // ... other relevant state properties<br>  },<br>  mutations: {<br>    // Mutations to modify the state<br>    addToCart(state, product) {<br>      // Add logic to modify cart and product quantities<br>    },<br>    removeFromCart(state, product) {<br>      // Add logic to remove item from cart and update product quantities<br>    },<br>  },<br>  actions: {<br>    // Actions to perform async operations and commit mutations<br>    addToCart({ commit }, product) {<br>      commit(&#39;addToCart&#39;, product);<br>    },<br>    removeFromCart({ commit }, product) {<br>      commit(&#39;removeFromCart&#39;, product);<br>    },<br>  },<br>  getters: {<br>    // Getters to retrieve and compute derived state data<br>    getTotalCartValue: state =&gt; {<br>      // Compute total cart value based on items and quantities<br>    },<br>  },<br>});</pre><h3>Integrating Vuex with Vue Components</h3><h4>ProductListing.vue</h4><p>This component displays available products for users to browse and add to their cart:</p><pre>&lt;!-- ProductListing.vue --&gt;<br>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h2&gt;Product Listings&lt;/h2&gt;<br>    &lt;ul&gt;<br>      &lt;li v-for=&quot;product in products&quot; :key=&quot;product.id&quot;&gt;<br>        {{ product.name }} - ${{ product.price }}<br>        &lt;button @click=&quot;addToCart(product)&quot;&gt;Add to Cart&lt;/button&gt;<br>      &lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>export default {<br>  computed: {<br>    products() {<br>      return this.$store.state.products;<br>    },<br>  },<br>  methods: {<br>    addToCart(product) {<br>      this.$store.dispatch(&#39;addToCart&#39;, product);<br>    },<br>  },<br>};<br>&lt;/script&gt;</pre><h4>Cart.vue</h4><p>This component represents the user’s shopping cart:</p><pre>&lt;!-- Cart.vue --&gt;<br>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h2&gt;Shopping Cart&lt;/h2&gt;<br>    &lt;ul&gt;<br>      &lt;li v-for=&quot;item in cartItems&quot; :key=&quot;item.id&quot;&gt;<br>        {{ item.name }} - ${{ item.price }}<br>      &lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>export default {<br>  computed: {<br>    cartItems() {<br>      return this.$store.state.cart;<br>    },<br>    totalCartValue() {<br>      return this.$store.getters.getTotalCartValue;<br>    },<br>  },<br>};<br>&lt;/script&gt;</pre><h3>Conclusion: Leveraging Vuex for E-commerce Solutions</h3><p>In conclusion, Vuex offers a structured and organized approach to managing complex state in Vue.js applications, particularly in e-commerce contexts. By leveraging Vuex’s State, Mutations, Actions, and Getters, developers can build scalable and maintainable e-commerce platforms.</p><p>Vuex’s centralized store ensures consistency and predictability in data flow, facilitating smooth interactions between components. With Vuex, managing product inventory, user shopping carts, and coordinating checkout processes becomes streamlined and efficient. The structured nature of Vuex simplifies the retrieval and manipulation of data across different components, ensuring a single source of truth and minimizing potential conflicts in state management.</p><p>By utilizing Vuex’s mutations, actions, and getters, developers can orchestrate seamless updates to the store, triggering controlled modifications to the application’s state. This results in a more robust and maintainable codebase, as well as improved scalability for handling increased complexity within e-commerce applications.</p><p>In essence, Vuex acts as a reliable cornerstone for maintaining application-wide data, enabling developers to craft responsive, organized, and scalable e-commerce solutions with Vue.js. Its cohesive structure enhances the maintainability and extensibility of applications, offering a solid foundation for future enhancements and optimizations.</p><p>In the dynamic landscape of e-commerce, Vuex stands as a powerful ally, ensuring that the complexities of managing product inventory, user interactions, and transactional flows are effectively managed while maintaining a high standard of performance and user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80614b93ae36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drupal 9, 10 Queue Worker with Batch Processing and Guzzle API]]></title>
            <link>https://kushaler2010.medium.com/drupal-9-10-queue-worker-with-batch-processing-and-guzzle-api-4d1b41327550?source=rss-3e1200b23dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d1b41327550</guid>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[queue-worker]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[drupal-9]]></category>
            <dc:creator><![CDATA[Kushal Bansal]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 02:42:46 GMT</pubDate>
            <atom:updated>2023-08-05T02:42:46.468Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we will explore the powerful features of Drupal 9.4 Queue Worker with Batch Processing and Guzzle API Integration, using a custom module named ‘Custom Queue Worker.’ By integrating the Guzzle HTTP client, we will fetch data from an external API endpoint and efficiently process it using batch operations. The Queue Worker API enables background processing, and Guzzle simplifies the API requests, making it a seamless experience for developers to manage large-scale data updates.</p><h4>Example Module: ‘Custom Queue Worker’</h4><p>To demonstrate Drupal 9.4 Queue Worker with Batch Processing and Guzzle API Integration, we will create a custom module called ‘Custom Queue Worker.’ In this example, we will fetch data from an external API and process it using batch operations.</p><h4>Step 1: Module Setup</h4><p>Let’s set up the module:</p><ol><li>Create a new folder named ‘custom_queue_worker’ inside the ‘modules/custom’ directory of your Drupal installation.</li><li>Inside the ‘custom_queue_worker’ folder, create two files:<br>a. ‘custom_queue_worker.info.yml’: This file contains the module metadata.<br>b. ‘custom_queue_worker.module’: This file holds the module’s PHP code.</li><li>Add the following code to ‘custom_queue_worker.info.yml’:</li></ol><pre>name: &#39;Custom Queue Worker&#39;<br>type: module<br>description: &#39;Demonstrates Drupal 9.4 Queue Worker with Batch Processing and Guzzle API Integration.&#39;<br>core_version_requirement: ^9 || ^10<br>package: Custom<br>dependencies:<br>  - &#39;queue&#39;<br>  - &#39;http_client&#39;</pre><h4>Step 2: Create the Services Configuration</h4><p>Next, let’s define the service configuration for the ‘Custom Queue Worker’ module.</p><ol><li>Create a new file named ‘custom_queue_worker.services.yml’ inside the ‘custom_queue_worker’ module folder.</li><li>Add the following code to ‘custom_queue_worker.services.yml’:</li></ol><pre>services:<br>  custom_queue_worker.http_client:<br>    class: GuzzleHttp\Client<br>    factory: [&#39;@http_client_factory&#39;, &#39;fromOptions&#39;]<br>    arguments:<br>      - base_uri: &#39;https://api.example.com&#39;<br><br>  custom_queue_worker.batch_builder:<br>    class: Drupal\Core\Batch\BatchBuilder<br><br>  custom_queue_worker.queue_worker:<br>    class: Drupal\custom_queue_worker\Plugin\QueueWorker\CustomQueueWorkerQueueWorker<br>    arguments:<br>      - &#39;@http_client_factory&#39;<br>      - &#39;@batch.builder&#39;<br>    tags:<br>      - { name: queue_worker }</pre><h4>Step 3: Implement Batch Processing with Guzzle API Integration</h4><p>Next, let’s implement the batch processing with Guzzle API integration:</p><ol><li>Add the following code to ‘custom_queue_worker.module’:</li></ol><pre>&lt;?php<br><br>use Drupal\Core\Queue\QueueWorkerBase;<br>use Symfony\Component\DependencyInjection\ContainerInterface;<br>use Drupal\Core\Plugin\ContainerFactoryPluginInterface;<br>use GuzzleHttp\Client;<br>use Drupal\Core\Batch\BatchBuilder;<br>use Drupal\Core\Batch\BatchManagerInterface;<br><br>/**<br> * Implements hook_help().<br> */<br>function custom_queue_worker_help($route_name, $route_parameters) {<br>  // ... (same as before) ...<br>}<br><br>/**<br> * Implements hook_menu().<br> */<br>function custom_queue_worker_menu() {<br>  // ... (same as before) ...<br>}<br><br>/**<br> * Batch processing callback.<br> */<br>function custom_queue_worker_run_batch() {<br>  // ... (same as before) ...<br>}</pre><h4>Step 4: Create the Queue Worker</h4><p>Now, let’s create the Queue Worker with batch processing and Guzzle API integration:</p><ol><li>Create a new file named ‘CustomQueueWorkerQueueWorker.php’ inside the ‘src/Plugin/QueueWorker’ directory within the ‘custom_queue_worker’ module folder.</li><li>Add the following code to ‘CustomQueueWorkerQueueWorker.php’:</li></ol><pre>&lt;?php<br><br>namespace Drupal\custom_queue_worker\Plugin\QueueWorker;<br><br>use Drupal\Core\Queue\QueueWorkerBase;<br>use Symfony\Component\DependencyInjection\ContainerInterface;<br>use Drupal\Core\Plugin\ContainerFactoryPluginInterface;<br>use GuzzleHttp\Client;<br>use Drupal\Core\Batch\BatchBuilderInterface;<br>use GuzzleHttp\Exception\RequestException;<br>use GuzzleHttp\Psr7\Request;<br><br>/**<br> * Process batch API data fetcher.<br> *<br> * @QueueWorker(<br> *   id = &quot;custom_queue_worker_queue&quot;,<br> *   title = @Translation(&quot;Custom Queue Worker Queue&quot;),<br> *   cron = {&quot;time&quot; = 60}<br> * )<br> */<br>class CustomQueueWorkerQueueWorker extends QueueWorkerBase implements ContainerFactoryPluginInterface {<br><br>  /**<br>   * The HTTP client.<br>   *<br>   * @var \GuzzleHttp\ClientInterface<br>   */<br>  protected $httpClient;<br><br>  /**<br>   * The batch builder.<br>   *<br>   * @var \Drupal\Core\Batch\BatchBuilderInterface<br>   */<br>  protected $batchBuilder;<br><br>  /**<br>   * Constructs a new CustomQueueWorkerQueueWorker object.<br>   *<br>   * @param \GuzzleHttp\Client $http_client<br>   *   The Guzzle HTTP client.<br>   * @param \Drupal\Core\Batch\BatchBuilderInterface $batch_builder<br>   *   The batch builder.<br>   */<br>  public function __construct(Client $http_client, BatchBuilderInterface $batch_builder) {<br>    $this-&gt;httpClient = $http_client;<br>    $this-&gt;batchBuilder = $batch_builder;<br>  }<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {<br>    return new static(<br>      $container-&gt;get(&#39;custom_queue_worker.http_client&#39;),<br>      $container-&gt;get(&#39;custom_queue_worker.batch_builder&#39;)<br>    );<br>  }<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public function processItem($data) {<br>    $start = $data[&#39;start&#39;];<br>    $end = $data[&#39;end&#39;];<br><br>    $api_url = &#39;/api/data/&#39; . $start . &#39;/&#39; . $end;<br><br>    try {<br>      $response = $this-&gt;httpClient-&gt;get($api_url);<br>      if ($response-&gt;getStatusCode() === 200) {<br>        $api_data = json_decode($response-&gt;getBody(), TRUE);<br><br>        // Batch processing to handle API data.<br>        $batch = $this-&gt;batchBuilder-&gt;setTitle(t(&#39;Processing API data from @start to @end&#39;, [&#39;@start&#39; =&gt; $start, &#39;@end&#39; =&gt; $end]))<br>          -&gt;setFinishCallback([$this, &#39;batchFinished&#39;])<br>          -&gt;setInitMessage(t(&#39;Batch processing is starting.&#39;))<br>          -&gt;setProgressMessage(t(&#39;Processed @current out of @total items.&#39;))<br>          -&gt;setErrorMessage(t(&#39;An error occurred during batch processing.&#39;))<br>          -&gt;addOperation([$this, &#39;processAPIData&#39;], [$api_data])<br>          -&gt;set(&#39;api_data&#39;, $api_data)<br>          -&gt;set(&#39;processed_items&#39;, 0)<br>          -&gt;set(&#39;total_items&#39;, count($api_data))<br>          -&gt;execute();<br>      }<br>    } catch (RequestException $e) {<br>      watchdog_exception(&#39;custom_queue_worker&#39;, $e);<br>    }<br>  }<br><br>  /**<br>   * Batch process API data.<br>   *<br>   * @param array $api_data<br>   *   The API data.<br>   * @param array $context<br>   *   The batch context.<br>   */<br>  public function processAPIData(array $api_data, array &amp;$context) {<br>    $batch_size = 10; // Number of items to process in each batch.<br><br>    $start = $context[&#39;sandbox&#39;][&#39;processed_items&#39;];<br>    $end = $start + $batch_size;<br>    $end = min($end, count($api_data));<br><br>    // Your logic to process the API data here.<br>    // Example: Save data to entities, update nodes, etc.<br><br>    // Update batch progress.<br>    $context[&#39;sandbox&#39;][&#39;processed_items&#39;] += $end - $start;<br>    $context[&#39;message&#39;] = t(&#39;Processed @current out of @total items.&#39;, [<br>      &#39;@current&#39; =&gt; $context[&#39;sandbox&#39;][&#39;processed_items&#39;],<br>      &#39;@total&#39; =&gt; $context[&#39;sandbox&#39;][&#39;total_items&#39;],<br>    ]);<br><br>    // Set the batch progress percentage.<br>    $context[&#39;finished&#39;] = $context[&#39;sandbox&#39;][&#39;processed_items&#39;] / $context[&#39;sandbox&#39;][&#39;total_items&#39;];<br>  }<br><br>  /**<br>   * Batch finished callback.<br>   *<br>   * @param bool $success<br>   *   TRUE if the batch processed successfully, otherwise FALSE.<br>   * @param array $results<br>   *   The batch results.<br>   * @param array $operations<br>   *   The batch operations.<br>   */<br>  public function batchFinished($success, array $results, array $operations) {<br>    if ($success) {<br>      drupal_set_message(t(&#39;Batch processing completed successfully.&#39;));<br>    } else {<br>      drupal_set_message(t(&#39;Batch processing encountered errors.&#39;), &#39;error&#39;);<br>    }<br>  }<br>}</pre><h4>Step 5: Enable the Module</h4><p>To run our example, enable the ‘Custom Queue Worker’ module through the Drupal admin interface or by using Drush: drush en custom_queue_worker.</p><h4>Step 6: Run the Fetch Data Example</h4><p>To run the example, follow these steps:</p><ol><li>Visit the URL ‘/example/fetch_data’ on your Drupal site while logged in as an administrator.</li><li>A message will be displayed, indicating that “Fetch Data Example with Guzzle API Integration is processing in the background. You will be notified once it completes.”</li><li>The background processing will start automatically, and you will see progress messages in the Drupal status report or log, indicating the number of items processed.</li><li>The batch process will handle the data received from the external API, allowing you to process and save data to entities or update nodes, depending on the specific use case.</li></ol><h4>Conclusion:</h4><p>In this blog post, we explored the powerful features of Drupal 9.4 Queue Worker with Batch Processing and Guzzle API Integration. By integrating Guzzle HTTP client, we fetched data from an external API endpoint and efficiently processed it using batch operations. The Queue Worker API allowed for seamless background processing of tasks, enabling Drupal to handle large-scale data updates without affecting the main request/response cycle.</p><p>With the ‘Custom Queue Worker’ module as a practical example, we demonstrated how Drupal’s flexible architecture and powerful APIs facilitate seamless integration of external services, unlocking the full potential of your Drupal-powered websites and applications.</p><p>As you explore and experiment with Drupal’s capabilities, remember that the possibilities are endless. Whether it’s integrating with external APIs, handling complex data processing, or delivering exceptional user experiences, Drupal empowers you to build robust, scalable, and future-proof solutions. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d1b41327550" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Creativity with Paragraph Behaviors in Drupal: A Hands-on Guide]]></title>
            <link>https://kushaler2010.medium.com/unlocking-creativity-with-paragraph-behaviors-in-drupal-a-hands-on-guide-8add21b58bf3?source=rss-3e1200b23dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8add21b58bf3</guid>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[drupal-10]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[drupal-9]]></category>
            <dc:creator><![CDATA[Kushal Bansal]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 12:46:11 GMT</pubDate>
            <atom:updated>2023-07-26T12:46:11.340Z</atom:updated>
            <content:encoded><![CDATA[<p>Drupal, a powerful content management system, offers an array of features to empower developers and content editors alike. One such feature is Paragraphs, which allows for dynamic content creation by breaking down pages into structured and reusable components. In this blog, we will explore the world of Paragraph Behaviors in Drupal and demonstrate their potential using three custom behaviors: “Text Color,” “Background Color,” and “Border Style.” Let’s unlock the creativity of content editors by enabling them to design visually stunning pages without relying on complex customizations.</p><p>Paragraph Behaviors in Drupal allow us to extend the functionality of Paragraphs without altering the core code. By creating custom behaviors, we can enable content editors to add extra fields to Paragraph entities and enhance their display in a flexible and modular way.</p><p>In this example, we will implement three custom Paragraph Behaviors: “Text Color,” “Background Color,” and “Border Style.” Each behavior will provide a unique field for content editors to customize the appearance of Paragraphs on their pages.</p><h4>Step 1: Setting Up the Environment</h4><p>Before we begin, ensure you have Drupal 9 or 10 installed, along with the “custom_paragraph_behavior” module. This module will serve as the foundation for our custom behaviors.</p><p>Step 2: Implementing the “Text Color” Behavior</p><p>The “Text Color” behavior allows content editors to set the color of the text within the Paragraph. Let’s go through the implementation:</p><ol><li>Define the Custom Behavior Interface:</li></ol><ul><li>Create CustomTextColorBehaviorInterface.php inside the custom_paragraph_behavior/src/Plugin/ParagraphBehavior/ folder.</li></ul><pre>&lt;?php<br><br>namespace Drupal\custom_paragraph_behavior\Plugin\ParagraphBehavior;<br><br>use Drupal\Component\Plugin\PluginInspectionInterface;<br><br>interface CustomTextColorBehaviorInterface extends PluginInspectionInterface {<br><br>  // Add custom methods and signatures here as needed.<br><br>}</pre><h4>Step2: Implement the “Text Color” Behavior Plugin:</h4><ul><li>Create CustomTextColorBehavior.php inside the same folder.</li></ul><pre>&lt;?php<br><br>namespace Drupal\custom_paragraph_behavior\Plugin\ParagraphBehavior;<br><br>use Drupal\paragraphs\ParagraphBehaviorBase;<br>use Drupal\Core\Form\FormStateInterface;<br><br>/**<br> * Provides a custom Paragraph behavior to set text color.<br> *<br> * @ParagraphBehavior(<br> *   id = &quot;custom_text_color_behavior&quot;,<br> *   label = @Translation(&quot;Custom Text Color Behavior&quot;),<br> *   description = @Translation(&quot;Adds a &#39;text color&#39; field to the Paragraph entity.&quot;),<br> * )<br> */<br>class CustomTextColorBehavior extends ParagraphBehaviorBase {<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public static function isApplicable($paragraph_type) {<br>    // Apply this behavior to all Paragraph types for this example.<br>    return TRUE;<br>  }<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public function buildBehaviorForm(ParagraphInterface $paragraph, array &amp;$form, FormStateInterface $form_state) {<br>    // Add a &quot;text color&quot; textfield to the Paragraph edit form.<br>    $form[&#39;field_text_color&#39;] = [<br>      &#39;#type&#39; =&gt; &#39;textfield&#39;,<br>      &#39;#title&#39; =&gt; $this-&gt;t(&#39;Text Color&#39;),<br>      &#39;#default_value&#39; =&gt; $paragraph-&gt;get(&#39;field_text_color&#39;)-&gt;value,<br>    ];<br>  }<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public function extractFormValues(ParagraphInterface $paragraph, array &amp;$form, FormStateInterface $form_state) {<br>    // Save the value of the &quot;text color&quot; textfield to the Paragraph entity.<br>    $paragraph-&gt;set(&#39;field_text_color&#39;, $form_state-&gt;getValue([&#39;fields&#39;, &#39;field_text_color&#39;]));<br>  }<br><br>}</pre><p>Register the “Text Color” Behavior:</p><h4>Step3: Implementing the “Background Color” Behavior</h4><p>The “Background Color” behavior allows content editors to set a background color for the Paragraph. Let’s proceed with the implementation:</p><pre>&lt;?php<br><br>namespace Drupal\custom_paragraph_behavior\Plugin\ParagraphBehavior;<br><br>use Drupal\Component\Plugin\PluginInspectionInterface;<br><br>interface CustomBackgroundColorBehaviorInterface extends PluginInspectionInterface {<br><br>  // Add custom methods and signatures here as needed.<br><br>}</pre><p>Create CustomBackgroundColorBehavior.php inside the same folder.</p><pre>&lt;?php<br><br>namespace Drupal\custom_paragraph_behavior\Plugin\ParagraphBehavior;<br><br>use Drupal\paragraphs\ParagraphBehaviorBase;<br>use Drupal\Core\Form\FormStateInterface;<br><br>/**<br> * Provides a custom Paragraph behavior to set background color.<br> *<br> * @ParagraphBehavior(<br> *   id = &quot;custom_background_color_behavior&quot;,<br> *   label = @Translation(&quot;Custom Background Color Behavior&quot;),<br> *   description = @Translation(&quot;Adds a &#39;background color&#39; field to the Paragraph entity.&quot;),<br> * )<br> */<br>class CustomBackgroundColorBehavior extends ParagraphBehaviorBase {<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public static function isApplicable($paragraph_type) {<br>    // Apply this behavior to all Paragraph types for this example.<br>    return TRUE;<br>  }<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public function buildBehaviorForm(ParagraphInterface $paragraph, array &amp;$form, FormStateInterface $form_state) {<br>    // Add a &quot;background color&quot; textfield to the Paragraph edit form.<br>    $form[&#39;field_background_color&#39;] = [<br>      &#39;#type&#39; =&gt; &#39;textfield&#39;,<br>      &#39;#title&#39; =&gt; $this-&gt;t(&#39;Background Color&#39;),<br>      &#39;#default_value&#39; =&gt; $paragraph-&gt;get(&#39;field_background_color&#39;)-&gt;value,<br>    ];<br>  }<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public function extractFormValues(ParagraphInterface $paragraph, array &amp;$form, FormStateInterface $form_state) {<br>    // Save the value of the &quot;background color&quot; textfield to the Paragraph entity.<br>    $paragraph-&gt;set(&#39;field_background_color&#39;, $form_state-&gt;getValue([&#39;fields&#39;, &#39;field_background_color&#39;]));<br>  }<br><br>}</pre><h4>Step4: Implementing the “Border Style” Behavior</h4><p>The “Border Style” behavior empowers content editors to select a border style for the Paragraph. Let’s proceed with the implementation:</p><ol><li>Define the Custom Behavior Interface:</li></ol><ul><li>Create CustomBorderStyleBehaviorInterface.php inside the custom_paragraph_behavior/src/Plugin/ParagraphBehavior/ folder.</li></ul><pre>&lt;?php<br><br>namespace Drupal\custom_paragraph_behavior\Plugin\ParagraphBehavior;<br><br>use Drupal\Component\Plugin\PluginInspectionInterface;<br><br>interface CustomBorderStyleBehaviorInterface extends PluginInspectionInterface {<br><br>  // Add custom methods and signatures here as needed.<br><br>}</pre><p>2. Implement the “Border Style” Behavior Plugin:</p><ul><li>Create CustomBorderStyleBehavior.php inside the same folder.</li></ul><pre>&lt;?php<br><br>namespace Drupal\custom_paragraph_behavior\Plugin\ParagraphBehavior;<br><br>use Drupal\paragraphs\ParagraphBehaviorBase;<br>use Drupal\Core\Form\FormStateInterface;<br><br>/**<br> * Provides a custom Paragraph behavior to set border style.<br> *<br> * @ParagraphBehavior(<br> *   id = &quot;custom_border_style_behavior&quot;,<br> *   label = @Translation(&quot;Custom Border Style Behavior&quot;),<br> *   description = @Translation(&quot;Adds a &#39;border style&#39; field to the Paragraph entity.&quot;),<br> * )<br> */<br>class CustomBorderStyleBehavior extends ParagraphBehaviorBase {<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public static function isApplicable($paragraph_type) {<br>    // Apply this behavior to all Paragraph types for this example.<br>    return TRUE;<br>  }<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public function buildBehaviorForm(ParagraphInterface $paragraph, array &amp;$form, FormStateInterface $form_state) {<br>    // Add a &quot;border style&quot; select field to the Paragraph edit form.<br>    $form[&#39;field_border_style&#39;] = [<br>      &#39;#type&#39; =&gt; &#39;select&#39;,<br>      &#39;#title&#39; =&gt; $this-&gt;t(&#39;Border Style&#39;),<br>      &#39;#options&#39; =&gt; [<br>        &#39;none&#39; =&gt; $this-&gt;t(&#39;None&#39;),<br>        &#39;solid&#39; =&gt; $this-&gt;t(&#39;Solid&#39;),<br>        &#39;dashed&#39; =&gt; $this-&gt;t(&#39;Dashed&#39;),<br>        &#39;dotted&#39; =&gt; $this-&gt;t(&#39;Dotted&#39;),<br>      ],<br>      &#39;#default_value&#39; =&gt; $paragraph-&gt;get(&#39;field_border_style&#39;)-&gt;value,<br>    ];<br>  }<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public function extractFormValues(ParagraphInterface $paragraph, array &amp;$form, FormStateInterface $form_state) {<br>    // Save the value of the &quot;border style&quot; select field to the Paragraph entity.<br>    $paragraph-&gt;set(&#39;field_border_style&#39;, $form_state-&gt;getValue([&#39;fields&#39;, &#39;field_border_style&#39;]));<br>  }<br><br>}</pre><h4>Step 5: Register the Custom Behavior Plugin</h4><p>Update the custom_paragraph_behavior.info.yml file.</p><pre>name: &#39;Custom Paragraph Behavior&#39;<br>type: module<br>core_version_requirement: ^9 || ^10<br>package: Custom<br>dependencies:<br>  - paragraphs: ^1.12</pre><h4>Step 6: Enabling the Custom Behaviors</h4><p>Enable the “Custom Paragraph Behavior” module through the Drupal admin interface or Drush.</p><h4>Step 7: Applying the Custom Behaviors</h4><p>Navigate to “Structure” &gt; “Paragraph types” and edit the desired Paragraph type(s). Under the “Manage form display” and “Manage display” tabs, select the custom behaviors you want to apply to each Paragraph type.</p><h4>Conclusion</h4><p>Drupal’s Paragraph Behaviors provide a powerful and intuitive way to enhance content creation and presentation. In this blog, we explored three custom behaviors: “Text Color,” “Background Color,” and “Border Style.” By implementing these behaviors, we enable content editors to unleash their creativity and design visually captivating pages with ease.</p><p>With Paragraph Behaviors, Drupal becomes a more flexible and dynamic content management system, empowering content editors to take control of the visual aspect of their websites without relying on complex customizations from developers. As you embark on your Drupal journey, consider exploring the world of custom behaviors and other powerful features to deliver stunning, user-centric web experiences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8add21b58bf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Computed Fields and How to use them in Drupal]]></title>
            <link>https://kushaler2010.medium.com/what-are-computed-fields-and-how-to-use-them-in-drupal-3a7996113c2f?source=rss-3e1200b23dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a7996113c2f</guid>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[drupal-9]]></category>
            <category><![CDATA[linkedin]]></category>
            <dc:creator><![CDATA[Kushal Bansal]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 12:36:39 GMT</pubDate>
            <atom:updated>2023-07-26T00:01:55.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9PDs7gJLknyWeL01IYo_A.png" /></figure><p>Drupal, one of the most popular content management systems, is renowned for its extensibility and flexibility. One of the powerful features it offers is the ability to create custom fields for entities. These fields can be of different types, such as text, number, or date. However, in some cases, you may need to compute a field’s value based on other entity data or external sources. This is where computed fields come into play.</p><p>In Drupal, computed fields can be created using various data types to suit different scenarios and use cases. Let’s assume that we have a custom content type called “Product” with fields like “Quantity” and “Unit Price,” and we want to calculate and display various computed fields based on these values.</p><ol><li>String (text): Computed Field: “Product Name Concatenation” Description: Concatenates the product name with a static text.</li></ol><p>Example Output:</p><blockquote>Product: “T-Shirt”</blockquote><blockquote>Computed Field Value: “T-Shirt — On Sale”</blockquote><p>2. Integer (integer): Computed Field: “Total Quantity in Stock” Description: Calculates the total quantity of a product in stock based on the sum of the available quantity and reserved quantity.</p><p>Example Output:</p><blockquote>Available Quantity: 50</blockquote><blockquote>Reserved Quantity: 10</blockquote><blockquote>Computed Field Value: 60</blockquote><p>3. Decimal (decimal): Computed Field: “Total Price” Description: Computes the total price of the product based on the quantity and unit price.</p><p>Example Output:</p><blockquote>Quantity: 5</blockquote><blockquote>Unit Price: $20.50</blockquote><blockquote>Computed Field Value: $102.50</blockquote><p>4. Float (float): Computed Field: “Discount Percentage” Description: Calculates the discount percentage based on the original price and the sale price.</p><p>Example Output:</p><blockquote>Original Price: $50.00</blockquote><blockquote>Sale Price: $40.00</blockquote><blockquote>Computed Field Value: 20.0 (percentage)</blockquote><p>5. Date (date): Computed Field: “Estimated Delivery Date” Description: Calculates the estimated delivery date based on the current date and shipping time.</p><p>Example Output:</p><blockquote>Current Date: July 25, 2023</blockquote><blockquote>Shipping Time (in days): 5</blockquote><blockquote>Computed Field Value: July 30, 2023</blockquote><p>6. Boolean (boolean): Computed Field: “Is In Stock” Description: Checks if the product is in stock based on the available quantity.</p><p>Example Output:</p><blockquote>Available Quantity: 0</blockquote><blockquote>Computed Field Value: false</blockquote><p>7. Entity Reference (entity_reference): Computed Field: “Related Products” Description: Fetches and displays related products based on certain criteria, such as category or tags.</p><p>Example Output:</p><blockquote>Criteria: Category “Electronics”</blockquote><blockquote>Computed Field Value: [Product A, Product B, Product C]</blockquote><p>8. File (file): Computed Field: “Product Manual” Description: Dynamically fetches and displays the product manual file based on the product type.</p><p>Example Output:</p><blockquote>Product Type: “Electronics”</blockquote><blockquote>Computed Field Value: [Link to Electronics Manual]</blockquote><p>9. Image (image): Computed Field: “Product Thumbnail” Description: Retrieves and displays a dynamic product thumbnail based on the product category.</p><p>Example Output:</p><blockquote>Product Category: “Apparel”</blockquote><blockquote>Computed Field Value: [Image of Apparel Product]</blockquote><p>10. Link (link): Computed Field: “Product Purchase Link” Description: Generates and displays a dynamic purchase link based on the product availability.</p><p>Example Output:</p><blockquote>Is Available: true</blockquote><blockquote>Computed Field Value: [Link to Purchase Product]</blockquote><p>These examples demonstrate the versatility of computed fields in Drupal and how they can be used to generate and display dynamic information based on various calculations and conditions. Depending on your specific use case, you can create computed fields of different data types to enhance your Drupal website’s functionality and user experience.</p><p>These are some of the primary data types in which computed fields can be created in Drupal. The choice of data type depends on the nature of the computed value you want to generate and display on your website. When creating a computed field, it’s essential to select the most appropriate data type to ensure accurate representation and proper handling of the computed data.</p><p>In this blog post, we’ll explore the process of adding a programmatically defined computed field to an entity in modern versions of Drupal (8, 9, and 10). Computed fields allow you to generate dynamic values on the fly, making it easier to display calculated or derived data within your Drupal content. To illustrate its usage, we’ll create a custom module that calculates and displays the total price of a product based on its quantity and unit price.</p><p><strong>Prerequisites</strong></p><p>Before we dive into the implementation, ensure you have the following prerequisites in place:</p><ol><li>A working Drupal installation (version 8 or later).</li><li>Basic understanding of Drupal’s module development and entity API.</li></ol><p><strong>Creating a Custom Module</strong></p><p>Firstly, create a custom module that will house our computed field. You can name it something like ‘custom_computed_field’ (replace ‘custom’ with your desired module name). Inside the module folder, create the necessary files (i.e., .info.yml, .module).</p><p><strong>Defining the Computed Field</strong></p><p>In Drupal 8 and later versions, we can use the ‘Field API’ to define our computed field. Within your custom module’s .module file, implement hook_entity_base_field_info() to declare the field:</p><pre>function custom_computed_field_entity_base_field_info(EntityTypeInterface $entity_type) {<br>  $fields = [];<br><br>  if ($entity_type-&gt;id() === &#39;node&#39; &amp;&amp; $entity_type-&gt;get(&#39;type&#39;) === &#39;product&#39;) {<br>    $fields[&#39;total_price&#39;] = BaseFieldDefinition::create(&#39;decimal&#39;)<br>      -&gt;setLabel(t(&#39;Total Price&#39;))<br>      -&gt;setDescription(t(&#39;The total price of the product.&#39;))<br>      -&gt;setComputed(TRUE)<br>      -&gt;setClass(&#39;\Drupal\custom_computed_field\Plugin\Field\TotalPriceComputedField&#39;)<br>      -&gt;setReadOnly(TRUE);<br>  }<br><br>  return $fields;<br>}</pre><p>In the above code, we’re creating a computed field called ‘total_price’ for the ‘product’ content type. The field is set as read-only and points to the class ‘\Drupal\custom_computed_field\Plugin\Field\TotalPriceComputedField’, which we will create next.</p><p>Creating the Computed Field Value Class:</p><p>Now, let’s create the class that will compute the field value. Inside your module, create a new folder called ‘src’ and add the necessary subfolders to match the class namespace.</p><p>In our example, we create the file ‘TotalPriceComputedField.php’ at ‘custom_computed_field/src/Plugin/Field’:</p><pre>namespace Drupal\custom_computed_field\Plugin\Field;<br><br>use Drupal\Core\Field\FieldItemListInterface;<br>use Drupal\Core\Field\Plugin\Field\FieldType\DecimalItem;<br>use Drupal\Core\Field\Plugin\Field\FieldType\DecimalItemInterface;<br><br>/**<br> * Plugin implementation of the &#39;total_price&#39; field type.<br> *<br> * @FieldType(<br> *   id = &quot;total_price&quot;,<br> *   label = @Translation(&quot;Total Price&quot;),<br> *   description = @Translation(&quot;This field displays the total price of the product.&quot;),<br> *   category = @Translation(&quot;Custom&quot;),<br> *   default_widget = &quot;number&quot;,<br> *   default_formatter = &quot;number_decimal&quot;<br> * )<br> */<br>class TotalPriceComputedField extends DecimalItem implements DecimalItemInterface {<br><br>  /**<br>   * {@inheritdoc}<br>   */<br>  public function computeValue() {<br>    // Calculate the total price based on quantity and unit price.<br>    $quantity = $this-&gt;getEntity()-&gt;get(&#39;field_quantity&#39;)-&gt;getValue();<br>    $unit_price = $this-&gt;getEntity()-&gt;get(&#39;field_unit_price&#39;)-&gt;getValue();<br><br>    // Ensure that both quantity and unit price are available.<br>    if (!empty($quantity) &amp;&amp; !empty($unit_price)) {<br>      $quantity = $quantity[0][&#39;value&#39;];<br>      $unit_price = $unit_price[0][&#39;value&#39;];<br>      $total_price = $quantity * $unit_price;<br><br>      $this-&gt;value = number_format($total_price, 2, &#39;.&#39;, &#39;&#39;);<br>    } else {<br>      $this-&gt;value = 0;<br>    }<br>  }<br><br>}</pre><p>In the above class, we’re extending the core ‘DecimalItem’ class to handle the computed field value. The actual computation of the value happens in the ‘computeValue()’ method. We fetch the quantity and unit price from other fields of the ‘product’ entity and calculate the total price by multiplying them. We then format the result to display a rounded decimal value with two decimal places.</p><p>After creating the necessary files and implementing the field and computation logic, enable your custom module.</p><p>Congratulations! You’ve successfully added a programmatically defined computed field to an entity in modern Drupal (8, 9, and 10). In our example, we created a custom module that computes and displays the total price of a product based on its quantity and unit price. Computed fields open up new possibilities for dynamically generating content and displaying calculated information based on other entity data or external sources. With this newfound knowledge, you can enhance your Drupal projects with custom computed fields tailored to your specific needs. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a7996113c2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading to Drupal 10]]></title>
            <link>https://kushaler2010.medium.com/upgrading-to-drupal-10-be962605b6ec?source=rss-3e1200b23dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/be962605b6ec</guid>
            <category><![CDATA[drupal-10]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[drupal-development]]></category>
            <category><![CDATA[drupal-upgrade]]></category>
            <dc:creator><![CDATA[Kushal Bansal]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 03:45:58 GMT</pubDate>
            <atom:updated>2022-12-30T06:18:37.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqgggbwR_5HzrAkFsm69sQ.png" /></figure><h3>Preparing for upgrading your drupal website to Drupal 10</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*TnNKpYwKk3x9Gk0W60xxcw.png" /></figure><p>With the latest major release of Drupal 10 on 14th December 2022, there are some exciting new features added to Drupal. It is build on top of Drupal 9, instead of complete codebase change. With this release all deprecated code has been removed, and dependencies are updated. This allows Drupal to deliver new value without disruption and gives developers sufficient time to update future API changes.</p><h3><strong>Things to do Before Upgrading to Drupal 10</strong></h3><h3><strong>Database Requirements</strong></h3><p>MySQL, MariaDB, or Percona Server (Recommended)</p><p><strong>Supported versions for Drupal 9 and 10</strong></p><ul><li>MariaDB 10.3.7+</li><li>MySQL/Percona 5.7.8+</li><li>Follow below link for amazon linux environments.</li></ul><p><a href="https://techviewleo.com/how-to-install-mariadb-server-on-amazon-linux/">https://techviewleo.com/how-to-install-mariadb-server-on-amazon-linux/</a></p><p><strong>Required configuration</strong></p><ul><li>InnoDB as the primary storage engine</li><li>The PDO database extension</li></ul><h3>Web Server Requirements</h3><p>Drupal works on Apache, Nginx, and other web servers.</p><h3>PHP requirements</h3><ol><li>Drupal 10 requires at least PHP 8.1. PHP 8.1.6 is recommended. Follow below link if using amazon linux environment:-</li></ol><p><a href="https://computingforgeeks.com/how-to-install-php-8-on-amazon-linux/"><strong>https://computingforgeeks.com/how-to-install-php-8-on-amazon-linux/</strong></a></p><p>Check available php versions : <strong>sudo amazon-linux-extras | grep php and sudo amazon-linux-extras enable php8.1 to anable php 8.1 version.</strong></p><ol><li>Required PHP extensions<strong>.</strong></li></ol><p><strong>PHP Data Objects</strong> extension must be activated for Drupal 10 to install and run correctly.</p><p><strong>PHP XML extension</strong> (for Blog API, Drupal, and Ping modules). This extension is enabled by default in a standard PHP installation.</p><p><strong>GD library</strong> is a required extension in Drupal 10 and is needed for image manipulation (resizing user pictures, image and image cache modules). ImageMagick is also supported for basic image manipulations in Drupal core but there is much less support from contributed modules.</p><p><strong>PHP OpenSSL</strong> extension is recommended to allow Drupal to make outgoing requests using HTTPS and is required when using the Update Manager. Read PHP OpenSSL requirements for more information.</p><p><strong>Drupal 10 require PHP compiled with JSON</strong>. JSON support is normally compiled as part of PHP core, but in case you’re getting errors like PHP Fatal error: Call to undefined function Drupal\\Component\\Serialization\\json_encode() in ... core/lib/Drupal/Component/Serialization/Json.php try adding the JSON extension.</p><p>The <strong>PHP cURL</strong> extension is required for automated testing in Drupal 10 and higher, as well as Aggregator and some contributed modules.</p><p>The <strong>PHP mbstring</strong> extension provides multibyte specific string functions used for Drupal installation in other languages except for English and also multilingual sites in Drupal. It helps deal with multibyte encodings in PHP and also handles Unicode based encoding like UTF-8 or UCS-2.</p><p>3. Memory requirements</p><p><strong>PHP memory requirements</strong> can vary significantly depending on the modules in use on our site. The minimum required memory size is <strong><em>64MB</em></strong>.</p><h3>Composer requirements</h3><p>Drupal 10 will require <strong>Composer 2.3.6 or higher</strong>, since this will be the requirement for using Automatic Updates. Composer can be updated by running composer self-update.</p><h3>Update to 9.4 or 9.5</h3><p>Update your drupal version to 9.4 or 9.5</p><h3>Update contributed projects</h3><p><a href="https://www.drupal.org/project/upgrade_status">Upgrade Status</a></p><p>Go to the following page: <em>/admin/reports/upgrade-status</em> and check the report for your custom modules and themes.</p><p>Update all contributed projects(modules and themes) and ensure they are Drupal 10 compatible. For this, i<strong>nstall Upgrade Status module and run a scan of the modules, both contrib and custom. Check for deprecated modules and uncompatible modules for D10.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzanzmSL0P9jqfMl7H-_tw.jpeg" /></figure><p>Now, check for deprecation errors simillar to image below:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YeyMYBOVPgWoy2UOJDIntA.png" /></figure><p>There will be a case, when certain contrib modules are not yet compatible with Drupal 10. In that scenario, check for any related and available patches related for the particular module on drupal.org.</p><p>we have a <a href="https://github.com/mglaman/composer-drupal-lenient">Composer plugin</a> that will let you install modules that are not yet D10-ready. First, install the plugin: composer require mglaman/composer-drupal-lenient. It let&#39;s you install modules.</p><p>Then add module to the allowed list by executing another Composer command:</p><pre>composer config --merge --json extra.drupal-lenient.allowed-list &#39;[&quot;drupal/commerce_giftcard&quot;]&#39;</pre><p>Finally, check for a patch that will make the module D10-ready on drupal.org. If no patch is available, try to create your on patch on drupal.org</p><p><a href="https://www.drupal.org/docs/develop/git/using-git-to-contribute-to-drupal/working-with-patches/making-a-patch">Making a patch</a></p><p>Or create your local <strong>patches</strong> folder in your project folder beside web or docroot folder. Add your patch file in this folder.</p><pre>&quot;extra&quot;: {<br> &quot;drupal-scaffold&quot;: {<br> &quot;locations&quot;: {<br> &quot;web-root&quot;: &quot;docroot/&quot;<br> }<br> },<br> &quot;enable-patching&quot;: false,<br> &quot;patches&quot;: {<br>  &quot;drupal/commerce_giftcard&quot;: {<br>              &quot;Drupal 10 compatibility issue&quot;: &quot;./patches/commerce_gift_card.patch&quot;<br>   },<br>}</pre><p>Fix your custom modules and fix the deprecated code.</p><p>Once your contrib and custom modules and themes are fixed as per Drupal 10 compatibility and Upgrade status is showing 100%, you are ready to go to the next step.</p><h3>Upgrade to D10 using Composer</h3><p>Use the below command to set folder permissions before upgrading.</p><pre>chmod 777 web/sites/default<br>chmod 666 web/sites/default/*settings.php<br>chmod 666 web/sites/default/*services.yml</pre><p>Use the below command if you want to upgrade to version 10.0.0.</p><pre>composer require &#39;drupal/core-recommended:10.0.0&#39; &#39;drupal/core-composer-scaffold:10.0.0&#39; &#39;drupal/core-project-message:10.0.0&#39;</pre><p>If you have drupal/core-dev installed:</p><pre>composer require &#39;drupal/core-dev:^10&#39; --dev --update-with-dependencies --no-update</pre><p>Now, perform the update to the code itself:</p><pre>composer update</pre><p>Run any pending database updates, required if you update module code and that module needs to update the database, either by visiting update.php in the browser, or with Drush:</p><p>drush updatedb</p><p>When complete, restore read-only access to the sites/default directory:</p><p>chmod 755 web/sites/default chmod 644 web/sites/default/*settings.php chmod 644 web/sites/default/*services.yml</p><p>At this stage, we are done with all the essential steps to upgrade to D10. Now to your website admin and you will see new fresh Drupal 10 interface.</p><p>Go to /admin/reports/updates, to check the status report of your Drupal 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YemBQUbpTtIwx2wYyDEDlQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be962605b6ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Post Migration and Pre Migration Events in Drupal.]]></title>
            <link>https://kushaler2010.medium.com/using-post-migration-and-pre-migration-events-in-drupal-8ba75bc7444e?source=rss-3e1200b23dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba75bc7444e</guid>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[data-migration]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[drupal-9]]></category>
            <dc:creator><![CDATA[Kushal Bansal]]></dc:creator>
            <pubDate>Tue, 13 Dec 2022 10:53:38 GMT</pubDate>
            <atom:updated>2022-12-13T10:53:38.290Z</atom:updated>
            <content:encoded><![CDATA[<p>Since Drupal 8 was launched migration became an essential feature in most of the websites which were using versions greater than Drupal 7. It could be an one time migration from Drupal lower versions to a higher version, or a regular cron job running your migrations in sync from an external api source or files. While doing this migration process, sometime there is a requirement to achieve a <strong>Pre migration functionality or Post migration</strong> <strong>functionality</strong>. For example: we are doing <strong>migration of paragraphs(importing api data into paragraphs) </strong>and once the migration is finished, we want these paragraphs to be referenced automatically to nodes of a <strong>Content type Article</strong> depending on some <strong>Title</strong> field of the node, which matches with the one of the parameters in migrated source data. There could be many ways to achieve this functionality but using Events and Event Subscribers in Symfony based Drupal versions in one of the cleanest way to do this. We can use Post Migration Event in above scenario.</p><p><strong>For a quick reference, these are the events we can use during migration:</strong></p><ol><li>MAP_SAVE — This event allows modules to perform an action whenever the disposition of an item being migrated is saved to the map table.</li><li>MAP_DELETE — This event allows modules to perform an action whenever a row is deleted from a migration’s map table (implying it has been rolled back).</li><li>PRE_IMPORT — This event allows modules to perform an action whenever a migration import operation is about to begin.</li><li>POST_IMPORT — This event allows modules to perform an action whenever a migration import operation is completing.</li><li>PRE_ROW_SAVE — This event allows modules to perform an action whenever a specific item is about to be saved by the destination plugin.</li><li>POST_ROW_SAVE — This event allows modules to perform an action whenever a specific item has been saved by the destination plugin.</li><li>PRE_ROLLBACK — This event allows modules to perform an action whenever a migration rollback operation is about to begin.</li><li>POST_ROLLBACK — This event allows modules to perform an action whenever a migration rollback operation is completing.</li><li>PRE_ROW_DELETE — This event allows modules to perform an action whenever a specific item is about to be deleted by the destination plugin.</li><li>POST_ROW_DELETE — This event allows modules to perform an action whenever a specific item has been deleted by the destination plugin.</li><li>IDMAP_MESSAGE — This event allows modules to perform an action whenever a message is being logged by the ID map.</li></ol><p><strong>Creating an Event Subscriber</strong></p><ol><li>To create an event subscriber, you will create both an EventSubscriber class and an entry in your module’s services.yml file.<strong>The my_module.services.yml file:</strong></li></ol><pre>services:<br>  migration_subscriber:<br>    class: Drupal\MY_MODULE\EventSubscriber\MyModuleMigrationSubscriber<br>    tags:<br>      - { name: &#39;event_subscriber&#39; }</pre><ol><li>In your module create the following directory structure: “src/EventSubscriber”. Then create a file for the subscriber that is descriptive in its purpose. Keep in mind that a subscriber can “subscribe” to one or more events. Meaning the same class can handle the “POST_IMPORT” event and the “PRE_ROLLBACK” event or all of the events if you wish. Often, a preference is to have one class per event that you are subscribing to so that you make it easier to find and troubleshoot problems when they occur. Keeps things isolated.</li><li>In this case, create a file that is called “MyModuleMigrationSubscriber.php”. With a class of the same name within it (see example below). Then within that you create a getSubscribedEvents function and return an array of the events your class will act on and associate each event with a function within your class. Then declare each function and take the needed actions. The below example is really used on a production website right now (though names have been changed to protect witnesses).</li><li>After you have created your subscriber class you just need to add a reference to it in your module’s services.yml file (see example below). Then finally clear cache to get it recognized.</li><li><strong>Class MyModuleMigrationSubscriber.php:</strong></li></ol><pre>&lt;?php</pre><pre>namespace Drupal\MY_MODULE\EventSubscriber;</pre><pre>use Drupal\migrate\Event\MigrateEvents;<br>use Drupal\migrate\Event\MigrateImportEvent;<br>use Symfony\Component\EventDispatcher\EventSubscriberInterface;</pre><pre>/**<br> * Class PreMigrationSubscriber.<br> *<br> * Run a test to validate that the server is available.<br> *<br> * @package Drupal\YOUR_MODULE<br> */<br>class MyModuleMigrationSubscriber implements EventSubscriberInterface {</pre><pre>  /**<br>   * Get subscribed events.<br>   *<br>   * @inheritdoc<br>   */<br>  public static function getSubscribedEvents() {<br>    $events[MigrateEvents::PRE_IMPORT][] = [&#39;onMigratePreImport&#39;];<br>    $events[MigrateEvents::POST_IMPORT][] = [&#39;onMigratePostImport&#39;];<br>    return $events;<br>  }</pre><pre>  /**<br>   * Check for the image server status just once to avoid thousands of requests.<br>   *<br>   * @param \Drupal\migrate\Event\MigrateImportEvent $event<br>   *   The import event object.<br>   */<br>  public function onMigratePreImport(MigrateImportEvent $event) {<br>    $migration_id = $event-&gt;getMigration()-&gt;getBaseId();</pre><pre>    if (strpos($migration_id, &#39;_products&#39;, -9)) {<br>      $store = \Drupal::service(&#39;tempstore.private&#39;)-&gt;get(&#39;my_module_migrations&#39;);</pre><pre>      if ($this-&gt;checkImageServerStatus(&#39;https://www.TESTDOMAIN.com&#39;)) {<br>        $store-&gt;set(&#39;server_available&#39;, TRUE);<br>      }<br>      else {<br>        $store-&gt;set(&#39;server_available&#39;, FALSE);<br>        $event-&gt;logMessage(&#39;The server is unreachable.&#39;);<br>      }<br>    }<br>  }</pre><pre>  /**<br>   * Checks the status of the image server.<br>   *<br>   * @param string $url<br>   *   The URL to check.<br>   *<br>   * @return bool<br>   *   TRUE if the image server is available, FALSE otherwise.<br>   */<br>  private function checkImageServerStatus($url) {<br>    $headers = @get_headers($url);</pre><pre>    // Use condition to check the existence of URL.<br>    if ($headers &amp;&amp; strpos($headers[0], &#39;200&#39;)) {<br>      return TRUE;<br>    }</pre><pre>    return FALSE;<br>  }</pre><pre>  /**<br>   * Check for our specified last node migration and run our flagging mechanisms.<br>   *<br>   * @param \Drupal\migrate\Event\MigrateImportEvent $event<br>   *   The import event object.<br>   */<br>  public function onMigratePostImport(MigrateImportEvent $event) {<br>    $migration_id = $event-&gt;getMigration()-&gt;getBaseId();</pre><pre>    // Do a little bit of cleanup.<br>    if (strpos($migration_id, &#39;_products&#39;, -9)) {<br>      $store = \Drupal::service(&#39;tempstore.private&#39;)-&gt;get(&#39;my_module_migrations&#39;);<br>      $store-&gt;delete(&#39;server_available&#39;);<br>    }<br>  }</pre><pre>}</pre><p>The above code snippet is taken from <a href="https://www.drupal.org/docs/drupal-apis/migrate-api/migrate-api-overview">https://www.drupal.org/docs/drupal-apis/migrate-api/migrate-api-overview</a>.</p><p>There could be multiple use cases and based on that we need to decide which Migration Event can make our job easy<strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba75bc7444e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading from Drupal 8 to Drupal 9]]></title>
            <link>https://kushaler2010.medium.com/upgrading-from-drupal-8-to-drupal-9-bc804945d875?source=rss-3e1200b23dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc804945d875</guid>
            <category><![CDATA[drupal-8-end-of-life]]></category>
            <category><![CDATA[upgrading-from-d8-to-d9]]></category>
            <category><![CDATA[eol-drupal-8]]></category>
            <category><![CDATA[drupal-8]]></category>
            <dc:creator><![CDATA[Kushal Bansal]]></dc:creator>
            <pubDate>Fri, 03 Sep 2021 02:47:42 GMT</pubDate>
            <atom:updated>2021-09-03T03:22:31.283Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Drupal 8 will reach its end-of-life on November 2, 2021</strong>, before the release of Drupal 9.3.0, due to <a href="https://symfony.com/releases/3.4">Symfony 3’s end-of-life</a>. If you are using Drupal 8, <strong>you must upgrade to Drupal 9.2 before November to keep your site secure</strong>. (Drupal 9.1 security coverage ends shortly after the Drupal 8 end-of-life, so updating to 9.2 directly is best.)</p><p>The above context is taken from drupal.org (https://www.drupal.org/psa-2021-2021-06-29) and which on otherhand has prompted most of us to upgrade our drupal websites from past versions to latest drupal 9 version. Although support for drupal 7 will still be there but since Drupal 8 is built on Symfony Architecture, it becomes necessary to upgrade all drupal 8 websites to Drupal 9 before EOL. From a technical perspective Drupal 9.0.0 is Drupal 8.9.0 with all of the <a href="https://drupalize.me/tutorial/what-is-deprecated-code">deprecated code</a> removed. There are no significant schema changes, or feature additions, that would require a complex upgrade. As long as all of the code in your project is using the current APIs the transition from Drupal 8.9.0 to Drupal 9.0.0 shouldn’t be any more complex then the move from 8.8.x to 8.9.0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjOmHJ_7H0P5y9WRtK-fTA.png" /><figcaption>Image source from <a href="https://drupalize.me/">https://drupalize.me/</a></figcaption></figure><h3>When should I upgrade to Drupal 9?</h3><p>The easiest answer to this is “Upgrade it when your backened or code is ready”</p><p>The primary consideration should be wether or not the contributed modules you rely on, and your own custom modules, are Drupal 9 compatible. Once they are, there is no reason to not upgrade.</p><h3>How should I upgrade?</h3><h3>Prerequisites</h3><ul><li>Your site must be updated to the latest minor version. Upgrades are only supported from the final long term support (LTS) release and one previous (e.g. Drupal 8.8+), not from earlier releases (e.g. Drupal 8.3). Follow the <a href="https://www.drupal.org/docs/updating-drupal/updating-drupal-core-via-composer">update instructions</a>.</li><li>You should upgrade any outdated modules on your site to their latest versions. Older module versions may not express compatibility with Drupal 9.</li><li>Your hosting environment must meet <a href="https://www.drupal.org/docs/system-requirements/php-requirements">the minimum system requirements</a> for the Drupal version you are upgrading to (e.g. PHP 7.4 or later).</li><li>Check if you have deprecated code in your site that was removed in the next major version. Fix any deprecations, if required. The <a href="https://www.drupal.org/project/upgrade_status/">Upgrade Status module</a> can help you with this. You might have to <a href="https://www.drupal.org/docs/updating-drupal/updating-modules-and-themes-using-composer">upgrade several modules</a>.</li><li>Once you are done with upgrading your modules (contrib and custom) to latest D9 stable code without any deprecations, then follow the steps below to update the Drupal core.</li></ul><p>There might be a situation when you face too much deprecated code errors for contributed modules used in your website and might not have much idea about how to resolve it than you can go to that module page and look for Issues logged for that module and find the relevant patch as per your issue. After that apply that patch. If the issue is not in the Queue then create your own patch and apply.</p><p>Below is the drupal.org documentation to apply patch or create one.</p><p><a href="https://www.drupal.org/docs/develop/git/using-git-to-contribute-to-drupal/applying-a-patch-in-a-feature-branch">https://www.drupal.org/docs/develop/git/using-git-to-contribute-to-drupal/applying-a-patch-in-a-feature-branch</a></p><h3>Upgrading a Composer-based Drupal 8 site</h3><p>Perform the following steps from your Drupal 8 site’s root (where composer.json lives).</p><ol><li>Temporarily add write access to protected files and directories:</li></ol><p>chmod 777 web/sites/default chmod 666 web/sites/default/*settings.php chmod 666 web/sites/default/*services.yml</p><p>2. Next, you’ll need to pull in both the Drupal 9 version of core-recommended and dev-dependencies packages as dependencies. We use --no-update to avoid a chicken-and-egg problem with mutual dependencies:</p><p>composer require drupal/core-recommended:^9 drupal/core-composer-scaffold:^9 drupal/core-project-message:^9 --update-with-dependencies --no-update</p><p>If you have drupal/core-dev installed:composer require drupal/core-dev:^9 --dev --update-with-dependencies --no-update</p><p>3.Now, actually perform the update to the code itself:</p><p>composer update</p><p>Note: If any of your packages doesn’t have a release explicitly declared as D9-compatible, you will likely run into a dependency error when trying to update your codebase. There may already be a patch in the issue queue that you can use if you use to ‘upgrade’ the project to be drupal 9 compatible. Please refer to this blog post for more details on how to handle this situation: <a href="https://www.mediacurrent.com/blog/how-fix-catch-22-problem-drupal-9-fixes-composer/">https://www.mediacurrent.com/blog/how-fix-catch-22-problem-drupal-9-fixe...</a></p><p>Another, less recommended way to get around this, is you can add an alias to drupal/core, such as:</p><p>composer require &quot;drupal/core:9.0.0 as 8.9.0&quot; --no-update &amp;&amp; composer update</p><p>(Make sure you replace 9.0.0 and 8.9.0 to whatever versions you are using in your installation.). This can lead to problems with modules that are *explicitly* d9 only, as they will not work in this scenario, but it might get you past where you need to be.</p><p>4. Run any pending database updates, required if you update module code and that module needs to update the database, either by visiting update.php in the browser, or with Drush:drush updatedb</p><p>5. When complete, restore read-only access to the sites/default directory:</p><p>chmod 755 web/sites/default chmod 644 web/sites/default/*settings.php chmod 644 web/sites/default/*services.yml</p><p>If you did run to include core 9.0 as 8.9 make sure to change the entry after a successful upgrade in your composer.json file. Otherwise you won&#39;t be able to install any Drupal updates.</p><p>&quot;drupal/core&quot;: &quot;^9.0.0&quot;,</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc804945d875" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>