Code issues - orders table field is not updating value

Hey there! I’m encountering an issue with my code. The “formattedText” field in the “saveOrderData” function isn’t updating on the client as expected. Currently, I’m trying to update it from the server using the variable “newFormattedText”, but it seems like something isn’t working correctly. Do you have any ideas about what might be wrong or how I can fix it? Your assistance would be greatly appreciated!

localscript:

-- Define the orders table if it doesn't exist
local orders = {}

-- Function to get order data when buttonYesRequestOrder is pressed
local function saveOrderData()
	-- Gather information about the selected items and calculate total cost
	local selectedItems = {}
	for _, button in ipairs(clickedButtons) do
		local itemName = buttonNames[button.Name]
		if itemName then
			table.insert(selectedItems, itemName)
		end
	end
	local totalCost = calculateTotalPrice()

	-- Create the order object
	local order = {
		username = Players.LocalPlayer.Name, -- Include the username of the player
		item1 = selectedItems[1] or "",
		item2 = selectedItems[2] or "",
		totalprice = totalCost,
		formattedText = ""
	}

	-- Add the order to the orders table
	table.insert(orders, order)

	-- Notify the server about the new order
	orderUpdateEvent:FireServer(order)

	return order -- Return the order table
end

-- Function to process the order data
local function processOrder(orderData)
	-- Process the order by sending it to the server and displaying loading animation
	local totalPrice = calculateTotalPrice()

	if totalPrice > 0 then
		resetOrder()
		ReplicatedStorage.remoteEvents:WaitForChild("close_OrderGUI"):FireServer()
		toggleLoadingOrderSent(true)
		wait(3)
		toggleLoadingOrderSent(false)
		wait(0.2)

		local playerTeamName = Players.LocalPlayer.Team and Players.LocalPlayer.Team.Name
		if playerTeamName == "Customer" then
			local clonedTemplateEvent = game:GetService("ReplicatedStorage").orderTemplate:WaitForChild("clonedTemplateEvent")
			-- Pass order data as parameters to clonedTemplateEvent:FireServer()
			clonedTemplateEvent:FireServer(orderData.username, orderData.item1, orderData.item2, orderData.totalprice, orderData.formattedText)
		else
			print("You are not in the Customer Team.")
		end
		resetButtonColor() -- Reset button color
	else
		warn("There are no items in the order or a template already exists.")
	end
end

-- Connect click event for yes request order button
buttonYesRequestOrder.MouseButton1Click:Connect(function()
	-- Process the order when the "Yes" button is clicked
	local orderData = saveOrderData()
	if orderData then
		print("Order data saved:", orderData)
		processOrder(orderData)
	else
		warn("Failed to save order data.")
	end
end)

server-script:

local clonedTemplateEvent = game:GetService("ReplicatedStorage").orderTemplate:WaitForChild("clonedTemplateEvent")

clonedTemplateEvent.OnServerEvent:Connect(function(player, username, item1, item2, totalPrice, newFormatText)
	local frameTemplate = game:GetService("ReplicatedStorage").orderTemplate.Template

	-- Format the text for the textLabel
	local formattedText

	if item1 and item2 and item2 ~= "" then
		formattedText = "Order by " .. username .. ": " .. item1 .. " and " .. item2 .. ". Your earnings: $" .. totalPrice .. " CB"
	elseif item1 then
		formattedText = "Order by " .. username .. ": " .. item1 .. ". Your earnings: $" .. totalPrice .. " CB"
	else
		warn("No items provided for the order.")
		return
	end

	-- Loop through all players
	for _, plr in ipairs(game.Players:GetPlayers()) do
		if plr.Team and plr.Team.Name == "Chef" then
			-- Clone the frameTemplate into the ScrollingFrame
			local OrdersList_UI = plr:WaitForChild("PlayerGui"):FindFirstChild("OrdersList_UI")
			OrdersList_UI.Enabled = true

			local clonedFrame = frameTemplate:Clone()
			clonedFrame.Parent = OrdersList_UI.Background.ScrollingFrame

			-- Update the textLabel with formatted text
			clonedFrame.TextLabel.Text = formattedText
		else
			warn("Player is not in Chef Team.")
		end
	end
	
	newFormatText = formattedText
end)
2 Likes

I would send back the remote event signal to the clients on team Chef, instead of cloning the UI from the server. Reason being, server to client replication is filtered and won’t properly replicate the changes to the client.

So, in your server-sided script, in the most simplistic way, you would add clonedTemplatedEvent:FireAllClients(yourFormattedText)
and then on the client-sided script, you would check the team of the client / player, then update the text, or whatever you need to do to accomplish that.

Let me know if you need any further advice / assistance.

1 Like

I’ve tried, but it’s still not updating in my orders table. Check it out:

cloned template server script:

local clonedTemplateEvent = game:GetService("ReplicatedStorage").orderTemplate:WaitForChild("clonedTemplateEvent")

clonedTemplateEvent.OnServerEvent:Connect(function(player, username, item1, item2, totalPrice, newFormatText)
	local frameTemplate = game:GetService("ReplicatedStorage").orderTemplate.Template

	-- Format the text for the textLabel
	local formattedText

	if item1 and item2 and item2 ~= "" then
		formattedText = "Order by " .. username .. ": " .. item1 .. " and " .. item2 .. ". Your earnings: $" .. totalPrice .. " CB"
	elseif item1 then
		formattedText = "Order by " .. username .. ": " .. item1 .. ". Your earnings: $" .. totalPrice .. " CB"
	else
		warn("No items provided for the order.")
		return
	end

	-- Loop through all players
	for _, plr in ipairs(game.Players:GetPlayers()) do
		if plr.Team and plr.Team.Name == "Chef" then
			-- Clone the frameTemplate into the ScrollingFrame
			local OrdersList_UI = plr:WaitForChild("PlayerGui"):FindFirstChild("OrdersList_UI")
			OrdersList_UI.Enabled = true

			local clonedFrame = frameTemplate:Clone()
			clonedFrame.Parent = OrdersList_UI.Background.ScrollingFrame

			-- Update the textLabel with formatted text
			clonedFrame.TextLabel.Text = formattedText
		else
			warn("Player is not in Chef Team.")
		end
	end
	
	newFormatText = formattedText
	clonedTemplateEvent:FireAllClients(newFormatText)
end)

full localscript:

-- Import necessary services
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")

-- Get the remote event for updating orders
local orderUpdateEvent = ReplicatedStorage.remoteEvents:WaitForChild("OrderUpdateEvent")

-- Get the player's GUI
local playerGui = Players.LocalPlayer:WaitForChild("PlayerGui")

-- Find the button within the PlayerGui hierarchy
local deliveryOrderButton = playerGui:WaitForChild("Order_Delivery"):WaitForChild("deliveryOrderButton")
local orderTextInfo = playerGui:WaitForChild("Order_Delivery").orderTextInfo

-- Define variables
local buttonsFolder = script.Parent
local hideGuiButton = buttonsFolder.Parent.OrderFrame.NoTextButton
local totalCostTextLabel = buttonsFolder.Parent.OrderFrame.TotalCostText
local buttonYesRequestOrder = buttonsFolder.Parent.OrderFrame.YesTextButton
local textOrdersNames = {
	buttonsFolder.Parent.OrderFrame.OrderName1Text,
	buttonsFolder.Parent.OrderFrame.OrderName2Text
}
local clickedButtons = {}

-- Define buttons and their associated names
local buttonNames = {
	BurgerTextButton = "Burger",
	DonutTextButton = "Donut",
	FriesTextButton = "Fries",
	SliceOfCakeTextButton = "Slice of Cake",
	SodaTextButton = "Soda",
	WaterTextButton = "Water"
}

-- Define prices for each button
local buttonPrices = {
	BurgerTextButton = 5,
	DonutTextButton = 3,
	FriesTextButton = 4,
	SliceOfCakeTextButton = 6,
	SodaTextButton = 2,
	WaterTextButton = 1
}

-- Function to toggle loading order sent GUI
local function toggleLoadingOrderSent(enabled)
	-- Toggle the loading order sent GUI visibility
	Players.LocalPlayer.PlayerGui.loading_order_sent.Enabled = enabled
end

-- Function to update order name displayed
local function updateOrderName(button, index)
	-- Update the displayed order name based on the button clicked
	local orderNameText = textOrdersNames[index]
	if orderNameText then
		orderNameText.Text = button.Text
	end
end

-- Function to calculate total price of selected items
local function calculateTotalPrice()
	-- Calculate the total price of selected items
	local totalPrice = 0
	for _, clickedButton in ipairs(clickedButtons) do
		local price = buttonPrices[clickedButton.Name]
		totalPrice = totalPrice + price
	end
	return totalPrice
end

-- Connect click events for each button
for _, button in pairs(buttonsFolder:GetChildren()) do
	if button:IsA("TextButton") then
		-- Connect click events for each button to handle order selection
		button.MouseButton1Click:Connect(function()
			if #clickedButtons < 2 then
				table.insert(clickedButtons, button)
				updateOrderName(button, #clickedButtons)
				totalCostTextLabel.Text = "Total Cost: $" .. calculateTotalPrice()
				-- Change button background color to green to indicate selection
				button.BackgroundColor3 = Color3.fromRGB(0, 255, 0) -- Green color
			end
		end)
	end
end

-- Function to reset button color
local function resetButtonColor()
	-- Reset the color of all buttons to their original color
	for _, button in ipairs(buttonsFolder:GetChildren()) do
		if button:IsA("TextButton") then
			button.BackgroundColor3 = Color3.fromRGB(211, 211, 211) -- Original color
		end
	end
end

-- Function to reset the order
local function resetOrder()
	-- Reset the order selection and displayed information
	clickedButtons = {}
	for _, orderNameText in ipairs(textOrdersNames) do
		orderNameText.Text = "..."
	end
	totalCostTextLabel.Text = "Total Cost: $0"
end

-- Connect click event for hide GUI button
hideGuiButton.MouseButton1Click:Connect(function()
	-- Reset the order and hide the GUI
	resetOrder()
	ReplicatedStorage.remoteEvents:WaitForChild("close_OrderGUI"):FireServer()
	resetButtonColor() -- Reset button color
end)

-- Define the orders table if it doesn't exist
local orders = {}

-- Function to get order data when buttonYesRequestOrder is pressed
local function saveOrderData()
	-- Gather information about the selected items and calculate total cost
	local selectedItems = {}
	for _, button in ipairs(clickedButtons) do
		local itemName = buttonNames[button.Name]
		if itemName then
			table.insert(selectedItems, itemName)
		end
	end
	local totalCost = calculateTotalPrice()

	-- Create the order object
	local order = {
		username = Players.LocalPlayer.Name, -- Include the username of the player
		item1 = selectedItems[1] or "",
		item2 = selectedItems[2] or "",
		totalprice = totalCost,
		formattedText = ""
	}

	-- Add the order to the orders table
	table.insert(orders, order)

	-- Notify the server about the new order
	orderUpdateEvent:FireServer(order)

	return order -- Return the order table
end

-- Function to check nearby customer
local function checkNearbyCustomer()
	-- Check if there is a customer nearby and return their username if found
	local maxDistance = 15 -- Maximum distance to consider a player as nearby (adjust as needed)
	local player = game.Players.LocalPlayer
	local nearbyCustomer = ""

	for _, otherPlayer in ipairs(game.Players:GetPlayers()) do
		if otherPlayer ~= player and otherPlayer.Team.Name == "Customer" then
			local character = otherPlayer.Character
			if character and character:FindFirstChild("HumanoidRootPart") then
				local distance = (character.HumanoidRootPart.Position - player.Character.HumanoidRootPart.Position).magnitude
				if distance <= maxDistance then
					nearbyCustomer = otherPlayer.Name -- Set the nearby customer username
					break
				end
			end
		end
	end

	return nearbyCustomer
end

-- Function to update the order text based on nearby customer
local function updateOrderText()
	-- Update the order text based on the nearby customer's presence
	local nearbyCustomer = checkNearbyCustomer()
	if nearbyCustomer == "" then
		orderTextInfo.Text = "You are holding the Order of ... in your hands. Place the Tray/Plate on a green spot on the tables."
	else
		orderTextInfo.Text = "You are holding the Order of " .. nearbyCustomer .. " in your hands. Place the Tray/Plate on a green spot on the tables."
	end
end

-- Call the updateOrderText function periodically to keep the order text updated
local function updateOrderPeriodically()
	-- Continuously update the order text to reflect nearby customer presence
	spawn(function()
		while true do
			updateOrderText()
			wait(1)
		end
	end)
end

-- Function to check if the order exists in the orders table
local function checkOrderExists(username)
	-- Check if an order exists for a given username
	print("Checking if order exists for username:", username)
	for _, order in pairs(orders) do
		if order.username == username then
			print("Order found for username:", username)
			return true -- Order found
		end
	end
	print("Order not found for username:", username)
	return false -- Order not found
end

-- Function to process the order data
local function processOrder(orderData)
	-- Process the order by sending it to the server and displaying loading animation
	local totalPrice = calculateTotalPrice()

	if totalPrice > 0 then
		resetOrder()
		ReplicatedStorage.remoteEvents:WaitForChild("close_OrderGUI"):FireServer()
		toggleLoadingOrderSent(true)
		wait(3)
		toggleLoadingOrderSent(false)
		wait(0.2)

		local playerTeamName = Players.LocalPlayer.Team and Players.LocalPlayer.Team.Name
		if playerTeamName == "Customer" then
			local clonedTemplateEvent = game:GetService("ReplicatedStorage").orderTemplate:WaitForChild("clonedTemplateEvent")
			-- Pass order data as parameters to clonedTemplateEvent:FireServer()
			clonedTemplateEvent:FireServer(orderData.username, orderData.item1, orderData.item2, orderData.totalprice, orderData.formattedText)
		else
			print("You are not in the Customer Team.")
		end
		resetButtonColor() -- Reset button color
	else
		warn("There are no items in the order or a template already exists.")
	end
end

-- Connect click event for yes request order button
buttonYesRequestOrder.MouseButton1Click:Connect(function()
	-- Process the order when the "Yes" button is clicked
	local orderData = saveOrderData()
	if orderData then
		print("Order data saved:", orderData)
		processOrder(orderData)
	else
		warn("Failed to save order data.")
	end
end)

-- Start updating the order text periodically
updateOrderPeriodically()
2 Likes

Yeah you’re pretty close, just gotta add a listener on the local script, which listens to the FireClient event from your remote.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.