Wednesday 10 August 2016

Convert multidimensional array to single dimensional using php


Below is the function to convert multidimensional array into single dimensional array.



function array_flatten($array, $x = NULL) {

        if (!is_array($array)) {
            return false;
        }
        $result = array();

        $x = ($x == '') ? 0 : $x;

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $result = array_merge($result, self::array_flatten($value, $x++));
            } else {
                $result[$x][$key] = $value;
            }
        }
        return $result;

    }



Yii2 href post – Post data using link tag



In Yii2, you can post data using link tag in a form with  data-method post, you can also pass data as params.


Example usage:
Html::a('<i class="fa fa fa-arrow-right"></i> Confirm Details', ['controller/action'], [
                        'class' => 'btn bg-blue btn-flat',
                        'data' => [
                            'method' => 'post',
                            'params' => [
                                'confirm-user' => '1',
                                'user_id' => '10',

                            ],
                        ]
                    ]);

Yii2 from events


In Yii2, below are the form events which we can make use it on front end / client side .

  • beforeValidate,
  • afterValidate,
  •  beforeValidateAttribute,
  • afterValidateAttribute,
  • beforeSubmit,
  •  ajaxBeforeSend,
  • ajaxComplete

Example usage:

$("#FORM-ID").on("afterValidate", function (event, messages) {

    // Now you can work with messages by accessing messages variable
 var attributes = $(this).data().attributes; // to get the list of attributes
    that has been passed in attributes property

  var settings = $(this).data().settings; // to get the settings

});

Yii2 model relation with multiple conditions

In AR Model Relations you can add multiple ON condition using andOnCondition method.
public function getInvoiceItem(){

return $this->hasOne(Invoice::className(), ['order_no' => 'order_no']) 

            ->andOnCondition(['item' => $this->order_item])           

            ->andOnCondition(['user_id' => $this->user_id]);
}