Forms in html with mysql integration

Im making a whitelist form for a friend. I figured out how to make form with text that gets sent to the database. But I also need few questions with radio buttons. Cant figure it out how to make it send the form info (steamid, email, name) to the database if like 8 out of 10 questions are anwared correctly. Didnt find any information about it on the web, or maybe im just blind.

Too few argument in the istance of class with a dipendency injection in the constructor PHP [duplicate]

I’m starting to study the “dipendency injection”, and i would like start this practice in my project but i’m having some troubles.

I’m creating a custom CMS, and i have a class called “Address”. As obvious, this class interact with the addresses of customer.

That’s provide also to get the city of customer with the costal pode provided. I need an external API to do this, and i decide to integrate a Guzzle for interact with the Api that permits me to acces to this info.

So i thought inject this class in the constructor of my Address class, in this way:

namespace AppAddress;
use GuzzleHttp;

Class Address {

    private $client;
    public function __construct(GuzzleHttpClient $client) {
        $this->client = $client;
    }

where i will do the istance in my index.php, in this way:

<?PHP
use AppAddressAddress;

$address = new Address();

But i still get the error:

Fatal error : Uncaught ArgumentCountError: Too few arguments to function AppAddressAddress::__construct(), 0 passed

I would like have a explication on this, and if i’m using correctly the concept of dipendency injection. Thank you!

MySql query for inserting data in the table is executing two times [closed]

I have made an ecommerce android app.
Whenever I add product in the database table the MySQL query is inserting the same data two times in the table.
I have provided my PHP file and JAVA file .

<?php
$productname = $_POST['productName'];
$productPrice = $_POST['price'];
$desc = $_POST['desc'];
$unit = $_POST['unit'];
$mini = $_POST['minimum'];
$category = $_POST['category'];
$offer = $_POST['offer'];
$image1 = $_POST['img1'];
$image2 = $_POST['img2'];
$image3 = $_POST['img3'];
$image4 = $_POST['img4'];
$image5 = $_POST['img5'];
$sellerId = (Integer) $_POST['seller'];

date_default_timezone_set('Asia/Kolkata');

 $date=date("Y-m-d");
//echo $date;

 $time =date("H:i:s");

$filename1 = rand().".jpg";
file_put_contents("product_images/".$filename1,base64_decode($image1));
$filename2 = rand().".jpg";
file_put_contents("product_images/".$filename2,base64_decode($image2));

if($image3=="non"){
$filename3 ="non";
}else{
$filename3 = rand().".jpg";
file_put_contents("product_images/".$filename3,base64_decode($image3));
}


if($image4=="non"){
$filename4 = "non";

}else{
$filename4 = rand().".jpg";
file_put_contents("product_images/".$filename4,base64_decode($image4));
}


if($image5=="non"){
$filename5 = "non";
}else{
$filename5 = rand().".jpg";
file_put_contents("product_images/".$filename5,base64_decode($image5));
}



include "config.php";
$sql="INSERT INTO `products` (`sellerId`,`productname`, `price`, `unit`, `image1`,                 
`image2`, `image3`,`image4`,`image5`, `description`, `offer`, `category`, `minimum`,     
`inStock`,`date`)
 VALUES ('{$sellerId}','{$productname}', '{$productPrice}', '{$unit}', '{$filename1}', 
 '{$filename2}', '{$filename3}','{$filename4}','{$filename5}','{$desc}', '{$offer}',     
 '{$category}', '{$mini}', '0' , '{$date}')";
$result=mysqli_query($conn,$sql) or die("result failed");
echo "added successfully";
?>

This is the java file. I am adding data throgh volley class and the function name is volleyMethodAddingProduct() .

public class addProductPage extends AppCompatActivity {
RecyclerView imageRecycler;
ImageView camera ;
Toolbar toolbar;
Button add , cancel, gallery;
EditText name , price , desc ,offers , minimum;
ArrayList<String> images = new ArrayList<>();
AutoCompleteTextView catDropdown , unitDropdown;
TextInputLayout DropText , unitText;
private final String url = "https://atttherate.com/Z_getUnits.php";
private final String url2 = "https://atttherate.com/Z_getCategory.php";
private final String url3 = "https://atttherate.com/Z_addProduct.php";

Button retry;

Dialog dialog;

int className;
int getsession;
ArrayList<productImageModal> list;
ArrayList<String> category = new ArrayList<>();
ArrayList<String> unit = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_product_page);
    catDropdown = findViewById(R.id.auto);
    unitDropdown = findViewById(R.id.unit);

    SharedPreferencelogin session = new SharedPreferencelogin(addProductPage.this);
    getsession = session.getSession();

    getUnits();
    getCategories();

    ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(addProductPage.this,     
  R.layout.sampledroptextlayout,category);
    catDropdown.setAdapter(myAdapter);

    ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(addProductPage.this, 
    R.layout.sampledroptextlayout,unit);
    unitDropdown.setAdapter(myAdapter2);


    Intent get = getIntent();
    className = get.getIntExtra("class",-1);

    gallery = findViewById(R.id.addgalleryimg);
    toolbar = findViewById(R.id.toolbaar2);
    add = findViewById(R.id.addSaveProduct);
    cancel = findViewById(R.id.addSavecancel);
    name = findViewById(R.id.addproductName);
    price = findViewById(R.id.addproductPrice);
    desc = findViewById(R.id.addproductDesc);
    offers = findViewById(R.id.addOffer);
    DropText = findViewById(R.id.dropText);
    unitText = findViewById(R.id.dropText2);
    imageRecycler = findViewById(R.id.EditproductImageRecycler);
    minimum = findViewById(R.id.addproductminimum);


    gallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkRequest();
            pick();
        }
    });

    cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String nameText = name.getText().toString().trim();
            String priceText = price.getText().toString().trim();
            String decsText = desc.getText().toString().trim();
            String offersText = offers.getText().toString().trim();
            String catDropdownText = catDropdown.getText().toString().trim();
            String unitDropdownText = unitDropdown.getText().toString().trim();
            String mini = minimum.getText().toString().trim();
            int imagesSize = images.size();


            ConnectivityManager cm = (ConnectivityManager) 
            getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (nameText.equals("") || priceText.equals("") || decsText.equals("") || 
             catDropdownText.equals("") || unitDropdownText.equals("") || 
              mini.equals("") ) {
                Toast.makeText(addProductPage.this,"Fill up all required 
           feilds",Toast.LENGTH_SHORT).show();
            }else {
                if (null == netInfo) {
                    dialog = new Dialog(addProductPage.this);
                    dialog.setContentView(R.layout.dialoglayout);
                    
            
           dialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.dialogback));
                    dialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, 
            ViewGroup.LayoutParams.WRAP_CONTENT);
                    dialog.setCancelable(false);
                    dialog.show();
                    retry = dialog.findViewById(R.id.Retry);
                    retry.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            recreate();
                        }
                    });

                } else {
                    if (offers.getText().toString().isEmpty() || 
            Double.valueOf(offers.getText().toString().trim()) == 0) {
                        offers.setText("no");
                    }
                    volleyMethodAddingProduct();
                    Intent intent = new Intent(addProductPage.this, 
       SellerAddedProductConfirm.class);
                    intent.putExtra("class" , className);
                    startActivity(intent);
                }
            }

        }
    });
   }


private void pick(){
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT,  
   android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE , true);
    intent.setType("image/*");
    launcher.launch(intent);
}

private String encodeBitmapImage(Bitmap bitmap){

    ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG,70,byteArrayOutputStream);
    byte[] bytesofimage=byteArrayOutputStream.toByteArray();
    String tring= android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
    return tring;

}

    ActivityResultLauncher<Intent> launcher = registerForActivityResult(new 
  ActivityResultContracts.StartActivityForResult(), new 
    ActivityResultCallback<ActivityResult>() {
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onActivityResult(ActivityResult result) {
        if (result != null && result.getResultCode() == RESULT_OK) {
            list = new ArrayList<>();
            ClipData clips = result.getData().getClipData();

            images.add(0,"non");
            images.add(1,"non");
            images.add(2,"non");
            images.add(3,"non");
            images.add(4,"non");


            if (clips !=null) {
                if (6 > clips.getItemCount() && 1 < clips.getItemCount()) {
                    if (clips != null) {
                        for (int i = 0; i < clips.getItemCount(); i++) {

                            Uri imgUri = clips.getItemAt(i).getUri();
                            try {
                                Bitmap bitmap = 
    MediaStore.Images.Media.getBitmap(addProductPage.this.getContentResolver(), imgUri);
                                String str = encodeBitmapImage(bitmap);
                                images.set(i,str);

                                ByteArrayOutputStream bytes = new 
  ByteArrayOutputStream();
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bytes);
                                String path = 
MediaStore.Images.Media.insertImage(addProductPage.this.getContentResolver(), bitmap, 
  "image", "val");
                                byte[] bytee = bytes.toByteArray();
                                list.add(new productImageModal(bytee));
                            } catch (Exception e) {

                            }

                        }


                    } else {
                        Toast.makeText(addProductPage.this, "No image 
   founddddddddddddddddd", Toast.LENGTH_LONG).show();
                    }


                } else {
                    Toast.makeText(addProductPage.this, "Select minimum 3 images and 
  maximum 5 images", Toast.LENGTH_LONG).show();
                    pick();
                }
            }else {
                Toast.makeText(addProductPage.this, "Select minimum 3 images and maximum 
    5 images", Toast.LENGTH_LONG).show();
                pick();
            }


            imageRecycler = findViewById(R.id.EditproductImageRecycler);
            productImageAdapter adapter = new productImageAdapter(list, 
   addProductPage.this);
            imageRecycler.setAdapter(adapter);
            LinearLayoutManager layout = new LinearLayoutManager(addProductPage.this, 
   LinearLayoutManager.VERTICAL, false);
            imageRecycler.setLayoutManager(layout);

        }
    }

  });



private boolean checkRequest(){

    if(Build.VERSION.SDK_INT >= 23){
        int camera = ActivityCompat.checkSelfPermission(addProductPage.this , 
    Manifest.permission.CAMERA);
        int write = ActivityCompat.checkSelfPermission(addProductPage.this, 
 Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if(camera == PackageManager.PERMISSION_DENIED && write == 
  PackageManager.PERMISSION_DENIED){
            ActivityCompat.requestPermissions(addProductPage.this , new String[] 
     {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE} , 2);
            return  false;
        }

    }

    return true ;
  }


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 
    @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if(requestCode==2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && 
   grantResults[1] == PackageManager.PERMISSION_GRANTED){
        pick();
    }else{
        Toast.makeText(addProductPage.this, "Not granted " , Toast.LENGTH_LONG).show();
    }
}


public void getCategories(){
    ArrayList<frontCategoryModal> catArray = new ArrayList<>();

    StringRequest request = new StringRequest(Request.Method.POST, url2, new 
   Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject Jobject = new 
      JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
                String success = Jobject.getString("success");
                JSONArray Jarray = Jobject.getJSONArray("datas");
                if(success.equals("1")) {
                    for (int i = 0; i < Jarray.length(); i++) {
                        JSONObject object = Jarray.getJSONObject(i);
                        String name = object.getString("name");
                        String image = object.getString("image");
                        int id = object.getInt("id");
                        String imgUrl = "https://atttherate.com/category_images/"+image;

                        category.add(name);
                    }
                }

            } catch (JSONException jsonException) {
                jsonException.printStackTrace();
            }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }


    });

    RequestQueue queue = Volley.newRequestQueue(addProductPage.this);
    queue.add(request);
};


public void getUnits(){
    ArrayList<frontCategoryModal> catArray = new ArrayList<>();

    StringRequest request = new StringRequest(Request.Method.POST, url, new 
     Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject Jobject = new 
     JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
                String success = Jobject.getString("success");
                JSONArray Jarray = Jobject.getJSONArray("datas");
                if(success.equals("1")) {
                    for (int i = 0; i < Jarray.length(); i++) {
                        JSONObject object = Jarray.getJSONObject(i);
                        String name = object.getString("name");

                        unit.add(name);
                    }
                }

            } catch (JSONException jsonException) {
                jsonException.printStackTrace();
            }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }


    });

    RequestQueue queue = Volley.newRequestQueue(addProductPage.this);
    queue.add(request);
};



public void volleyMethodAddingProduct() {

    ExecutorService executer = Executors.newSingleThreadExecutor();

    executer.execute(new Runnable() {
        @Override
        public void run() {

            SharedPreferencelogin session = new 
   SharedPreferencelogin(addProductPage.this);
            getsession = session.getSession();

            final String seller = String.valueOf(getsession);
            final String addProductName = name.getText().toString().trim();
            final String addPrice =  price.getText().toString().trim();
            final String addDesc = desc.getText().toString().trim();
            final String addUnit = unitDropdown.getText().toString().trim();
            final String addOffer = String.valueOf(offers.getText().toString().trim());
            final String category = catDropdown.getText().toString().trim();
            final String minimumOrder = minimum.getText().toString().trim();
          

            final String image1 ;
            final String image2 ;
            final String image3 ;
            final String image4 ;
            final String image5 ;

            image1 = images.get(0);
            image2 = images.get(1);
            image3 = images.get(2);
            image4 = images.get(3);
            image5 = images.get(4);

            StringRequest request = new StringRequest(Request.Method.POST, url3, new 
     Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    name.setText("");
                    price.setText("");
                    desc.setText("");
                    unitDropdown.setText("");
                    String success = response;
                    
       Toast.makeText(addProductPage.this,success,Toast.LENGTH_LONG).show();

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            })
            {
                @Override
                protected Map<String, String> getParams() {
                    Map<String,String> map=new HashMap<String, String>();
                    map.put("productName",addProductName);
                    map.put("price",addPrice);
                    map.put("desc",addDesc);
                    map.put("unit",addUnit);
                    map.put("img1",image1);
                    map.put("img2",image2);
                    map.put("img3",image3);
                    map.put("img4",image4);
                    map.put("img5",image5);
                    map.put("minimum",minimumOrder);
                    map.put("offer",addOffer);
                    map.put("category",category);
                    map.put("seller",seller);

                    return map;
                }
            };

            RequestQueue queue = Volley.newRequestQueue(addProductPage.this);
            queue.add(request);
        }

    });
   }

  }

How to get google-cloud-batch working with pubsub for publishing from an API in PHP

Am trying to use the google-cloud-batch daemon as referenced in the PubSub documentation, the documentation seems very sparse, have followed it to a T, set it to publish via batch, the code when publishing is definitely trying to add it to the batchRunner, but there does not seem to be anything going through google-cloud-batch.

Any help would be really useful!

Using the latest version of the google PubSub library.

How can I append a string to a dynamic number value via preg_replace?

I have a string inside another to which I need to append something.

The structure of string is something like this:

$output = "Family: peppers, dimensions: 150 cm, origin: South America, Pot diameter: 14, height with pot: 80";

In that string I need to find Pot diameter and append to its numeric value the string cm. so it will look like

Pot diameter: 14 cm.

In the site it appears like this:

Family: peppers.
Dimensions: 150cm
Origin: South America
Pot diameter: 14
Height with pot: 80

I have been trying to use preg_replace() via

$output = preg_replace("/Pot diameter: [0-9]+/", ' cm.', $output)

but it doesn’t work at all. I can’t figure out how to find a number within given string – an exact number won’t work because it’s used dynamically. Only letters inside this string are static.

I figure out that Source code shows:

<div><br/>
<b>Średnica doniczki: </b>
14<br/>
</div>

Changing to:

$output = preg_replace("/<b>Średnica doniczki: </b> <br/>[0-9]+/", ' cm.', $output);

Dosen’t work either.

split long method in different methods

I have this method:

public function createExcel(Task $task = null, Project $project = null, $projectTitle = null)
    {
        $this->spreadsheet = new Spreadsheet();

        $default_border = array(
            'style' => Border::BORDER_THIN,
            'color' => array('rgb' => '1006A3')
        );

        $style_header = array(
            'borders' => array(
                'bottom' => $default_border,
                'left' => $default_border,
                'top' => $default_border,
                'right' => $default_border,
            ),
            'fill' => array(
                'type' => Fill::FILL_SOLID,
                'color' => array('rgb' => 'E1E0F7'),
            ),
            'font' => array(
                'bold' => true,
                'size' => 16,
            )
        );

        $style_content = array(
            'borders' => array(
                'bottom' => $default_border,
                'left' => $default_border,
                'top' => $default_border,
                'right' => $default_border,
            ),
            'fill' => array(
                'type' => Fill::FILL_SOLID,
                'color' => array('rgb' => 'eeeeee'),
            ),
            'font' => array(
                'size' => 12,
            )
        );

        /**
         * Header information of the excel sheet
         */
        $this->spreadsheet->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Zoekterm')
            ->setCellValue('B1', 'Website')
            ->setCellValue('C1', 'Pagina')
            ->setCellValue('D1', 'Paginatitel')
            ->setCellValue('E1', 'Paginabeschrijving')
            ->setCellValue('F1', 'KvK-nummer')
            ->setCellValue('G1', 'Vestigingsnummer')
            ->setCellValue('H1', 'Adresgegevens');
        $this->spreadsheet->getActiveSheet()->getStyle('A1:H1')->applyFromArray($style_header); // give style to header

        $dataku = [];


        if ($projectTitle == BoolState::TRUE) {
            foreach ($project->tasks as $task)
                if ($task->status_id == TaskStatus::CLOSED)
                    foreach ($task->activeResults as $result)
                        $dataku[] = [$result->task->search_query, $result->page_url, $result->page_link, $result->page_title, $result->page_description, $result->coc_number, $result->branch_code, $result->address];
        } else {
            foreach ($task->activeResults as $result)
                $dataku[] = [$result->task->search_query, $result->page_url, $result->page_link, $result->page_title, $result->page_description, $result->coc_number, $result->branch_code, $result->address];
        }


        $firststyle = 'A2';
        for ($i = 0; $i < count($dataku); $i++) {
            $urut = $i + 2;
            $search_query = 'A' . $urut;
            $page_url = 'B' . $urut;
            $page_link = 'C' . $urut;
            $page_title = 'D' . $urut;
            $page_description = 'E' . $urut;
            $coc_number = 'F' . $urut;
            $branch_code = 'G' . $urut;
            $address = 'H' . $urut;
            $this->spreadsheet->setActiveSheetIndex(0)
                ->setCellValue($search_query, $dataku[$i][0])
                ->setCellValue($page_url, $dataku[$i][1])
                ->setCellValue($page_link, $dataku[$i][2])
                ->setCellValue($page_title, $dataku[$i][3])
                ->setCellValue($page_description, $dataku[$i][4])
                ->setCellValue($coc_number, $dataku[$i][5])
                ->setCellValue($branch_code, $dataku[$i][6])
                ->setCellValue($address, $dataku[$i][7]);

            $laststyle = $page_description;
        }

        $this->spreadsheet->getActiveSheet()->getStyle($firststyle . ':' . $laststyle)->applyFromArray($style_content); // give style to header

        $writer = $this->outType == 'xlsx' ? new PhpOfficePhpSpreadsheetWriterXlsx($this->spreadsheet) : new Xls($this->spreadsheet);
        var_dump($this->stream);
        if (!$this->stream) {
            $writer->save($this->filename);
        } else {
            $this->filename = $this->filename == null ? $this->title : $this->filename;
            $this->cleanOutput();
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Cache-Control: max-age=0');
            header('Content-Disposition: attachment;filename="NVWA HDT ' . ucfirst($projectTitle ? $task->project->description : $task->search_query) . '.Xls"'); // file name of excel
            header('Content-type: application/vnd.ms-excel');
            $writer->save('php://output');
            Yii::app()->end();
        }
    }


So the upper part is for then layout of the excel sheet. But is it cleaner to have that in a seperate method?

Thank you

Polylang switcher flag replace

I have replaced my .png file with original file in polylang/flags yet the displaying flag still has source address of :

“data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAMAAABBPP0LAAAAk1BMVEUAiwAAhgAAggAAfQAAdwAAbgAAYQB5ynluxW5mwWZdvl1QuFAASgBFtEUyrDG34rjN6M3Y7tio2Kg8pDz8/Pz+/v749vf6ubn19PTm5ub5l5f2paX6hob3goL85eX61dX1zMz1q6vyw8PzsLDgg4H2AAD8ZGT5QUH3Njb0Kyv0GxvwBwfeAAD6V1f4S0voAADiAACHu6vxAAAAX0lEQVR4AQXBQXKDAAwEMK1xKeSS//80mTJ2pUAiEUFyQkSE9DoIJdjNO5mammxqao7+CbYio0ixu7qVgrLw5JwCfdX3+lyfzpH9+036zu32EsIczUl8haDt6Kcv4cE/X1ocnnuvhQsAAAAASUVORK5CYII=”

Where can I access the folder that plugin is using to show the image? Where is this “data:” folder located?

Symfony, constraint for User

Good day! Just started learning Symfony on my own.

I’m making a news portal. The administrator can download news from an Excel file. I am converting a file to an associative array. For example:

[ 'Title' => 'Some title',
  'Text'  => 'Some text',
  'User'  => '[email protected]',
  'Image' => 'https://loremflickr.com/640/360'
]

Next, I want to send this array to the form and use ‘constraints’ to validate it.
There are no problems with the fields ‘Title’, ‘Text’, ‘Image’. I don’t know how to properly check the ‘User’ field. The user in the file is submitting an Email, but I want to check that a user with that Email exists in the database.

NewsImportType

    class NewsImportType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class, [
                'constraints' =>
                [
                    new NotBlank(),
                    new Length(['min' => 256])
                ],
            ])
            ->add('text', TextareaType::class, [
                'constraints' =>
                [
                    new NotBlank(),
                    new Length(['max' => 1000])
                ],
            ])
            ->add('user', TextType::class, [
                'constraints' =>
                [
                    new NotBlank(),
                    new Email(),
                ],
            ->add('image', TextType::class, [
                'constraints' =>
                [
                    new NotBlank(),
                    new Length(['max' => 256]),
                    new Url()
                ],
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'allow_extra_fields' => true,
            'data_class' => News::class,
        ]);
    }
}

The entities User and News are connected by a One-to-Many relationship.

I was thinking about using ChoiceType and calling UserRepository somehow, but I don’t understand how to apply it correctly.

Please tell me how to correctly write ‘constraint’ for the ‘user’ field.
thank!

How to increment a int with sendinblue api request

I can’t seem to find out how to increment my sendinblue contact field “NBR_SESSIONS” on each time I load a session :

$createContact['attributes'] = array('NBR_SESSIONS'=>+1);

I didn’t find any help or documentation for incrementation for sendinblue api.
Does anyone ever tried to do that simple thing?

how to get the value of dynamic headings with jquery

I am trying to get the value of a dynamic heading.

If I run this code, it shows the list of that ten headings, but my need is, if I click a heading, it should show the value of that particular headings $i value. but it only returning the empty value in the alert.
how can I solve this problem?

<html>
<head>
  <title>
    sample
  </title>
  <script src="jquery.js"></script>
  <script>
    $(document).ready(function() {
      $('.myclass').click(function() {
        alert($(this).val());
      });
    });
  </script>
</head>

<body>
<?php
  for($i = 0; $i < 10; $i++) {
    echo '<h1 class="myclass" value = "'.$i.'"> find my number</h1>';
  }
?>
</body>
</html>`

Why does my custom directive shows parameters error when they are receiving them?

I made a custom conditional directive to determine if a user is allowed or not by the role.

Blade::if('isAllow', function($type, $my_role_id) {
    //dd($type, $my_role_id);
    $rol = Role::where('name', $type)->first();
    return $my_role_id == $rol->id? true : false;
});

I use it this way.

@isAllow('Requestor', Auth()->user()->role_id) All @elseisAllow Reviewed @endisAllow

If into the directive, I do a dd() to see the values, it shows them to me without much problem.

enter image description here

But, when I want to use it in the template, it shows me the following error:

Too few arguments to function AppProvidersAppServiceProvider::AppProviders{closure}(), 0 passed and exactly 2 expected

I can’t find a solution to explain me why is not getting any param when it does. Any help?

Compile Markdown-it with Node.js From PHP

I want to convert markdown to HTML using markdown-it. But I have a Apache server and my server-side language is PHP. Can I give the markdown to Node.js with PHP, compile it there, and get the response in php?

Something like, idk:

$MarkdownContent = "# Hello";
$HtmlContent = nodejs->compile("markdown-it", $MarkdownContent);