使用变量到DataTables服务器端列值Formatter

时间:2016-05-31 12:46:01

标签: php datatables server-side

我想通过服务器端Formatter在DataTables的每个单元格上传递PHP函数,但PHP函数是动态的。以下是示例代码:

$func_apply = $_GET['function_name']; // trim | strip_tags | md5 | ucwords

$columns[] = array(
'db'        => $field,
'dt'        => '3',
'formatter' => function( $d, $row ) {
                return $func_apply($d);
            }
);

但是这样我得到PHP错误未定义变量:$ func_apply 如果我把全局$ func_apply;在匿名函数中,它会给出致命错误:函数名必须是...中的字符串

1 个答案:

答案 0 :(得分:2)

我已使用PHP闭包解决了这个问题:

public class WhoopNavigationActivity extends AppCompatActivity
    implements FeedFragment.OnFragmentInteractionListener, NetworkFragment.OnFragmentInteractionListener,
    ProfileFragment.OnFragmentInteractionListener, NetworkNewModal.NetworkNewModalListener {

    SaveStateParams saveStateParams = new SaveStateParams();
    ServerPost serverPost = new ServerPost();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_whoop_navigation);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final FragmentsPagerAdapter fragmentsPagerAdapter = new FragmentsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        final ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(fragmentsPagerAdapter);

        // View of activity
        View view = findViewById(android.R.id.content);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

        tabLayout.setupWithViewPager(mViewPager);
    }

    public static class FragmentsPagerAdapter extends FragmentStatePagerAdapter {

        // Constructor
        public FragmentsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch(position) {
                case 0:
                    return FeedFragment.newInstance();
                case 1:
                    return NetworkFragment.newInstance();
                case 2:
                    return ProfileFragment.newInstance();
            }
            return null;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        public int getItemPosition(Object item) {
            // Causes adapter to reload all Fragments when notifyDataSetChanged is called
            return POSITION_NONE;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Feed";
                case 1:
                    return "Network";
                case 2:
                    return "Profile";
            }
            return null;
        }

    }
}