Skip to main content
amy_yl
Participant
February 27, 2016
Question

Problem passing argument to CFCOMPONENT.

  • February 27, 2016
  • 1 reply
  • 382 views

N00b here making slow headway turning spaghetti code into more suitable code.

I am tinkering with a very simple CFINVOKE of a component. On the page is this:

<cfinvoke

  component="Products"

    method="get_active_products"

    returnvariable="p"

    specificProduct="BA100">

</cfinvoke>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Component Play</title>

</head>

<body>

<p>Hi.</p>

<cfdump var="#p#">

</body>

</html>

And in Product.cfc is this:

<cfcomponent displayname="Active Products CFC" hint="Gets all active catalog products">

<!--- This function gets all the active products and their data from the DB --->

<cffunction name="get_active_products" hint="Gets active products in the database" returntype="query">

<!--- identify arguments --->

<cfargument name="specificProduct" type="string" required="no">

<!--- if we get a value, add it to the query ---> 

<cfif IsDefined(arguments.specificProduct)>

    <cfset whereClause="AND prod_code = " + specificProduct>

    <cfelse>

<!--- and if we don't, just make it blank --->

    <cfset whereClause="">

  </cfif>

<!--- now query for active products... --->

  <cfquery name="get_em" datasource="#application.datasource#"> 

        select * from tblProducts 

        WHERE prod_status != '4' and prod_status != '8' and prod_status != '11'

        #whereClause#

    </cfquery>

<!--- and return the dataset --->    

  <cfreturn get_em>

</cffunction>

</cfcomponent>

HOWEVEVER... It never seems to see arguments.specificProduct as having a value, thus always just returns all products. I've read a lot about CFINVOKE, CFCOMPONENT and all the ways to reference a variable... and tried them all! This is so simple. What's amiss?

Thanks.

This topic has been closed for replies.

1 reply

BKBK
Community Expert
Community Expert
February 27, 2016

1)  Do you happen to have 2 similar CFCs named, respectively, Products and Product? You wrote:

<cfinvoke component="Products"  ...>
And in Product.cfc is this:

2) Arguments.specificProduct is defined (except where the caller passes no argument). So testing for its existence seems partly redundant.


In any case, the line <cfif IsDefined(arguments.specificProduct)> may instead get Coldfusion to test for the existence of a variable named BA100. You could therefore improve the code as follows

<cfargument name="specificProduct" type="string" required="no" default="">



<cfif arguments.specificProduct is not "">

    <cfset whereClause="AND prod_code = " & arguments.specificProduct>

<cfelse>

   <cfset whereClause="">

</cfif>