I'm trying to validate the following json file but I can't find the way to access the "Address" child, how should I do it? Everything goes fine until it tries to access the "address" field.
Json:
{
"first_name": "Test",
"last_name": "Test",
"email": "test#gmail.com",
"mobile_phone": 123456789,
"address": {
"country": "Test",
"postal_code": "Test",
"city": "Test",
"street": "Test",
"number": "Test",
"floor": "Test",
"door": "Test"
},
"password": "Test",
"birth_date": "2005-12-30"
}
Code:
$data = $this->validator->validate($request, [
"first_name" => v::stringVal()->notEmpty(),
"last_name" => v::stringVal()->notEmpty(),
"email" => v::notEmpty()->email(),
"mobile_phone" => v::intVal()->notEmpty(),
"address" =>[
"country" => v::stringVal()->notEmpty(),
"postal_code" => v::stringVal()->notEmpty(),
"city" => v::stringVal()->notEmpty(),
"street" => v::stringVal()->notEmpty(),
"number" => v::stringVal()->notEmpty(),
"floor" => v::stringVal()->notEmpty(),
"door" => v::stringVal()->notEmpty(),
],
"password" => v::base64()->notEmpty(),
"birth_date" => v::date()->notEmpty()
]);
Looks like you are using Respect\Validation\Validator. We can make use of chained validation and the Key function to validate sub-arrays as shown in the docs.
$data = [
'parentKey' => [
'field1' => 'value1',
'field2' => 'value2'
'field3' => true,
]
];
Using the next combination of rules, we can validate child keys.
v::key(
'parentKey',
v::key('field1', v::stringType())
->key('field2', v::stringType())
->key('field3', v::boolType())
)
->assert($data); // You can also use check() or validate()
Applied to your data, the validation could look like this:
use Respect\Validation\Validator as v;
$json = json_decode('{
"first_name": "Test",
"last_name": "Test",
"email": "test#gmail.com",
"mobile_phone": 123456789,
"address": {
"country": "Test",
"postal_code": "Test",
"city": "Test",
"street": "Test",
"number": "Test",
"floor": "Test",
"door": "Test"
},
"password": "Test",
"birth_date": "2005-12-30"
}', true);
v::create()
->key('first_name', v::stringType()->length(1, 32))
->key('last_name', v::stringVal()->notEmpty())
//->..
->key('address',
v::key('country', v::stringType()->length(1, 32))
->key('postal_code', v::stringType()->length(1, 32))
->key('city', v::stringType()->length(1, 32))
//->..
)
->key('password', v::stringVal()->notEmpty())
->key('birth_date', v::stringVal()->notEmpty())
->assert($json); // You can also use check() or validate()
That is the way to access the child of the json:
$this->validator->validate($request, [
"first_name" => v::stringVal()->notEmpty(),
"last_name" => v::stringVal()->notEmpty(),
"email" => v::notEmpty()->email(),
"mobile_phone" => v::intVal()->notEmpty(),
"address" => v::notEmpty()
->key("country", v::stringVal()->notEmpty())->key("postal_code", v::stringVal())->key("city", v::stringVal()->notEmpty())->key("street", v::stringVal()->notEmpty())->key("number", v::stringVal())->key("floor", v::stringVal())->key("door", v::stringVal()),
"password" => v::base64()->notEmpty(),
"birth_date" => v::date('d/m/Y')->notEmpty()
]);
Related
I have created an array to convert into json file in php. But as per the requirement I need to assign an array to this array element. it's an array inside an array.
"data" => array( // data array
array(
"event_name" => "Purchase",
"event_time" => time(),
"event_id" => $order_id,
"user_data" => array(
"client_ip_address" => $ip,
"client_user_agent" => $browser,
"em" => $email,
"ph" => $phone,
"fbc" =>$fbp,
"fbp" =>$fbc,
"fn" => $fn,
"ct" => $ct,
"st" => $st,
"zp" => $zp,
"country" => $country,
"external_id" => $email
),
"contents" => $items,
// "id" => $item_ids,
// "quantity" => count($item_qty),
// // "delivery_category"=> "home_delivery",
// "order_id" => $order_id
// ),
"custom_data" => array(
"currency" => "GBP",
"value" => $order_total,
),
"action_source" => "website",
"event_source_url" => $fullURL,
),
)
);
But my $item array look like this when I echo
{
"id": 814,
"order_id": 36956,
"name": "Pearson BTEC Level 7 Certificate in Strategic Management and Leadership (RQF)",
"product_id": 19555,
"variation_id": 0,
"quantity": 2,
"tax_class": "",
"subtotal": "1158",
"subtotal_tax": "0",
"total": "1158",
"total_tax": "0",
"taxes": {
"total": [],
"subtotal": []
},
"meta_data": []
},
{
"id": 815,
"order_id": 36956,
"name": "Pearson BTEC Level 7 Diploma in Strategic Management and Leadership (RQF)",
"product_id": 19107,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "999",
"subtotal_tax": "0",
"total": "999",
"total_tax": "0",
"taxes": {
"total": [],
"subtotal": []
},
"meta_data": []
}
And when I assign this $items and converted to json then I can see only the ides of the array
"user_data": {
"client_ip_address": "2402:d000:a200:a4a8:f06d:40a:cf85:e26d",
"client_user_agent": "",
"em": "b99526fedef7fe1da29e27d6f09cb64efew536978778e6cde3d8277d71a04398d1a4",
"ph": "db80005a39b11372054b7708cac76gsaaww47af6ed3fe4b37b9a8b2be435e2fcff04a7",
"fbc": "",
"fbp": "",
"fn": "83cd072a16ddb3d793c2f5bcd7d0basdree5a04af680279cf6a26fb8dffe57ce3b51a",
"ct": "17a0730b80e55f4bee9569be3f7e6d0wqw500c5568ecb8d785759d7151ef40f5bbd",
"st": "e3b0c44298fc1c149afbf4c8996fb9sas2427ae41e4649b934ca495991b7852b855",
"zp": "ac7bb74de6884ffce919c15fef4193749sdsd4588026c643973946713ac46da540d",
"country": "c820736841e811c96d30b14eb998feb6bsddc2c9d0764b7731267438dc7d6bb5b59",
"external_id": "b99526fedef7fe1da29e27d6f09ssscb64536978778e6cde3d8277d71a04398d1a4"
},
"contents": [
{
"814": {},
"815": {}
}
],
result should be look like this in this way in "centents" element
"contents" : [{'id':'ABC123','quantity' :2,'item_price':5.99}, {'id':'XYZ789','quantity':2, 'item_price':9.99, 'delivery_category': 'in_store'}]
I think the problem is that your $items, is actually an array of "strings" (json)
try to do a json_decode() on those $items before adding it to the content.
anyway, when you ask a question try to remove all unnecessary stuff, and make an example with the minimum code you need help with, in this case it takes a lot of reading through stuff just to understand the issue.
I am trying to modify single field value, but whenever I do it it erases all other fields leaving updated field only, how can I modify a single field witouth affecting the other ones?
so far this is what I'm doing:
//
$updateResult2 = $coll_rutas->updateOne(
/* LIMIT TO ROUTE ID */
[
"_id" => new \MongoDB\BSON\ObjectId($ruta_id)
],
/* UPDATE VALUE */
[
'$set' => [
'destinos.$[d]' => [
"horas" => "1",
"minutos" => "15",
"millas" => "150",
"orden" => "1",
"notas" => "demo notes",
],
],
],
/* WHERE FILTER */
[
"upsert" => true,
'arrayFilters' => [
['d.ciudad_id' => 47]
]
]
);
//var_dump($updateResult2); exit;
This is the original mongo Object:
"destinos": [
{
"ciudad_id": "47",
"nombre_destino": "Salt Lake City, Utah",
"horas": "0",
"minutos": "0",
"millas": "0",
"orden": 1,
"notas": null,
"origenes": [
{
"ciudad_id": "45",
"nombre_origen": "Provo, Utah",
"orden": 1,
"notas": null,
"base_price": 0
}
]
}
],
With my changes it erases origenes array, ciudad_id and nombre destino, leaving it this way:
"destinos": [
{
"horas": "1",
"minutos": "15",
"millas": "150",
"orden": "1",
"notas": "demo notes"
]
}
],
With this code:
'$set' => [
'destinos.$[d]' => [
"horas" => "1",
"minutos" => "15",
"millas" => "150",
"orden" => "1",
"notas" => "demo notes",
],
]
you are targeting the destinos.$[d] element and replacing all of its contents with the new data structure.
You need to use the .(dot) notation to target each element in the nested array. It's a bit verbose but this would work:
'$set' => [
'destinos.$[d].horas' => "1",
'destinos.$[d].minutos' => "15",
'destinos.$[d].millas' => "150",
'destinos.$[d].orden' => "1",
'destinos.$[d].notas' => "demo notes"
]
I add a new contact API - send POST, according to the example below.
https://intranet_name.bitrix24.com/rest/crm.contact.add?auth=authentication_code&fields[NAME]=Maria&fields[SECOND_NAME]=Anna&fields[LAST_NAME]=Nowacka
It adds correctly, works.
I can not deal with the addition of the PHONE array, how to do it?
<script type="text/javascript">
BX24.callMethod(
"crm.contact.add",
{
fields:
{
"NAME": "John",
"SECOND_NAME": "Lancelot",
"LAST_NAME": "Doe",
"OPENED": "Y",
"ASSIGNED_BY_ID": 1,
"TYPE_ID": "CLIENT",
"SOURCE_ID": "SELF",
"PHOTO": { "fileData": document.getElementById('photo') },
"PHONE": [ { "VALUE": "555888", "VALUE_TYPE": "WORK" } ]
},
params: { "REGISTER_SONET_EVENT": "Y" }
},
function(result)
{
if(result.error())
console.error(result.error());
else
console.info("Created a new contact; ID=" + result.data());
}
);
OAuth 2.0 Protocol API documentation
I changed to uURL, it works.
You had to add a square bracket.
$data = array(
"fields" => array(
"NAME" => "Nowy2",
"LAST_NAME" => "Testowy1",
"ADDRESS" => "NowodÄ…browska 45",
"ADDRESS_POSTAL_CODE" => "54-345",
"ADDRESS_CITY" => "Warszawa",
"ADDRESS_COUNTRY" => "Polska",
"TYPE_ID" => "CLIENT",
"PHONE" => array([
"VALUE" => 994556765,
"VALUE_TYPE" => "WORK"]
)
)
);
Forgive my terminology im a newbie in in web dev.
To visualize my question, see below.
This is how RESTLER displays json:
[
{
"id": 1,
"name": "Daniel Craig",
"email": "dc#gmail.com"
},
{
"id": 2,
"name": "Tom Cruise",
"email": "tc#gmail.com"
}
]
This is how i would want RESTLER to display json results:
{"actors":[
{
"id": 1,
"name": "Daniel Craig",
"email": "dc#gmail.com"
},
{
"id": 2,
"name": "Tom Cruise",
"email": "tc#gmail.com"
}
]}
Just wrap your result with another array. if we assume that $result returns the first result above, do the following
$result = array(
array(
"id" => 1,
"name" => "Daniel Craig",
"email" => "dc#gmail.com"
),
array(
"id" => 2,
"name" => "Tom Cruise",
"email" => "tc#gmail.com"
)
);
return array('actors'=>$result);
My contents of MongoDB(when i used find()) is like this:
{
"_id": ObjectId("50072b17b4a6de3b11000001"),
"addresses": [
{
"_id": ObjectId("50072b17b4a6de3b11000004"),
"address1": "770 27th Ave",
"address2": null,
"city": "San Mateo",
"country": "United States",
"country_code": "US",
"name": "home",
"primary": true,
"state": "California",
"zip": "94403"
}
],
"biography": null,
"category_ids": [],
"department": null,
"emails": [
{
"_id": ObjectId("50072b17b4a6de3b11000003"),
"_type": "Email",
"name": "work",
"email": "alan#altimetergroup.com"
}
]
}
What I need to do is I need to update this MongoDB with additional datas's. For that I need to get the values in php as an array and insert that array in to this collection. How to get the values for these specified fields as an array in php and how to insert those in php??
$array = $this->collection->findOne(array('_id' => MONGO_ID));
//Update things
$this->collection->update(array('_id' => $array['_id']), $array);
MONGO_ID in my example should represent the '_id' MongoDB automatically assigns. Make sure it is sent as an Object, and not as a string.
If you want to add another entry, you add an entry like so:
$this->collection->insert($array_of_data, array('safe' => true));
For insert:
$id = new MongoId();
$test->insert(array('t' => 'test', 'email' => array('_id' => $id, 'email' => 'ccc#ccc.com')));
And the result:
{ "_id" : ObjectId("5088cba86527044a31000001"), "t" : "test", "email" : { "_id" : ObjectId("5088cba86527044a31000000"), "email" : "ccc#ccc.com" } }
It works :)