Is this a correct syntax or correct approach?
function formGroups($forms)
{
$g_education = $form->groups()->create(['name' => 'Education']);
$g_engagement = $form->groups()->create(['name' => 'Engagement in early childhood education']);
return[$g_education, $g_engagement];
}
private function forms()
{
$form = $this->period('B4 school', 5, 'year', 1, 'year')->periodDomains()->create(['domain_id' => $this->domains()->getKey()]);
return $form;
}
protected function test($formGroup)
{
return $this->$formGroup;
}
$form = $this->forms(); //passing the forms() value to $form
$formGroup = array($this->formGroups($form));
$this->educations($formGroup);
$this->engagements($formGroup);
I wanted to pass the value to $formGroup so that I can use the values from the other classes. I am currently getting an error while doing it. Is this the right syntax?
Related
I'm having one more problem in the logical realm.
I have an array containing ids:
$product_ids = ['1', '5', '3']; <- Example
Another string that I convert to an array separating it by commas, this to indicate the quantities of the products to be withdrawn. For example for product 1 I want 3 drives so I would need the array element to be "1,3".
$finalarray = ["1,3", "5,2", "3,10"];
Next I indicate the code that is executed in the controller (where is what I previously told):
public function ordenform(Request $request)
{
$input = $request->all();
$request->validate([
'nombre' => 'required|string',
'apellido' => 'required|string',
'productos' => 'required',
'cantidades' => 'required|string',
'enviosino' => 'required|in:si,no',
]);
// Quantity Array
$cantidades = explode(',', $input['cantidades']);
if (count($cantidades) != count($input['productos'])) {
return back()->withErrors(['Las cantidades no corresponden a los productos agregados']);
}
$total = 0;
$ganancia = 0;
foreach ($input['productos'] as $producto) {
$producto = Product::find((int) $producto);
$total += $producto->value;
$ganancia += $producto->ganancia;
$producto->stock = (int) $producto->stock - 1;
$producto->save();
}
if ($input['enviosino'] == 'si') {
$total += (int) $input['envio'];
}
if ($input['envio'] == null) {
$input['envio'] = 0;
}
// Products IDS Array
$jsonproductos = json_encode($input['productos']);
Order::create([
'nombre' => $input['nombre'],
'apellido' => $input['apellido'],
'product_ids' => $finalprods,
'value' => $total,
'ganancia' => $ganancia,
'envio' => $input['envio'],
]);
$caja = Config::where('id', 1)->get()->first();
$caja->dinerototal += $total;
$caja->gananciatotal += $ganancia;
$caja->save();
return back()->with('success', 'Orden creada correctamente');
}
Finally, I need to pass as creation parameter the final array to the column products_ids (later I will modify the name).
Another option I thought of is passing objects to an array:
[{id: 1, quantity: 3}]
But I don't know how to get to create that object, I'm still kind of new hehe.
I hope I have explained myself well, English is not my native language. I'm sorry.
I am attentive to your comments !! Greetings.
PS: I am using Laravel
To achieve [{id: 1, quantity: 3}] there will be several idea, but it seems to be an arrayList, so below is how you can create an arrayList in PHP. I have not tested the code, just written here, but should give you the idea to achieve this.
I am considering one is Order class.
<?php
class Order {
private $id;
private $quantity;
public function setId(int $id) {
$this->id = $id;
return $this;
}
public function getId(){
return $this->id;
}
public function setQuantity(int $quantity) {
$this->quantity = $quantity;
return $this;
}
public function getQuantity(){
return $this-> quantity;
}
public function toArray(){
return [
'id' => $this->getId(),
'quantity' => $this->getQuantity()
];
}
}
?>
another is OrderList.
<?php
class OrderList {
private $orderList;
public function __construct(Order ...$orders) {
$this->orderList = $orders;
}
public function toArray(){
$arr = [];
foreach ($this->orderList as $order) {
$arr[] = $order->toArray();
}
return $arr;
}
}
?>
and then use like
$order1 = new Order();
$order1 = $order1->setId(1)->setQuantity(10);
$order2 = new Order();
$order2 = $order1->setId(2)->setQuantity(20);
$orderList = new OrderList($order1, $order2);
var_dump(json_encode($orderList->toArray()));
//Output
string(47) "[{"id":2,"quantity":20},{"id":2,"quantity":20}]"
You do not need json_encode, I have added it to print only.
Nevermind, resolved ->
$prodsfinal = array();
for ($i = 0; $i < sizeof($cantidades); $i++) {
$array = [
'id' => json_decode($input['productos'][$i]),
'cantidad' => (int) $cantidades[$i],
];
array_push($prodsfinal, $array);
}
I am coding in Laravel, How can I pass variable to one function to another function in Controller,
In controller file I have 2 functions like this
public function hiringEmployee(Request $request)
{
$hireEmployee = new EmployeeHire();
$hireEmployee->candidateName = $request->get('candidateName');
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/cv', $name);
$hireEmployee->file = $name;
$hireEmployee->save();
return redirect('list-candidate');
}
public function assignInterview(Request $request, $id)
{
$assignInterview = EmployeeHire::find($id);
$interview = $request->get('interview');
$assignto = $request->get('assignto');
$dateTime = $request->get('dateTime');
$note = $request->get('note');
$interviewDetails = ([
'interview' => $interview,
'assign_to' => $assignto,
'date_time' => $dateTime,
'note' => $note,
]);
$assignInterview->interview_details = $interviewDetails;
$assignInterview->save();
Mail::send('emails.hireemployee', ['candidateName' => $candidateName], function ($message) use ($assignto, $name) {
$message->subject('Interview For New Candidate!');
$message->from('hrm#wcg.com', 'HRM');
$message->to($mail);
$message->attach('uploads/cv/'.$name);
});
return redirect('list-candidate');
}
I want to use $candidateName and $name in assignInterview() function from hiringEmployee() function.
How can I do it?
You won't be able to use the $name and $candidateName directly from the other function as they look like they are for two different requests, however, it looks like you're saving that data to database when you're creating a new EmployeeHire in your hiringEmployee() method so you should already have access to that information in your assignInterview() method:
$assignInterview = EmployeeHire::find($id); // this is where you loading the model
$candidateName = $assignInterview->candidateName;
$name = $assignInterview->file;
In your situation , you can use two approach:
#1
Use Session Variable as below:
Session::put('candidateName', $candidateName);
Then:
$value = Session::get('candidateName');
#2
Use class attribute:
class acontroller extends Controller
{
private $classCandidateName;
}
You can try something like this:
public function hiringEmployee(Request $request)
{
$hireEmployee = new EmployeeHire();
$hireEmployee->candidateName = $request->get('candidateName');
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/cv', $name);
$hireEmployee->file = $name;
$hireEmployee->save();
return redirect('list-candidate');
}
public function assignInterview(Request $request, $id)
{
$assignInterview = EmployeeHire::find($id);
if(is_null($assignInterview)){
return redirect()->back()->withErrors(['Error message here']);
}
$interviewDetails = ([
'interview' => $request->get('interview'),
'assign_to' => $request->get('assignto'),
'date_time' => $request->get('dateTime'),
'note' => $request->get('note'),
]);
$assignInterview->interview_details = $interviewDetails;
$assignInterview->save();
Mail::send('emails.hireemployee', ['candidateName' => $assignInterview->candidateName], function ($message) use ($assignto, $assignInterview->file) {
$message->subject('Interview For New Candidate!');
$message->from('hrm#wcg.com', 'HRM');
$message->to($mail);
$message->attach('uploads/cv/'.$assignInterview->file);
});
return redirect('list-candidate');
}
Please, you should to be careful with find($id). If it is a null, you will get an error.
Have fun!
In ZF2, I have a custom form element factory. It creates a custom MultiCheckbox and fills the checkbox values and labels from a db query.
class MyMultiCheckboxFactory
{
public function __invoke(FormElementManager $formElementManager)
{
$multiCheck = new \Zend\Form\Element\MultiCheckbox();
$serviceManager = $formElementManager->getServiceLocator();
$mapper = $serviceManager->get('Path\To\Mapper\To\Query\DB');
$descriptions = $mapper->findDescriptions($id);
// some processing to prepare $value_options array
$multiCheck->setOptions([
'label' => 'blah-blah',
'value_options' => $value_options
]);
return $multiCheck;
}
}
My problem is as follows. The method findDescriptions($id) depends on the $id which I can get from the route. But when I use MyMultiCheckbox in the form like this:
public function init()
{
$this->add([
'type' => 'Path\To\MyMultiCheckbox',
'name' => 'someName'
]);
}
I don't know how to pass the $id into the MyMultiCheckbox.
Could anyone help pleeeeeeeeeease?
You can fetch the id via the 'route match' instance inside the factory.
$event = $serviceManager->get('Application')->getMvcEvent();
$id = $event->getRouteMatch()->getParam('id', false);
if (empty($id)) {
throw new ServiceNotCreatedException('id not set!');
}
$descriptions = $mapper->findDescriptions($id);
I am looking for a way to access and change the DATABASE_CONFIG variables, based on user input. Using CakePHP I created a custom datasource, based on the one provided in the docs, to access an external API. The API returns a JSON string containing the 12 most recent objects. I need to be able to change the page number in the API request to get the next 12 results, as well as accept a free text query entered by the user.
app/Config/Database.php
class DATABASE_CONFIG {
public $behance = array(
'datasource' => 'BehanceDatasource',
'api_key' => '123456789',
'page' => '1',
'text_query' => 'foo'
);
}
app/Model/Datasource/BehanceDataSource.php
App::uses('HttpSocket', 'Network/Http');
class BehanceDatasource extends DataSource {
public $description = 'Beehance datasource';
public $config = array(
'api_key' => '',
'page' => '',
'text_query' => ''
);
public function __construct($config) {
parent::__construct($config);
$this->Http = new HttpSocket();
}
public function listSources($data = null) {
return null;
}
public function describe($model) {
return $this->_schema;
}
public function calculate(Model $model, $func, $params = array()) {
return 'COUNT';
}
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] === 'COUNT') {
return array(array(array('count' => 1)));
}
$queryData['conditions']['api_key'] = $this->config['api_key'];
$queryData['conditions']['page'] = $this->config['page'];
$queryData['conditions']['page'] = $this->config['text_query'];
$json = $this->Http->get('http://www.behance.net/v2/projects', $queryData['conditions']);
$res = json_decode($json, true);
if (is_null($res)) {
$error = json_last_error();
throw new CakeException($error);
}
return array($model->alias => $res);
}
}
Is there anyway to access and change the $behance array, or is there another way to go about accessing an external API with cakePHP that I am totally missing?
Here is the function that find the first exercise with the certain lessonid
public function exerciseAction($lessonid, $exercise)
{
$em = $this->getDoctrine()->getEntityManager();
$exercise = $em->getRepository('PrezentariPrezentariBundle:Exercise')->findOneByLesson($lessonid);
return $this->render('PrezentariPrezentariBundle:Page:exercise.html.twig', array(
'exercise' => $exercise,
'lessonid' => $lessonid,
));
}
Here I try to implement a function to al the exercises one by one
public function exercisePagerAction($exercise)
{
$em = $this->getDoctrine()->getEntityManager();
$nextExercise= $em->getRepository('PrezentariPrezentariBundle:Exercise')->getNext($exercise);
return $this->render('PrezentariPrezentariBundle:Page:exercise.html.twig', array(
'exercise' => $nextExercise,
));
}
Your problem is here:
$nextExercise= $em->getRepository('PrezentariPrezentariBundle:Exercise')->getNext($exercise);
You need to find sth.
$nextExercise= $em->getRepository('PrezentariPrezentariBundle:Exercise')->findOneById($exercise)->getNext();