So I have a method in my class that will create a new lead with a $fields
parameter that the user can pass in the fields.
Let's say I have the following format:
$new_pardot = new FH_Pardot(); $new_pardot->create_prospect();
create_prospect()
The method has $fields
parameters and needs to be passed in an array, so the example is as follows:
$new_pardot->create_prospect([ 'email' => $posted_data['email'], // Make key mandatory or throw error on method. 'firstName' => $posted_data['first-name'], 'lastName' => $posted_data['last-name'], ]);
Is there a way to make the email
key in $fields
mandatory? Users need to pass the email
key, but they can choose to pass other keys as shown above.
Here is the sample method:
public function create_prospect(array $fields) { // Other logic in here. }
P粉0193532472024-01-30 12:35:18
You should create a validation for your $posted_data['email'].
and check if it is required.
But if you want this format, you can try the following:
1- Use separate parameters for email:
public function create_prospect($email,array $fields) { // Other logic in here. }
2-A better approach is to check the email field in an array, with or without an external function:
public function create_prospect(array $fields) { if(!array_key_exists("email", $fields)){ // printing error! => echo 'error' or throw an exception return; } }
P粉6681466362024-01-30 12:20:08
You can verify using one of several methods. The two obvious ways are to validate within the create_prospect
function, or to validate before/outside calling create_prospect
.
The traditional approach is to validate before trying to create the entity. It makes collecting and displaying validation errors easier than throwing validation messages from everywhere.
Withinpublic function create_prospect(array $fields) { if (!isset($fields['email']) { throw new ValidationException('Please provide an email'); } ... carry on with your work }
$fields = [ 'email' => $posted_data['email'], 'firstName' => $posted_data['first-name'], 'lastName' => $posted_data['last-name'], ]; if (!isset($fields['email']) { throw new ValidationException('Please provide an email'); } $new_pardot = new FH_Pardot(); $new_pardot->create_prospect($fields);